1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.caches.memcached;
17
18 import java.io.ByteArrayInputStream;
19 import java.io.ByteArrayOutputStream;
20 import java.io.Closeable;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.ObjectInputStream;
24 import java.io.ObjectOutputStream;
25 import java.util.zip.GZIPInputStream;
26 import java.util.zip.GZIPOutputStream;
27
28 import net.spy.memcached.CachedData;
29 import net.spy.memcached.transcoders.Transcoder;
30
31 import org.apache.ibatis.cache.CacheException;
32
33
34
35
36
37
38 final class CompressorTranscoder implements Transcoder<Object> {
39
40
41
42
43 private static final int SERIALIZED_COMPRESSED = 3;
44
45
46
47
48 @Override
49 public boolean asyncDecode(final CachedData cachedData) {
50 return false;
51 }
52
53
54
55
56 @Override
57 public Object decode(final CachedData cachedData) {
58 byte[] buffer = cachedData.getData();
59
60 ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
61 GZIPInputStream gzis = null;
62 ObjectInputStream ois = null;
63 Object ret = null;
64
65 try {
66 gzis = new GZIPInputStream(bais);
67 ois = new ObjectInputStream(gzis);
68 ret = ois.readObject();
69 } catch (Exception e) {
70 throw new CacheException("Impossible to decompress cached object, see nested exceptions", e);
71 } finally {
72 closeQuietly(ois);
73 closeQuietly(gzis);
74 closeQuietly(bais);
75 }
76 return ret;
77 }
78
79
80
81
82 @Override
83 public CachedData encode(final Object object) {
84 ByteArrayOutputStream baos = new ByteArrayOutputStream();
85 GZIPOutputStream gzops = null;
86 ObjectOutputStream oos = null;
87
88 try {
89 gzops = new GZIPOutputStream(baos);
90 oos = new ObjectOutputStream(gzops);
91 oos.writeObject(object);
92 } catch (IOException e) {
93 throw new CacheException("Impossible to compress object [" + object + "], see nested exceptions", e);
94 } finally {
95 closeQuietly(oos);
96 closeQuietly(gzops);
97 closeQuietly(baos);
98 }
99
100 byte[] buffer = baos.toByteArray();
101 return new CachedData(SERIALIZED_COMPRESSED, buffer, CachedData.MAX_SIZE);
102 }
103
104
105
106
107 @Override
108 public int getMaxSize() {
109 return Integer.MAX_VALUE;
110 }
111
112
113
114
115
116
117
118 private static void closeQuietly(final Closeable closeable) {
119 if (closeable != null) {
120 try {
121 closeable.close();
122 } catch (IOException e) {
123
124 }
125 }
126 }
127
128 }