Tuesday, April 30, 2013

Jersey Resource Filter example

  1. Create Filter class by implementing ResourceFilter and ContainerRequestFilter interfaces.
public class TestFilterFirst implements ResourceFilter, ContainerRequestFilter {

	@Context HttpServletRequest request;
	@Context HttpServletResponse response;
	
	@Override
	public ContainerRequest filter(ContainerRequest arg0) {
		//Filter logic goes here.
		return arg0;
	}

	@Override
	public ContainerRequestFilter getRequestFilter() {
		return this;
	}

	@Override
	public ContainerResponseFilter getResponseFilter() {
		return null;
	}
	
}

2.  Create Rest Service Class

@Path("/helloworld")
public class TestJersey {

	@GET
	@Produces("text/plain")
	@ResourceFilters({ TestFilterFirst.class })
	public String sayHello() {
		System.out.println("Hello");
		return "Hello World";
	}
}

Notice ResourceFilters Annotation. multiple classes can be added here as comma separated. Each class added here will be configured as filter to this service.

No specific configuration is required in web.xml to add filters if you are using ResourceFilters annotation.


 

Tuesday, April 16, 2013

Method Level Custom annotation java example

Create custom annotaion class

package com.arvind;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(value=RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
 String[] customValues();
}
Create Test class for testing
package com.arvind;

import java.lang.reflect.Method;

public class Test {

@CustomAnnotation(customValues = { "First Value", "Second Value" })
 public void testing() {

 }

 public static void main(String[] args) {

  Class clazz = Test.class;
  Method[] methods = clazz.getMethods();

  for (Method method : methods) {
     if ("testing".equals(method.getName())) {
        if (method.isAnnotationPresent(CustomAnnotation.class)) {
            CustomAnnotation ca = method.getAnnotation(CustomAnnotation.class);
            if (ca != null){
              for (String value : ca.customValues()) {
                  System.out.println(value);
              }
           }
       }
    }
  }
 }

}

Output will be
First Value
Second Value