Created
September 5, 2014 09:04
-
-
Save ypetya/3597187359be8f2a2207 to your computer and use it in GitHub Desktop.
Serialize and deserialize java Object into a bytearray containing GZIP-ped data.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just to show someone how streams and object stream implementation works in the java world.