Sunday, October 23, 2011

Using Jackson with Apache CXF - JAX-RS

Apache CXF uses Jettison for generating JSON generation. By default, Jettison adds the class name as well in JSON representation. To remove the class name from the json, there is some extra configuration required, which I will tell you some other time. Another solution to this problem is to use Jackson.

public class Error{

   Integer code;
   String reason;

   /*
    * getters and setters 
    */
   
}

Jettison's JSON:



{ "error" : { code: "CODE", reason: "REASON } }

Jackson's JSON:

{ code: "CODE", reason: "REASON" }




Now I will explain how to tell CXF to use Jackson instead of Jettison. Following are the required steps:

  1. You need to add Jackson in your classpath. If you are using Maven, you just need to add following lines in your pom.xml:
  2.       
             org.codehaus.jackson
             jackson-jaxrs
             1.9.0
          
    
  3. Next thing is to tell CXF to use Jackson. If you using Spring, you can add following lines in your bean configuration xml:
  4.         
               
            
        
       
    

Friday, September 23, 2011

Writing custom filter for jersey


If we want to intercept all the request coming to jersey controller. For example if we want to check if user is authenticated before each request, we will do this in each method. So to achieve this functionality we would prefer writing a filter, which will intercept each request and check for authentication.

Writing a filter:
We need to implement ContainerRequestFilter interface for creating Jersey filter. Following is the code sample for intercepting and modifying a request using jersey filter:



import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.log4j.Logger;
/**
 *
 * @author arnav
 */
public class MyAppFilter implements ContainerRequestFilter{


   public ContainerRequest filter(ContainerRequest request) {

      MultivaluedMap<String, String> headers = request.getRequestHeaders();

      headers.add("code", "MY_APP_CODE");
      request.setHeaders((InBoundHeaders)headers);

      return request;
   }
}

In the above class, I have intercepted the request and added a "code" into HTTP Header.


After adding this class, we need to register this filter for our web application. So now we will add following lines in our web.xml:



    
        Jersey Spring Web Application
        com.sun.jersey.spi.spring.container.servlet.SpringServlet
      
         com.sun.jersey.spi.container.ContainerRequestFilters
         package.MyAppFilter
              
    
@GET
	@Produces("application/xml")
	public PersonList getIt(@HeaderParam("code") String code) {

		System.out.println(code);
	}
This will have access to the "code", we have set in our MyAppFilter class.