I am using using jersey as my rest client. I want to write a custom annotation which will intercept the request so that i can validate the user and throw error accordingly. So i can annotate only those functions which i want to validate. there two problems around it.
as far as i have seen the annotations they all inject property before the actual call. how can i control while this function has been called. I need to access the @Context HttpServletRequest request part to get the userId and make a DB call to validate..
Classes which are going to be annotated my annotation parser need to know before hand. how can i make this independent of that. like spring annotations.
@MYCustomFIlter @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{programId}/processCount") public Response getProgramInitializedCount(@PathParam("programId") String programId, @Context HttpServletRequest request) { //this line will be moved to annotation filter. String userId = WfManagerUtil.getCurrentUser(request);
Any ideas around this how can this be achieved.
FIRST EDIT : with some research i found out how to do it. But this is not happening. Can somebody help me in finding out why.
Annotation :
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidateUser {
}
filter :
public class ValidateUserFilter implements ContainerRequestFilter {
@Override
public ContainerRequest filter(ContainerRequest request) throws WebApplicationException{
String user = request.getHeaderValue(USER_HEADER);
//rest of code.
}
}
Binding :
@Provider
public class ResourceFilterBindingFeature implements DynamicFeature {
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
if (resourceInfo.getResourceMethod().isAnnotationPresent(ValidateUser.class)) {
context.register(CommonResourceFilter.class);
}
}
}
and using it as :
@Path("/v1.0/programs")
public class ProgramsResource {
@ValidateUser
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{programId}/initialization/progress/")
public Response getProgramInitializedCount(@PathParam("programId") String programId,
@Context HttpServletRequest request) throws WorkflowManagerException {
//code
}
}
POM :
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.8</version>
<!-- <scope>provided</scope> -->
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
<!-- <scope>provided</scope> -->
</dependency>
Where possibly i am doing wrong. the filter class is not being invoked.