Friday, June 14, 2013

Get Input object in Jersey Filter

There is no direct way I found where jersey can provide me input object ( conversion from json to java object) in Filter as it does in Resource.


Following is the code I used to accomplished it.



public <T> T getInputObject(HttpServletRequest request, Class<T> type) {
  if (request != null && type != null) {
   try {
    ServletInputStream inputStream = request.getInputStream();
    // Wrap a BufferedReader around the InputStream
    BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
    // Read response until the end
    inputStream.mark(inputStream.available());
    StringBuffer total = new StringBuffer();
    
    String line = null;
    while ((line = rd.readLine()) != null) {
     total.append(line);
    }

    inputStream.reset();


    ObjectMapper obm = new ObjectMapper();
    return obm.readValue(total.toString(), type);
   } catch (Exception e) {
    logback.error("Exception during getting Input Object for jersey filter",e);
    return null;
   }
  }
  return null;
 }

You can call this method in your Jersey filter to get Input object.
MyRestInput input=getInputObject(request, MyRestInput .class);

Wednesday, May 15, 2013

Class 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.TYPE)
@Retention(value=RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
 String[] customValues();
}
Create Test class for testing
package com.arvind;

import java.lang.reflect.Method;

@CustomAnnotation(customValues = { "First Value", "Second Value" })
public class Test {
 public static void main(String[] args) {
  Test t = new Test();
  boolean present = t.getClass().isAnnotationPresent(CustomAnnotation.class);
  if (present) {
   CustomAnnotation ca = t.getClass().getAnnotation(CustomAnnotation.class);
   if (ca != null) {
    for (String value : ca.customValues()) {
     System.out.println(value);
    }
   }
  }
 }
}

Output will be
First Value
Second Value

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

Friday, January 25, 2013

Java Serialization Questions

How Serialization works ?

Suppose following example.

C extends B extends A.

Case 1:

if Class A implements Serializable interface. B and C need not to do it explicitly. If I create an object of class C, serialize it and deserialize, all the attributes of A, B and C will be populated.

Because while de-serialization none of the class's constructor will be called.

If any of this class have an attribute of class which don't implement Serializable Interface, while serialization exception will be thrown.

Case 2:

A and C don't implements Serializable interface but B implements.

Now in this case all the attributes of B and C will be serialized and deserialized but A's attributes will not.

Only class A's Constructor will be called during deserialization.

Other than A, if any class have an attribute of class which don't implement Serializalbe interface exception will be thrown.

Case 3:

A and B don't implements Serializable interface only C implements.

Now in this case all the attributes of A and B will not be serialized and deserialized only C's attributes will.

Only class A's and B's Constructor will be called during deserialization.

Both than A and B can have an attribute of class which don't implement Serializalbe interface.
  

Summary: If super class implements Serializable interface, child class will inherit it. 
If superclass don't implements Serializable interface and chlid class does, and if you try to serialize object of child class, only child class's attributes will be serialized.
Super class's attributes will be ignored.



Q- Example of Extenalization


class Employee implements Externalizable {
      String name;
      double salary;
      int age;
      long cardNo;

      public void writeExternal(ObjectOutput out) throws IOException {
             out.writeUTF(name);
             out.writeInt(age);
             out.writeDouble(salary);

      }

      public void readExternal(ObjectInput in) throws IOException,
                    ClassNotFoundException {
             name = in.readUTF();
             age = in.readInt();
             salary = in.readDouble();

      }
}


For more questions Refer Click here