1 package org.apache.ojb.broker.cache;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 import java.util.Properties;
19
20 import org.apache.commons.lang.builder.ToStringBuilder;
21 import org.apache.commons.lang.builder.ToStringStyle;
22 import org.apache.jcs.JCS;
23 import org.apache.jcs.access.exception.CacheException;
24 import org.apache.jcs.access.exception.ObjectExistsException;
25 import org.apache.ojb.broker.Identity;
26 import org.apache.ojb.broker.PersistenceBroker;
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56 public class ObjectCacheJCSImpl implements ObjectCache
57 {
58
59
60
61 public static final String DEFAULT_REGION = "ojbDefaultJCSRegion";
62
63 private JCS jcsCache;
64
65
66
67 private String regionName = DEFAULT_REGION;
68
69 public ObjectCacheJCSImpl(PersistenceBroker broker, Properties prop)
70 {
71 this(null);
72 }
73
74
75
76
77 public ObjectCacheJCSImpl(String name)
78 {
79 regionName = (name != null ? name : DEFAULT_REGION);
80 try
81 {
82 jcsCache = JCS.getInstance(regionName);
83 }
84 catch(Exception e)
85 {
86 throw new RuntimeCacheException("Can't instantiate JCS ObjectCacheImplementation", e);
87 }
88 }
89
90 public String getRegionName()
91 {
92 return regionName;
93 }
94
95
96
97
98 public void cache(Identity oid, Object obj)
99 {
100 try
101 {
102 jcsCache.put(oid.toString(), obj);
103 }
104 catch (CacheException e)
105 {
106 throw new RuntimeCacheException(e);
107 }
108 }
109
110 public boolean cacheIfNew(Identity oid, Object obj)
111 {
112 boolean result = false;
113 try
114 {
115 jcsCache.putSafe(oid.toString(), obj);
116 result = true;
117 }
118 catch(ObjectExistsException e)
119 {
120
121 }
122 catch(CacheException e)
123 {
124 throw new RuntimeCacheException(e);
125 }
126 return result;
127 }
128
129
130
131
132
133 public Object lookup(Identity oid)
134 {
135 return jcsCache.get(oid.toString());
136 }
137
138
139
140
141
142
143 public void remove(Identity oid)
144 {
145 try
146 {
147 jcsCache.remove(oid.toString());
148 }
149 catch (CacheException e)
150 {
151 throw new RuntimeCacheException(e.getMessage());
152 }
153 }
154
155
156
157
158 public void clear()
159 {
160 if (jcsCache != null)
161 {
162 try
163 {
164 jcsCache.remove();
165 }
166 catch (CacheException e)
167 {
168 throw new RuntimeCacheException(e);
169 }
170 }
171 }
172
173 public String toString()
174 {
175 ToStringBuilder buf = new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE);
176 buf.append("JCS region name", regionName);
177 buf.append("JCS region", jcsCache);
178 return buf.toString();
179 }
180 }
181