1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.gwe.utils;
18
19 import java.io.IOException;
20 import java.io.Serializable;
21 import java.util.zip.Deflater;
22 import java.util.zip.Inflater;
23
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26
27
28
29
30
31 public class CompressedObject<VALUE_TYPE extends Serializable> implements Serializable {
32
33 private static Log log = LogFactory.getLog(CompressedObject.class);
34
35 private int originalLength;
36 private byte[] compressedObject = null;
37 private VALUE_TYPE targetObject = null;
38
39 public CompressedObject() { nullTarget(); }
40
41 public CompressedObject(VALUE_TYPE target) throws CompressionException { setTarget(target); }
42
43 public void setTargetBlindly(VALUE_TYPE target) {
44 try {
45 setTarget(target);
46 } catch (CompressionException e) {
47 String msg = "Unusual IOException error caught trying to create a serialized stream of an object";
48 log.warn(msg, e);
49 throw new RuntimeException(msg, e.getCause());
50 }
51 }
52
53 public void setTarget(VALUE_TYPE target) throws CompressionException {
54 if (target == null) {
55 nullTarget();
56 return;
57 }
58
59 byte[] source = serializeTarget(target);
60 originalLength = source.length;
61 byte[] compressedTarget = new byte[originalLength];
62 Deflater compresser = new Deflater(5, true);
63 compresser.setInput(source);
64
65 compresser.finish();
66 int length = compresser.deflate(compressedTarget);
67 if (length == originalLength) {
68 compressedTarget = null;
69 targetObject = target;
70 } else {
71 compressedObject = new byte[length];
72 System.arraycopy(compressedTarget, 0, compressedObject, 0, length);
73 }
74 }
75
76 private byte[] serializeTarget(Serializable target) throws CompressionException {
77 try {
78 return IOUtils.serializeObject(target);
79 } catch (IOException e) {
80 throw new CompressionException(e);
81 }
82 }
83
84 private void nullTarget() {
85 compressedObject = null;
86 targetObject = null;
87 }
88
89 public VALUE_TYPE getTargetBlindly() {
90 try {
91 return getTarget();
92 } catch (CompressionException e) {
93
94 log.warn("Problems decompressing target object", e);
95 return null;
96 }
97 }
98
99 public VALUE_TYPE getTarget() throws CompressionException {
100 if (targetObject != null) return targetObject;
101 if (compressedObject == null) return null;
102
103 byte[] result = new byte[originalLength];
104
105
106 Inflater decompresser = new Inflater(true);
107 decompresser.setInput(compressedObject, 0, compressedObject.length);
108 try {
109 decompresser.inflate(result);
110 decompresser.end();
111 return (VALUE_TYPE) IOUtils.deserializeObject(result);
112 } catch (Exception e) {
113 throw new CompressionException(e);
114 }
115 }
116 }
117