I'm trying to intercept requests to my jaxrs apis basead on annotations, my filter is simple:
#Provider
public class Filter implements ContainerRequestFilter {
#Context
private ResourceInfo info;
#Override
public void filter(ContainerRequestContext crc) throws IOException {
// here I'm trying to get the annotate resource class or method.
info.getResourceClass().isAnnotationPresent(MyCustomAnnotation.class);
}
}
this works fine with a simple resource like this: (works both in class and method)
#Path("/")
public class SimpleResource {
#GET
#MyCustomAnnotation
public String test() {
return "test";
}
}
But in my real application, I have scenarios like this:
#Path("/")
public class RootResource {
#Inject
ChildResource childResource;
#Path("child")
public ChildResource child () {
return childResource;
}
}
So, I wanna put my custom annotation only on ResourceLocator and on the fly verify that the final resource contains the annotation.
#Path("/")
#CustomAnnotation
public class RootResource {
#Inject
ChildResource childResource;
#Path("child")
public ChildResource child () {
return childResource;
}
}
is it possible? or i can only get information about the matched resource?
"In jersey how would be this?"
With Jersey you have access to the resource model, and ways to traverse the model. You can see jersey server introspectionmodeller not public in v2.0? for some explanation and examples of how to traverse the model and Resource and ResourceMethod. Other than that, there is not much documentation these APIs.
Below is a complete example Using Jersey Test Framework. You can run the class like any other JUnit test. You just need this one dependency to run it
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>2.19</version>
<scope>test</scope>
</dependency>
And here's the test.
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;
import java.util.logging.Logger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import static junit.framework.Assert.assertEquals;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.server.ExtendedUriInfo;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.model.Resource;
import org.glassfish.jersey.server.model.ResourceMethod;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
public class ResourceModelTest extends JerseyTest {
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
public static #interface ResourceAnnotation {
String value();
}
#Path("root")
#ResourceAnnotation("SomeValue")
public static class ParentResource {
#Path("sub")
public ChildResource getChild() {
return new ChildResource();
}
#GET
public String get() {
return "ROOT";
}
}
public static class ChildResource {
#GET
public String get() {
return "CHILD";
}
}
#Provider
public static class ResourceFilter implements ContainerResponseFilter {
#Override
public void filter(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) throws IOException {
ExtendedUriInfo info = (ExtendedUriInfo) requestContext.getUriInfo();
List<ResourceMethod> resourceLocators = info.getMatchedResourceLocators();
if (!resourceLocators.isEmpty()) {
Resource parent = resourceLocators.get(0).getParent();
Class<?> parentClass = parent.getHandlerClasses().iterator().next();
ResourceAnnotation anno = parentClass.getAnnotation(ResourceAnnotation.class);
if (anno != null) {
responseContext.getHeaders().putSingle("X-SubResource-Header", anno.value());
}
}
}
}
#Override
public ResourceConfig configure() {
return new ResourceConfig(ParentResource.class)
.register(ResourceFilter.class);
}
#Override
public void configureClient(ClientConfig config) {
config.register(new LoggingFilter(Logger.getAnonymousLogger(), true));
}
#Test
public void get_child_resource() {
Response response = target("root/sub").request().get();
assertEquals(200, response.getStatus());
assertEquals("SomeValue", response.getHeaderString("X-SubResource-Header"));
}
}
Related
I want to write a custom deserializer for some parameters in the requests of type application/x-www-form-urlencoded like used in case of requests of type application/json, with #JsonDeserialize(using = AbcDeserializer.class) annotation. I am using spring boot and Jackson, although I figured out that Jackson is not used here.
I tried figuring out how spring deserializes object by default. But couldn't find a way.
How does spring deserialize a request of type application/x-www-form-urlencoded by default?
Can I override this deserialization, preferrably by using some annotation on parameters that need special handling?
My solution is based on custom ConditionalGenericConverter. It works with #ModelAttribute. Let's see whole implementation.
Application bootstrap example.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#SpringBootApplication
public class DemoApplication {
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new Base64JsonToObjectConverter());
}
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Here is custom annotation.
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
#Retention(RetentionPolicy.RUNTIME)
public #interface Base64Encoded {
}
Next we need implementation of the converter. As you can see, converter converts only String -> Object, where Object field must be annotated with Base64Encoded annotation.
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Base64;
import java.util.Collections;
import java.util.Set;
#Component
public class Base64JsonToObjectConverter implements ConditionalGenericConverter {
private final ObjectMapper objectMapper;
private final Base64.Decoder decoder;
public Base64JsonToObjectConverter() {
this.objectMapper = new ObjectMapper();
this.decoder = Base64.getDecoder();
}
#Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
return targetType.hasAnnotation(Base64Encoded.class);
}
#Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(String.class, Object.class));
}
#Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
String string = (String) source;
try {
byte[] decodedValue = this.decoder.decode(string);
return this.objectMapper.readValue(decodedValue, targetType.getType());
} catch (IllegalArgumentException | IOException e) {
throw new ConversionFailedException(sourceType, targetType, source, e);
}
}
}
Here is an example of POJO (see the annotated field) and REST controller.
import com.example.demo.Base64Encoded;
public class MyRequest {
private String varA;
#Base64Encoded
private B varB;
public String getVarA() {
return varA;
}
public void setVarA(String varA) {
this.varA = varA;
}
public B getVarB() {
return varB;
}
public void setVarB(B varB) {
this.varB = varB;
}
}
import com.example.demo.domain.MyRequest;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class DemoController {
#RequestMapping(path = "/test", method = RequestMethod.POST)
public MyRequest test(#ModelAttribute MyRequest myRequest) {
return myRequest;
}
}
Currently I'm rendering a command object in a MessageBodyReader but I'd like to be able to do this in a #BeanParam:
Inject a field derived from the SecurityContext (Is there somewhere to hook in the conversion?).
have a field inject that has been materialised by a MessageBodyReader.
Is this possible ?
Note: Go Down to UPDATE. I guess it is possible to use #BeanParam. Though you need to inject the SecurityContext into the bean and extract the name info.
There's no way to achieve this with #BeanParam corrected. You could use a MessageBodyReader the way you are doing, but IMO that's more of a hack than anything. Instead, the way I would achieve it is to use the framework components the way they are supposed to be used, which involves custom parameter injection.
To achieve this, you need two things, a ValueFactoryProvider to provide parameter values, and a InjectionResolver with your own custom annotation. I won't do much explaining for the example below, but you can find a good explanation in
Jersey 2.x Custom Injection Annotation With Attributes
You can run the below example like any JUnit test. Everything is included into the one class. These are the dependencies I used.
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>2.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.19</version>
<scope>test</scope>
</dependency>
And here is the test
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.security.Principal;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Entity;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import org.glassfish.hk2.api.Factory;
import org.glassfish.hk2.api.InjectionResolver;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.api.TypeLiteral;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.internal.inject.AbstractContainerRequestValueFactory;
import org.glassfish.jersey.server.internal.inject.AbstractValueFactoryProvider;
import org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider;
import org.glassfish.jersey.server.internal.inject.ParamInjectionResolver;
import org.glassfish.jersey.server.model.Parameter;
import org.glassfish.jersey.server.spi.internal.ValueFactoryProvider;
import org.glassfish.jersey.test.JerseyTest;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CustomInjectionTest extends JerseyTest {
#Target(ElementType.PARAMETER)
#Retention(RetentionPolicy.RUNTIME)
public static #interface CustomParam {
}
public static class CustomModel {
public String name;
public RequestBody body;
}
public static class RequestBody {
public String message;
}
public static class CustomParamValueFactory
extends AbstractContainerRequestValueFactory<CustomModel> {
#Override
public CustomModel provide() {
ContainerRequest request = getContainerRequest();
String name = request.getSecurityContext().getUserPrincipal().getName();
RequestBody body = request.readEntity(RequestBody.class);
CustomModel model = new CustomModel();
model.body = body;
model.name = name;
return model;
}
}
public static class CustomValueFactoryProvider extends AbstractValueFactoryProvider {
#Inject
public CustomValueFactoryProvider(MultivaluedParameterExtractorProvider multiProvider,
ServiceLocator locator) {
super(multiProvider, locator, Parameter.Source.UNKNOWN);
}
#Override
protected Factory<?> createValueFactory(Parameter parameter) {
if (CustomModel.class == parameter.getType()
&& parameter.isAnnotationPresent(CustomParam.class)) {
return new CustomParamValueFactory();
}
return null;
}
}
public static class CustomParamInjectionResolver extends ParamInjectionResolver<CustomParam> {
public CustomParamInjectionResolver() {
super(CustomValueFactoryProvider.class);
}
}
private static class CustomInjectBinder extends AbstractBinder {
#Override
protected void configure() {
bind(CustomValueFactoryProvider.class)
.to(ValueFactoryProvider.class)
.in(Singleton.class);
bind(CustomParamInjectionResolver.class)
.to(new TypeLiteral<InjectionResolver<CustomParam>>(){})
.in(Singleton.class);
}
}
private static final String PRINCIPAL_NAME = "peeskillet";
#PreMatching
public static class SecurityContextFilter implements ContainerRequestFilter {
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
requestContext.setSecurityContext(new SecurityContext(){
public Principal getUserPrincipal() {
return new Principal() {
public String getName() { return PRINCIPAL_NAME; }
};
}
public boolean isUserInRole(String role) { return false; }
public boolean isSecure() { return true;}
public String getAuthenticationScheme() { return null; }
});
}
}
#Path("test")
public static class TestResource {
#POST
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.APPLICATION_JSON)
public String post(#CustomParam CustomModel model) {
return model.name + ":" + model.body.message;
}
}
#Override
public ResourceConfig configure() {
return new ResourceConfig(TestResource.class)
.register(SecurityContextFilter.class)
.register(new CustomInjectBinder());
}
#Test
public void should_return_name_with_body() {
RequestBody body = new RequestBody();
body.message = "Hello World";
Response response = target("test").request()
.post(Entity.json(body));
assertEquals(200, response.getStatus());
String responseBody = response.readEntity(String.class);
assertEquals(PRINCIPAL_NAME + ":" + body.message, responseBody);
System.out.println(responseBody);
}
}
Note that I read the request body from the ContainerRequest inside the CustomParamValueFactory. It is the same RequestBody that I sent in JSON from the request in the #Test.
UPDATE
So to my surprise, it is possible to use #BeanParam. Here is the following bean I used to test
public static class CustomModel {
#Context
public SecurityContext securityContext;
public RequestBody body;
}
public static class RequestBody {
public String message;
}
The difference from the previous test is that instead of the name from the SecurityContext.Principal, we need to inject the entire SecurityContext. There's just no way for the inject to get the name from the Principal, So we will just do it manually.
The thing that surprised me the most though, is that we are able to inject the RequestBody entity. I didn't know this was possible.
Here is the complete test
import java.io.IOException;
import java.security.Principal;
import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Entity;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CustomInjectTestTake2 extends JerseyTest {
private static final String PRINCIPAL_NAME = "peeskillet";
private static final String MESSAGE = "Hello World";
private static final String RESPONSE = PRINCIPAL_NAME + ":" + MESSAGE;
public static class CustomModel {
#Context
public SecurityContext securityContext;
public RequestBody body;
}
public static class RequestBody {
public String message;
}
#PreMatching
public static class SecurityContextFilter implements ContainerRequestFilter {
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
requestContext.setSecurityContext(new SecurityContext(){
public Principal getUserPrincipal() {
return new Principal() {
public String getName() { return PRINCIPAL_NAME; }
};
}
public boolean isUserInRole(String role) { return false; }
public boolean isSecure() { return true;}
public String getAuthenticationScheme() { return null; }
});
}
}
#Path("test")
public static class TestResource {
#POST
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.APPLICATION_JSON)
public String post(#BeanParam CustomModel model) {
return model.securityContext.getUserPrincipal().getName()
+ ":" + model.body.message;
}
}
#Override
public ResourceConfig configure() {
return new ResourceConfig(TestResource.class)
.register(SecurityContextFilter.class);
}
#Test
public void should_return_name_with_body() {
RequestBody body = new RequestBody();
body.message = "Hello World";
Response response = target("test").request()
.post(Entity.json(body));
assertEquals(200, response.getStatus());
String responseBody = response.readEntity(String.class);
assertEquals(RESPONSE, responseBody);
System.out.println(responseBody);
}
}
See Also:
Custom Injection and Lifecycle Management
I'm getting Providers from context in my filter to get defined ObjectMapper
public class Filter implements ContainerRequestFilter, ContainerResponseFilter {
#Context
private Providers providers;
#Context
private HttpServletRequest request;
private ObjectMapper getObjectMapper() {
ContextResolver<ObjectMapper> contextResolver = providers.getContextResolver(ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE);
if (contextResolver == null) {
return new ObjectMapper();
}
return contextResolver.getContext(null);
}
}
but in test I can't inject mock in this filter using abstract binder with HttpServletRequest it works fine but Providers isn't mock. Example of test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration({ "..." })
#PrepareForTest({ ... })
public class Test extends JerseyTest {
#Rule
public PowerMockRule rule = new PowerMockRule();
private HttpServletRequest request;
private Providers providers;
#Override
protected Application configure() {
ResourceConfig config = new ResourceConfig(TestResource.class, Filter.class);
providers = mock(Providers.class);
request = mock(HttpServletRequest.class);
config.register(new AbstractBinder() {
#Override
protected void configure() {
bind(providers).to(Providers.class);
}
});
config.register(new AbstractBinder() {
#Override
protected void configure() {
bind(request).to(HttpServletRequest.class);
}
});
return config;
}
Why HttpServletRequest is mock in filter but Providers is not?
Providers shouldn't have to be mocked. It is handled by the framework. Any providers you want added, just register with the ResourceConfig. I don't know what you care doing wrong in your attempt at this, but below is a complete working example where the ContextResolver is discovered just fine.
If you still can't figure it out, please provide a full working single class example (without any mock or Spring stuff) like I have done.
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.Providers;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Assert;
import org.junit.Test;
public class ContextResolverTest extends JerseyTest {
#Provider
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public static class OMContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper = new ObjectMapper();
#Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
}
#Provider
public static class Filter implements ContainerRequestFilter {
#Context
private Providers providers;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
ContextResolver<ObjectMapper> contextResolver
= providers.getContextResolver(ObjectMapper.class,
MediaType.APPLICATION_JSON_TYPE);
if (contextResolver == null) {
requestContext.abortWith(
Response.serverError().entity("no resolver").build());
} else {
ObjectMapper mapper = contextResolver.getContext(null);
if (mapper == null) {
requestContext.abortWith(
Response.serverError().entity("no mapper").build());
return;
}
requestContext.abortWith(
Response.ok("resolver found").build());
}
}
}
#Path("test")
public static class TestResource {
#GET
public String dummyGet() {
return "Boo";
}
}
#Override
public Application configure() {
ResourceConfig config = new ResourceConfig();
config.register(TestResource.class);
config.register(OMContextResolver.class);
config.register(Filter.class);
return config;
}
#Test
public void contextResolverIsOk() {
Response response = target("test").request().get();
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("resolver found", response.readEntity(String.class));
response.close();
}
}
Hello I am building an application using dropwizard, that is using jersey 2.16 internally as REST API framework.
For the whole application on all resource methods I need some information so to parse that information I defined a custom filter like below
#java.lang.annotation.Target(ElementType.PARAMETER)
#java.lang.annotation.Retention(RetentionPolicy.RUNTIME)
public #interface TenantParam {
}
The tenant factory is defined below
public class TenantFactory implements Factory<Tenant> {
private final HttpServletRequest request;
private final ApiConfiguration apiConfiguration;
#Inject
public TenantFactory(HttpServletRequest request, #Named(ApiConfiguration.NAMED_BINDING) ApiConfiguration apiConfiguration) {
this.request = request;
this.apiConfiguration = apiConfiguration;
}
#Override
public Tenant provide() {
return null;
}
#Override
public void dispose(Tenant tenant) {
}
}
I haven't actually implemented the method but structure is above. There is also a TenantparamResolver
public class TenantParamResolver implements InjectionResolver<TenantParam> {
#Inject
#Named(InjectionResolver.SYSTEM_RESOLVER_NAME)
private InjectionResolver<Inject> systemInjectionResolver;
#Override
public Object resolve(Injectee injectee, ServiceHandle<?> serviceHandle) {
if(Tenant.class == injectee.getRequiredType()) {
return systemInjectionResolver.resolve(injectee, serviceHandle);
}
return null;
}
#Override
public boolean isConstructorParameterIndicator() {
return false;
}
#Override
public boolean isMethodParameterIndicator() {
return true;
}
}
Now in my resource method I am doing like below
#POST
#Timed
public ApiResponse create(User user, #TenantParam Tenant tenant) {
System.out.println("resource method invoked. calling service method");
System.out.println("service class" + this.service.getClass().toString());
//DatabaseResult<User> result = this.service.insert(user, tenant);
//return ApiResponse.buildWithPayload(new Payload<User>().addObjects(result.getResults()));
return null;
}
Here is how I am configuring the application
#Override
public void run(Configuration configuration, Environment environment) throws Exception {
// bind auth and token param annotations
environment.jersey().register(new AbstractBinder() {
#Override
protected void configure() {
bindFactory(TenantFactory.class).to(Tenant.class);
bind(TenantParamResolver.class)
.to(new TypeLiteral<InjectionResolver<TenantParam>>() {})
.in(Singleton.class);
}
});
}
The problem is during application start I am getting below error
WARNING: No injection source found for a parameter of type public void com.proretention.commons.auth.resources.Users.create(com.proretention.commons.api.core.Tenant,com.proretention.commons.auth.model.User) at index 0.
and there is very long stack error stack and description
Below is the declaration signature of user pojo
public class User extends com.company.models.Model {
No annotations on User class. Model is a class that defines only single property id of type long and also no annotations on model class
When I remove the User parameter from above create resource method it works fine and when I removed TenantParam it also works fine. The problem only occurs when I use both User and TenantParam
What I am missing here ? how to resolve this error ?
EDITED
I just tried with two custom method param injection, that is also not working
#POST
#Path("/login")
#Timed
public void validateUser(#AuthParam AuthToken token, #TenantParam Tenant tenant) {
}
What I am missing here ? Is this a restriction in jersey ?
Method parameters are handled a little differently for injection. The component we need to implement for this, is the ValueFactoryProvider. Once you implement that, you also need to bind it in your AbstractBinder.
Jersey has a pattern that it follows for implementing the ValueFactoryProvider. This is the pattern used to handle parameters like #PathParam and #QueryParam. Jersey has a ValueFactoryProvider for each one of those, as well as others.
The pattern is as follows:
Instead of implementing the ValueFactoryProvider directly, we extend AbstractValueFactoryProvider
public static class TenantValueProvider extends AbstractValueFactoryProvider {
#Inject
public TenantValueProvider(MultivaluedParameterExtractorProvider mpep,
ServiceLocator locator) {
super(mpep, locator, Parameter.Source.UNKNOWN);
}
#Override
protected Factory<?> createValueFactory(Parameter parameter) {
if (!parameter.isAnnotationPresent(TenantParam.class)
|| !Tenant.class.equals(parameter.getRawType())) {
return null;
}
return new Factory<Tenant>() {
#Override
public Tenant provide() {
...
}
};
}
In this component, it has a method we need to implement that returns the Factory that provides the method parameter value.
The InjectionResolver is what is used to handle the custom annotation. With this pattern, instead of directly implementing it, as the OP has, we just extend ParamInjectionResolver passing in our AbstractValueFactoryProvider implementation class to super constructor
public static class TenantParamInjectionResolver
extends ParamInjectionResolver<TenantParam> {
public TenantParamInjectionResolver() {
super(TenantValueProvider.class);
}
}
And that's really it. Then just bind the two components
public static class Binder extends AbstractBinder {
#Override
public void configure() {
bind(TenantParamInjectionResolver.class)
.to(new TypeLiteral<InjectionResolver<TenantParam>>(){})
.in(Singleton.class);
bind(TenantValueProvider.class)
.to(ValueFactoryProvider.class)
.in(Singleton.class);
}
}
Below is a complete test using Jersey Test Framework. The required dependencies are listed in the javadoc comments. You can run the test like any other JUnit test
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import org.glassfish.hk2.api.Factory;
import org.glassfish.hk2.api.InjectionResolver;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.api.TypeLiteral;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.internal.inject.AbstractContainerRequestValueFactory;
import org.glassfish.jersey.server.internal.inject.AbstractValueFactoryProvider;
import org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider;
import org.glassfish.jersey.server.internal.inject.ParamInjectionResolver;
import org.glassfish.jersey.server.model.Parameter;
import org.glassfish.jersey.server.spi.internal.ValueFactoryProvider;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Stack Overflow https://stackoverflow.com/q/29145807/2587435
*
* Run this like any other JUnit test. Dependencies required are as the following
*
* <dependency>
* <groupId>org.glassfish.jersey.test-framework.providers</groupId>
* <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
* <version>2.22</version>
* <scope>test</scope>
* </dependency>
* <dependency>
* <groupId>org.glassfish.jersey.media</groupId>
* <artifactId>jersey-media-json-jackson</artifactId>
* <version>2.22</version>
* <scope>test</scope>
* </dependency>
*
* #author Paul Samsotha
*/
public class TenantInjectTest extends JerseyTest {
#Target(ElementType.PARAMETER)
#Retention(RetentionPolicy.RUNTIME)
public static #interface TenantParam {
}
public static class User {
public String name;
}
public static class Tenant {
public String name;
public Tenant(String name) {
this.name = name;
}
}
public static class TenantValueProvider extends AbstractValueFactoryProvider {
#Inject
public TenantValueProvider(MultivaluedParameterExtractorProvider mpep,
ServiceLocator locator) {
super(mpep, locator, Parameter.Source.UNKNOWN);
}
#Override
protected Factory<?> createValueFactory(Parameter parameter) {
if (!parameter.isAnnotationPresent(TenantParam.class)
|| !Tenant.class.equals(parameter.getRawType())) {
return null;
}
return new AbstractContainerRequestValueFactory<Tenant>() {
// You can #Inject things here if needed. Jersey will inject it.
// for example #Context HttpServletRequest
#Override
public Tenant provide() {
final ContainerRequest request = getContainerRequest();
final String name
= request.getUriInfo().getQueryParameters().getFirst("tenent");
return new Tenant(name);
}
};
}
public static class TenantParamInjectionResolver
extends ParamInjectionResolver<TenantParam> {
public TenantParamInjectionResolver() {
super(TenantValueProvider.class);
}
}
public static class Binder extends AbstractBinder {
#Override
public void configure() {
bind(TenantParamInjectionResolver.class)
.to(new TypeLiteral<InjectionResolver<TenantParam>>(){})
.in(Singleton.class);
bind(TenantValueProvider.class)
.to(ValueFactoryProvider.class)
.in(Singleton.class);
}
}
}
#Path("test")
#Produces("text/plain")
#Consumes("application/json")
public static class TestResource {
#POST
public String post(User user, #TenantParam Tenant tenent) {
return user.name + ":" + tenent.name;
}
}
#Override
public ResourceConfig configure() {
return new ResourceConfig(TestResource.class)
.register(new TenantValueProvider.Binder())
.register(new LoggingFilter(Logger.getAnonymousLogger(), true));
}
#Test
public void shouldReturnTenantAndUserName() {
final User user = new User();
user.name = "peeskillet";
final Response response = target("test")
.queryParam("tenent", "testing")
.request()
.post(Entity.json(user));
assertEquals(200, response.getStatus());
assertEquals("peeskillet:testing", response.readEntity(String.class));
}
}
See Also:
Jersey 2.x Custom Injection Annotation With Attributes
My Comment in the Dropwizard issue: "No injection source found for a parameter"
I am trying to follow the example located here to create a factory in order to inject my HttpSession. Unfortunately no matter what I try it is not working. Not sure what could be the issue.
I have tried injecting just the HttpServletRequest and a provider. Here is my example using a provider. The error is a null pointer exception when trying to access the provider in the provide method. If I try to inject the HttpServletRequest I get no object available for injection. I am running this inside the GrizzlyTestContainer using JerseyTest. Is there something I need to add to my binder in order to bind the HttpServletRequest? I cannot seem to find an example.
public class HttpSessionFactory implements Factory<HttpSession> {
private final HttpServletRequest request;
#Inject
public HttpSessionFactory(Provider<HttpServletRequest> requestProvider) {
this.request = requestProvider.get();
}
#Override
public HttpSession provide() {
return request.getSession();
}
#Override
public void dispose(HttpSession t) {
}
}
You should #Override protected DeploymentContext configureDeployment() in the JerseyTest to return a ServletDeploymentContext. For example
import javax.inject.Inject;
import javax.inject.Provider;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.glassfish.hk2.api.Factory;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.ServletDeploymentContext;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;
import org.junit.Test;
public class ServletTest extends JerseyTest {
#Path("/session")
public static class SessionResource {
#Inject
HttpSession session;
#GET
public Response getSessionId() {
return Response.ok(session.getId()).build();
}
}
public static class HttpSessionFactory implements Factory<HttpSession> {
private final HttpServletRequest request;
#Inject
public HttpSessionFactory(Provider<HttpServletRequest> requestProvider) {
this.request = requestProvider.get();
}
#Override
public HttpSession provide() {
return request.getSession();
}
#Override
public void dispose(HttpSession t) {
}
}
#Override
protected TestContainerFactory getTestContainerFactory() {
return new GrizzlyWebTestContainerFactory();
}
#Override
protected DeploymentContext configureDeployment() {
ResourceConfig config = new ResourceConfig(SessionResource.class);
config.register(new AbstractBinder() {
#Override
protected void configure() {
bindFactory(HttpSessionFactory.class).to(HttpSession.class);
}
});
return ServletDeploymentContext.forServlet(
new ServletContainer(config)).build();
}
#Test
public void test() {
System.out.println(target("session").request().get(String.class));
}
}
You can see more examples in the source code tests