Wednesday, July 06, 2011

Code to Compress and Decompress JSON Object

Following code can be used to compress and decompress JSON Object



import java.util.zip.*;

import org.apache.commons.io.IOUtils;

public class Compressor{
    public static byte[] compress(byte[] content){
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try{
            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
            gzipOutputStream.write(content);
            gzipOutputStream.close();
        } catch(IOException e){
            throw new RuntimeException(e);
        }
        System.out.printf("Compression ratio %f\n", (1.0f * content.length/byteArrayOutputStream.size()));
        return byteArrayOutputStream.toByteArray();
    }

    public static byte[] decompress(byte[] contentBytes){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try{
            IOUtils.copy(new GZIPInputStream(new ByteArrayInputStream(contentBytes)), out);
        } catch(IOException e){
            throw new RuntimeException(e);
        }
        return out.toByteArray();
    }

    public static boolean notWorthCompressing(String contentType){
        return contentType.contains("jpeg")
                || contentType.contains("pdf")
                || contentType.contains("zip")
                || contentType.contains("mpeg")
                || contentType.contains("avi");
    }
}

Note : This code will required jackson-core-asl-1.5.3.jar and jackson-mapper-asl-1.5.8.jar in your classpath.

How to Process Decompress JSON Object using RabbitMQ Framework


Following code can be used to decompress a JSON File

public static byte[] decompress(byte[] data) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try{
IOUtils.copy(new GZIPInputStream(new ByteArrayInputStream(data)), out);
} catch(IOException e){
throw new RuntimeException(e);
}
return out.toByteArray();
}

and in our MessageListener implemented class use this code

byte[] decompressmessage = decompress(messageContent);
YourClass objYourClass = mapper.readValue(new String(decompressmessage), YourClass.class);

//YourClass code
import org.codehaus.jackson.annotate.JsonProperty;

public class YourClass {

@JsonProperty("EventNo") public String eventNo;
public String getEventNo() {
return eventNo;
}
public void setEventNo(String eventNo) {
this.eventNo = eventNo;
}
}