Skip to content

Instantly share code, notes, and snippets.

@ypetya
Created September 5, 2014 09:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ypetya/3597187359be8f2a2207 to your computer and use it in GitHub Desktop.
Save ypetya/3597187359be8f2a2207 to your computer and use it in GitHub Desktop.
Serialize and deserialize java Object into a bytearray containing GZIP-ped data.
package tools.distribution.transmission.serialization;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.logging.Level;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import tools.distribution.Factory;
import tools.distribution.protocol.Message;
/**
* Basic implementation of Marshaller via java.util.GZIPStream with default settings
* */
public class GZip extends Serialization implements CapableToSerializeIntoAByteArray {
public GZip(Factory f) {
super(f);
}
@Override
public byte[] marshall(Message input) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
GZIPOutputStream os = new GZIPOutputStream(bos);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(input);
oos.close();
os.close();
bos.close();
} catch (IOException e) {
getLogger().log(Level.WARNING, "could not marshal", e);
}
return bos.toByteArray();
}
@Override
public Message unmarshall(byte[] input) {
ByteArrayInputStream bis = new ByteArrayInputStream(input);
Message ret = null;
try {
GZIPInputStream gis = new GZIPInputStream(bis);
ObjectInputStream ois = new ObjectInputStream(gis);
ret = (Message)ois.readObject();
ois.close();
gis.close();
bis.close();
} catch (Exception e) {
getLogger().log(Level.WARNING, "could not unmarshal", e);
}
return ret;
}
}
@ypetya
Copy link
Author

ypetya commented Sep 16, 2014

Just to show someone how streams and object stream implementation works in the java world.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment