From b04f843f4084a0e6c86f7ecc5b94d0169cb90cad Mon Sep 17 00:00:00 2001 From: magenoxx Date: Wed, 8 Jun 2011 18:46:14 +0400 Subject: [PATCH] Net traffic compressing. Enabled by default. Can be disabled by -Dnocompress on server. --- .../src/mage/remote/traffic/ZippedObject.java | 15 ++++++ .../mage/remote/traffic/ZippedObjectImpl.java | 54 +++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 Mage.Common/src/mage/remote/traffic/ZippedObject.java create mode 100644 Mage.Common/src/mage/remote/traffic/ZippedObjectImpl.java diff --git a/Mage.Common/src/mage/remote/traffic/ZippedObject.java b/Mage.Common/src/mage/remote/traffic/ZippedObject.java new file mode 100644 index 0000000000..8b0969e11f --- /dev/null +++ b/Mage.Common/src/mage/remote/traffic/ZippedObject.java @@ -0,0 +1,15 @@ +package mage.remote.traffic; + +/** + * Base interface for class wrapping non compressed objects. + * Provides methods for compressing that should be used before sending it over internet and decompressing to get actual + * data. + * + * @author ayrat + */ +public interface ZippedObject { + + void zip(T object); + + T unzip(); +} diff --git a/Mage.Common/src/mage/remote/traffic/ZippedObjectImpl.java b/Mage.Common/src/mage/remote/traffic/ZippedObjectImpl.java new file mode 100644 index 0000000000..076ab2c145 --- /dev/null +++ b/Mage.Common/src/mage/remote/traffic/ZippedObjectImpl.java @@ -0,0 +1,54 @@ +package mage.remote.traffic; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +/** + * Implementation for compressing and decompressing objects using {@link GZIPInputStream} and {@link GZIPOutputStream}. + * Can be used to send any {@link Object} over internet to reduce traffic usage. + * + * @author ayrat + */ +public class ZippedObjectImpl implements ZippedObject, Serializable { + + private byte[] data; + + public ZippedObjectImpl(T object) { + zip(object); + } + + public void zip(T object) { + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + GZIPOutputStream gz = new GZIPOutputStream(bos); + ObjectOutputStream oos = new ObjectOutputStream(gz); + oos.writeObject(object); + oos.close(); + data = bos.toByteArray(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @SuppressWarnings("unchecked") + public T unzip() { + try { + ByteArrayInputStream bis = new ByteArrayInputStream(data); + GZIPInputStream gz = new GZIPInputStream(bis); + ObjectInputStream ois = new ObjectInputStream(gz); + Object o = ois.readObject(); + return (T)o; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + private static final long serialVersionUID = 1L; +}