Skip to content
This repository has been archived by the owner on Sep 13, 2021. It is now read-only.

Commit

Permalink
Keep validator injection for now (before dropwizard release)
Browse files Browse the repository at this point in the history
  • Loading branch information
alex-shpak committed Nov 8, 2018
1 parent 61b6e53 commit 93bc4c2
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package net.winterly.dropwizard.hk2bundle.validation;

import org.glassfish.hk2.api.ServiceLocator;

import javax.inject.Inject;
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import java.util.function.Consumer;

/**
* Utility jersey feature to get access to ServiceLocator
*/
public class GetLocatorFeature implements Feature {

private final Consumer<ServiceLocator> action;

@Inject
private ServiceLocator serviceLocator;

public GetLocatorFeature(Consumer<ServiceLocator> action) {
this.action = action;
}

@Override
public boolean configure(FeatureContext context) {
action.accept(serviceLocator);
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package net.winterly.dropwizard.hk2bundle.validation;

import io.dropwizard.Bundle;
import io.dropwizard.jersey.validation.Validators;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.glassfish.jersey.server.validation.internal.InjectingConstraintValidatorFactory;
import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorFactoryImpl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorFactory;
import javax.validation.ValidatorFactory;
import javax.ws.rs.container.ResourceContext;

public class InjectValidatorBundle implements Bundle {

private ConstraintValidatorFactory validatorFactory = new ConstraintValidatorFactoryImpl();

@Override
public void initialize(Bootstrap<?> bootstrap) {
ValidatorFactory validatorFactory = Validators.newConfiguration()
.constraintValidatorFactory(new InjectingValidatorFactory())
.buildValidatorFactory();

bootstrap.setValidatorFactory(validatorFactory);
}

@Override
public void run(Environment environment) {
GetLocatorFeature getLocatorFeature = new GetLocatorFeature(serviceLocator -> {
ResourceContext resourceContext = serviceLocator.getService(ResourceContext.class);
validatorFactory = resourceContext.getResource(InjectingConstraintValidatorFactory.class);
});
environment.jersey().register(getLocatorFeature);
}

private class InjectingValidatorFactory implements ConstraintValidatorFactory {

@Override
public final <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
return validatorFactory.getInstance(key);
}

@Override
public void releaseInstance(ConstraintValidator<?, ?> instance) { }
}
}

0 comments on commit 93bc4c2

Please sign in to comment.