1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.dao.orm.hibernate;
24  
25  import com.liferay.portal.kernel.cache.CacheKVP;
26  import com.liferay.portal.kernel.cache.CacheRegistry;
27  import com.liferay.portal.kernel.cache.CacheRegistryItem;
28  import com.liferay.portal.kernel.cache.MultiVMPool;
29  import com.liferay.portal.kernel.cache.PortalCache;
30  import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
31  import com.liferay.portal.kernel.dao.orm.FinderCache;
32  import com.liferay.portal.kernel.dao.orm.FinderPath;
33  import com.liferay.portal.kernel.dao.orm.SessionFactory;
34  import com.liferay.portal.kernel.util.InitialThreadLocal;
35  import com.liferay.portal.kernel.util.StringPool;
36  import com.liferay.portal.model.BaseModel;
37  import com.liferay.portal.util.PropsValues;
38  
39  import java.io.Serializable;
40  
41  import java.util.ArrayList;
42  import java.util.List;
43  import java.util.Map;
44  import java.util.concurrent.ConcurrentHashMap;
45  
46  import org.apache.commons.collections.map.LRUMap;
47  
48  /**
49   * <a href="FinderCacheImpl.java.html"><b><i>View Source</i></b></a>
50   *
51   * @author Brian Wing Shun Chan
52   *
53   */
54  public class FinderCacheImpl implements CacheRegistryItem, FinderCache {
55  
56      public static final String CACHE_NAME = FinderCache.class.getName();
57  
58      public void afterPropertiesSet() {
59          CacheRegistry.register(this);
60      }
61  
62      public void clearCache() {
63          clearLocalCache();
64  
65          PortalCache[] portalCaches = _portalCaches.values().toArray(
66              new PortalCache[_portalCaches.size()]);
67  
68          for (PortalCache portalCache : portalCaches) {
69              portalCache.removeAll();
70          }
71      }
72  
73      public void clearCache(String className) {
74          clearLocalCache();
75  
76          PortalCache portalCache = _getPortalCache(className);
77  
78          portalCache.removeAll();
79      }
80  
81      public void clearLocalCache() {
82          if (_localCacheEnabled.get().booleanValue()) {
83              Map<String, Object> localCache = _localCache.get();
84  
85              localCache.clear();
86          }
87      }
88  
89      public String getRegistryName() {
90          return CACHE_NAME;
91      }
92  
93      public Object getResult(
94          FinderPath finderPath, Object[] args, SessionFactory sessionFactory) {
95  
96          if (!PropsValues.VALUE_OBJECT_FINDER_CACHE_ENABLED ||
97              !finderPath.isFinderCacheEnabled() || !CacheRegistry.isActive()) {
98  
99              return null;
100         }
101 
102         Object primaryKey = null;
103 
104         Map<String, Object> localCache = null;
105 
106         String localCacheKey = null;
107 
108         if (_localCacheEnabled.get().booleanValue()) {
109             localCache = _localCache.get();
110 
111             localCacheKey = _encodeLocalCacheKey(
112                 finderPath.getClassName(), finderPath.getMethodName(),
113                 finderPath.getParams(), args);
114 
115             primaryKey = localCache.get(localCacheKey);
116         }
117 
118         if (primaryKey == null) {
119             PortalCache portalCache = _getPortalCache(
120                 finderPath.getClassName());
121 
122             String cacheKey = _encodeCacheKey(
123                 finderPath.getMethodName(), finderPath.getParams(), args);
124 
125             primaryKey = _multiVMPool.get(portalCache, cacheKey);
126 
127             if (primaryKey != null) {
128                 if (_localCacheEnabled.get().booleanValue()) {
129                     localCache.put(localCacheKey, primaryKey);
130                 }
131             }
132         }
133 
134         if (primaryKey != null) {
135             return _primaryKeyToResult(finderPath, sessionFactory, primaryKey);
136         }
137         else {
138             return null;
139         }
140     }
141 
142     public void invalidate() {
143         clearCache();
144     }
145 
146     public void putResult(FinderPath finderPath, Object[] args, Object result) {
147         if (!PropsValues.VALUE_OBJECT_FINDER_CACHE_ENABLED ||
148             !finderPath.isFinderCacheEnabled() || !CacheRegistry.isActive() ||
149             (result == null)) {
150 
151             return;
152         }
153 
154         Object primaryKey = _resultToPrimaryKey(result);
155 
156         if (_localCacheEnabled.get().booleanValue()) {
157             Map<String, Object> localCache = _localCache.get();
158 
159             String localCacheKey = _encodeLocalCacheKey(
160                 finderPath.getClassName(), finderPath.getMethodName(),
161                 finderPath.getParams(), args);
162 
163             localCache.put(localCacheKey, primaryKey);
164         }
165 
166         PortalCache portalCache = _getPortalCache(finderPath.getClassName());
167 
168         String cacheKey = _encodeCacheKey(
169             finderPath.getMethodName(), finderPath.getParams(), args);
170 
171         _multiVMPool.put(portalCache, cacheKey, primaryKey);
172     }
173 
174     public void removeResult(FinderPath finderPath, Object[] args) {
175         if (!PropsValues.VALUE_OBJECT_FINDER_CACHE_ENABLED ||
176             !finderPath.isFinderCacheEnabled() || !CacheRegistry.isActive()) {
177 
178             return;
179         }
180 
181         if (_localCacheEnabled.get().booleanValue()) {
182             Map<String, Object> localCache = _localCache.get();
183 
184             String localCacheKey = _encodeLocalCacheKey(
185                 finderPath.getClassName(), finderPath.getMethodName(),
186                 finderPath.getParams(), args);
187 
188             localCache.remove(localCacheKey);
189         }
190 
191         PortalCache portalCache = _getPortalCache(finderPath.getClassName());
192 
193         String cacheKey = _encodeCacheKey(
194             finderPath.getMethodName(), finderPath.getParams(), args);
195 
196         _multiVMPool.remove(portalCache, cacheKey);
197     }
198 
199     public void setLocalCacheEnabled(boolean localCacheEnabled) {
200         if (_localCacheAvailable) {
201             _localCacheEnabled.set(Boolean.valueOf(localCacheEnabled));
202         }
203     }
204 
205     public void setMultiVMPool(MultiVMPool multiVMPool) {
206         _multiVMPool = multiVMPool;
207     }
208 
209     private String _encodeCacheKey(
210         String methodName, String[] params, Object[] args) {
211 
212         StringBuilder sb = new StringBuilder();
213 
214         sb.append(methodName);
215         sb.append(_PARAMS_SEPARATOR);
216 
217         for (String param : params) {
218             sb.append(StringPool.PERIOD);
219             sb.append(param);
220         }
221 
222         sb.append(_ARGS_SEPARATOR);
223 
224         for (Object arg : args) {
225             sb.append(StringPool.PERIOD);
226             sb.append(String.valueOf(arg));
227         }
228 
229         return sb.toString();
230     }
231 
232     private String _encodeGroupKey(String className) {
233         StringBuilder sb = new StringBuilder();
234 
235         sb.append(CACHE_NAME);
236         sb.append(StringPool.PERIOD);
237         sb.append(className);
238 
239         return sb.toString();
240     }
241 
242     private String _encodeLocalCacheKey(
243         String className, String methodName, String[] params, Object[] args) {
244 
245         StringBuilder sb = new StringBuilder();
246 
247         sb.append(className);
248         sb.append(StringPool.PERIOD);
249         sb.append(methodName);
250         sb.append(_PARAMS_SEPARATOR);
251 
252         for (String param : params) {
253             sb.append(StringPool.PERIOD);
254             sb.append(param);
255         }
256 
257         sb.append(_ARGS_SEPARATOR);
258 
259         for (Object arg : args) {
260             sb.append(StringPool.PERIOD);
261             sb.append(String.valueOf(arg));
262         }
263 
264         return sb.toString();
265     }
266 
267     private PortalCache _getPortalCache(String className) {
268         String groupKey = _encodeGroupKey(className);
269 
270         PortalCache portalCache = _portalCaches.get(groupKey);
271 
272         if (portalCache == null) {
273             portalCache = _multiVMPool.getCache(groupKey, true);
274 
275             _portalCaches.put(groupKey, portalCache);
276         }
277 
278         return portalCache;
279     }
280 
281     private Object _primaryKeyToResult(
282         FinderPath finderPath, SessionFactory sessionFactory,
283         Object primaryKey) {
284 
285         if (primaryKey instanceof CacheKVP) {
286             CacheKVP cacheKVP = (CacheKVP)primaryKey;
287 
288             Class<?> modelClass = cacheKVP.getModelClass();
289             Serializable primaryKeyObj = cacheKVP.getPrimaryKeyObj();
290 
291             return EntityCacheUtil.loadResult(
292                 finderPath.isEntityCacheEnabled(), modelClass, primaryKeyObj,
293                 sessionFactory);
294         }
295         else if (primaryKey instanceof List) {
296             List<Object> cachedList = (List<Object>)primaryKey;
297 
298             List<Object> list = new ArrayList<Object>(cachedList.size());
299 
300             for (Object curPrimaryKey : cachedList) {
301                 Object result = _primaryKeyToResult(
302                     finderPath, sessionFactory, curPrimaryKey);
303 
304                 list.add(result);
305             }
306 
307             return list;
308         }
309         else {
310             return primaryKey;
311         }
312     }
313 
314     private Object _resultToPrimaryKey(Object result) {
315         if (result instanceof BaseModel) {
316             BaseModel<?> model = (BaseModel<?>)result;
317 
318             Class<?> modelClass = model.getClass();
319             Serializable primaryKeyObj = model.getPrimaryKeyObj();
320 
321             return new CacheKVP(modelClass, primaryKeyObj);
322         }
323         else if (result instanceof List) {
324             List<Object> list = (List<Object>)result;
325 
326             List<Object> cachedList = new ArrayList<Object>(list.size());
327 
328             for (Object curResult : list) {
329                 Object primaryKey = _resultToPrimaryKey(curResult);
330 
331                 cachedList.add(primaryKey);
332             }
333 
334             return cachedList;
335         }
336         else {
337             return result;
338         }
339     }
340 
341     private static final String _ARGS_SEPARATOR = "_A_";
342 
343     private static final String _PARAMS_SEPARATOR = "_P_";
344 
345     private static ThreadLocal<Map> _localCache;
346     private static boolean _localCacheAvailable;
347     private static ThreadLocal<Boolean> _localCacheEnabled =
348         new InitialThreadLocal<Boolean>(Boolean.FALSE);
349 
350     static {
351         if (PropsValues.VALUE_OBJECT_FINDER_THREAD_LOCAL_CACHE_MAX_SIZE > 0) {
352             _localCache = new InitialThreadLocal<Map>(new LRUMap(
353                 PropsValues.VALUE_OBJECT_FINDER_THREAD_LOCAL_CACHE_MAX_SIZE));
354             _localCacheAvailable = true;
355         }
356     }
357 
358     private MultiVMPool _multiVMPool;
359     private Map<String, PortalCache> _portalCaches =
360         new ConcurrentHashMap<String, PortalCache>();
361 
362 }