1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.cache.decorators;
17
18 import java.io.ByteArrayInputStream;
19 import java.io.ByteArrayOutputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.ObjectInputStream;
23 import java.io.ObjectOutputStream;
24 import java.io.ObjectStreamClass;
25 import java.io.Serializable;
26
27 import org.apache.ibatis.cache.Cache;
28 import org.apache.ibatis.cache.CacheException;
29 import org.apache.ibatis.io.Resources;
30 import org.apache.ibatis.io.SerialFilterChecker;
31
32
33
34
35 public class SerializedCache implements Cache {
36
37 private final Cache delegate;
38
39 public SerializedCache(Cache delegate) {
40 this.delegate = delegate;
41 }
42
43 @Override
44 public String getId() {
45 return delegate.getId();
46 }
47
48 @Override
49 public int getSize() {
50 return delegate.getSize();
51 }
52
53 @Override
54 public void putObject(Object key, Object object) {
55 if ((object != null) && !(object instanceof Serializable)) {
56 throw new CacheException("SharedCache failed to make a copy of a non-serializable object: " + object);
57 }
58 delegate.putObject(key, serialize((Serializable) object));
59 }
60
61 @Override
62 public Object getObject(Object key) {
63 Object object = delegate.getObject(key);
64 return object == null ? null : deserialize((byte[]) object);
65 }
66
67 @Override
68 public Object removeObject(Object key) {
69 return delegate.removeObject(key);
70 }
71
72 @Override
73 public void clear() {
74 delegate.clear();
75 }
76
77 @Override
78 public int hashCode() {
79 return delegate.hashCode();
80 }
81
82 @Override
83 public boolean equals(Object obj) {
84 return delegate.equals(obj);
85 }
86
87 private byte[] serialize(Serializable value) {
88 try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
89 ObjectOutputStream oos = new ObjectOutputStream(bos)) {
90 oos.writeObject(value);
91 oos.flush();
92 return bos.toByteArray();
93 } catch (Exception e) {
94 throw new CacheException("Error serializing object. Cause: " + e, e);
95 }
96 }
97
98 private Serializable deserialize(byte[] value) {
99 SerialFilterChecker.check();
100 Serializable result;
101 try (ByteArrayInputStream bis = new ByteArrayInputStream(value);
102 ObjectInputStream ois = new CustomObjectInputStream(bis)) {
103 result = (Serializable) ois.readObject();
104 } catch (Exception e) {
105 throw new CacheException("Error deserializing object. Cause: " + e, e);
106 }
107 return result;
108 }
109
110 public static class CustomObjectInputStream extends ObjectInputStream {
111
112 public CustomObjectInputStream(InputStream in) throws IOException {
113 super(in);
114 }
115
116 @Override
117 protected Class<?> resolveClass(ObjectStreamClass desc) throws ClassNotFoundException {
118 return Resources.classForName(desc.getName());
119 }
120
121 }
122
123 }