Sunday, November 19, 2017

Serialize & Deserialize exactly same as JAX-RS server

The following code sample show a way to serialize and deserialize exactly same as the JAX-RS server. The code used the same MessageBodyReader  and  MessageBodyWriter used while Jersey frameworks converts request and response body.

The annotation javax.ws.rs.core.Context  is the key. The Providers used by the framework can be fetched from the context.

I have used this technique to improve the performance of the GET call. There are no serialization and deserialization during the GET call. It helps in improving the performance



import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;

import org.springframework.stereotype.Component;

@Path("/emp")
@Produces({ MediaType.APPLICATION_JSON })
@Component
public class EmpResource {
    
    @Context
    javax.ws.rs.ext.Providers providers;
    
    @POST
    public Employee post(Employee emp) {
        //convert POJO to String
        MessageBodyWriter writer = providers.getMessageBodyWriter(Employee.class,
                Employee.class, null, MediaType.APPLICATION_JSON_TYPE);
        String jsonString = null;
        try {
            ByteArrayOutputStream entityStream = new ByteArrayOutputStream();
            writer.writeTo(emp, Employee.class, Employee.class, null,
                    MediaType.APPLICATION_JSON_TYPE, null, entityStream);
            jsonString = entityStream.toString();
            // Business logic
            //Store jsonString to back end
        } catch (IOException e) {}
        
        //convert String to POJO
        MessageBodyReader reader = providers.getMessageBodyReader(Employee.class,
                Employee.class, null, MediaType.APPLICATION_JSON_TYPE);
        Employee emp2 = null;
        try {
            emp2 = reader.readFrom(Employee.class, Employee.class, null,
                    MediaType.APPLICATION_JSON_TYPE, null,
                    new ByteArrayInputStream(jsonString.getBytes()));
        } catch (Exception e) {}
        
        return emp2;
    }
    
    @GET
    public String get(@QueryParam("id") String id) {
        //Read from backend
        String jsonString = null;

        //Performance improvement: Avoiding String-POJO-String conversion
        return jsonString;
    }
    
}




No comments: