3 * Copyright (C) 2015 EDIT
4 * European Distributed Institute of Taxonomy
5 * http://www.e-taxonomy.eu
7 * The contents of this file are subject to the Mozilla Public License Version 1.1
8 * See LICENSE.TXT at the top of this package for the full license terms.
10 package eu
.etaxonomy
.taxeditor
.remoting
.cache
;
12 import java
.lang
.reflect
.Field
;
13 import java
.util
.ArrayList
;
14 import java
.util
.Collection
;
15 import java
.util
.Iterator
;
16 import java
.util
.List
;
19 import net
.sf
.ehcache
.Cache
;
20 import net
.sf
.ehcache
.Element
;
22 import org
.apache
.log4j
.Logger
;
23 import org
.springframework
.util
.ReflectionUtils
;
25 import eu
.etaxonomy
.cdm
.model
.ICdmCacher
;
26 import eu
.etaxonomy
.cdm
.model
.common
.CdmBase
;
33 public class CacheLoader
{
34 private static final Logger logger
= Logger
.getLogger(CacheLoader
.class);
36 private static boolean isRecursiveEnabled
= true;
38 protected final ICdmCacher cdmCacher
;
40 private final Cache cdmlibModelCache
;
44 public CacheLoader(ICdmCacher cdmCacher
) {
45 this.cdmCacher
= cdmCacher
;
46 this.cdmlibModelCache
= CdmRemoteCacheManager
.getInstance().getCdmModelGetMethodsCache();
51 public CdmModelFieldPropertyFromClass
getFromCdmlibModelCache(String className
) {
52 Element e
= cdmlibModelCache
.get(className
);
56 return (CdmModelFieldPropertyFromClass
) e
.getObjectValue();
60 @SuppressWarnings("unchecked")
61 public <T
extends Object
> T
load(T obj
, boolean recursive
, boolean update
) {
65 if(obj
instanceof CdmBase
) {
66 return (T
) load((CdmBase
)obj
, recursive
, update
);
67 } else if (obj
instanceof Map
) {
68 return (T
) load((Map
<T
,T
>)obj
, recursive
, update
);
69 } else if (obj
instanceof Collection
) {
70 return (T
) load((Collection
<T
>)obj
, recursive
, update
);
76 @SuppressWarnings("unchecked")
77 private <T
extends Object
> T
loadRecursive(T obj
, List
<Object
> alreadyVisitedEntities
, boolean update
) {
81 if(obj
instanceof CdmBase
) {
82 return (T
) loadRecursive((CdmBase
)obj
, alreadyVisitedEntities
, update
);
83 } else if (obj
instanceof Map
) {
84 return (T
) load((Map
<T
,T
>)obj
, alreadyVisitedEntities
, update
);
85 } else if (obj
instanceof Collection
) {
86 return (T
) load((Collection
<T
>)obj
, alreadyVisitedEntities
, update
);
90 logger
.info("No caching yet for type " + obj
.getClass().getName());
95 public <T
extends Object
> Map
<T
,T
> load(Map
<T
,T
> map
, boolean recursive
, boolean update
){
98 if(isRecursiveEnabled
&& recursive
) {
99 logger
.info("---- starting recursive load for cdm entity map");
100 List
<Object
> alreadyVisitedEntities
= new ArrayList
<Object
>();
101 Map
<T
,T
> cachedMap
= load(map
, alreadyVisitedEntities
, update
);
102 alreadyVisitedEntities
.clear();
103 logger
.info("---- ending recursive load for cdm entity map \n");
106 return load(map
, null, update
);
111 private <T
extends Object
> Map
<T
,T
> load(Map
<T
,T
> map
, List
<Object
> alreadyVisitedEntities
, boolean update
){
112 //map = (Map<T,T>)deproxy(map);
114 if(map
== null || map
.isEmpty()) {
118 int originalMapSize
= map
.size();
119 Object
[] result
= new Object
[ map
.size() * 2 ];
120 Iterator
<Map
.Entry
<T
,T
>> iter
= map
.entrySet().iterator();
122 // to avoid ConcurrentModificationException
123 alreadyVisitedEntities
.add(map
);
124 while ( iter
.hasNext() ) {
125 Map
.Entry
<T
,T
> e
= iter
.next();
126 result
[i
++] = e
.getKey();
127 result
[i
++] = e
.getValue();
130 for(i
=0; i
<result
.length
;i
++) {
131 if(alreadyVisitedEntities
== null) {
132 result
[i
] = load(result
[i
], false, update
);
134 result
[i
] = loadRecursive(result
[i
], alreadyVisitedEntities
, update
);
138 for(i
= 0; i
< originalMapSize
; i
+=2 ) {
147 public <T
extends Object
> Collection
<T
> load(Collection
<T
> collection
, boolean recursive
, boolean update
){
149 Collection
<T
> loadedCollection
;
150 if(isRecursiveEnabled
&& recursive
) {
151 logger
.info("---- starting recursive load for cdm entity collection");
152 List
<Object
> alreadyVisitedEntities
= new ArrayList
<Object
>();
153 Collection
<T
> cachedCollection
= load(collection
, alreadyVisitedEntities
, update
);
154 alreadyVisitedEntities
.clear();
155 logger
.info("---- ending recursive load for cdm entity collection \n");
156 loadedCollection
= cachedCollection
;
158 loadedCollection
= load(collection
, null, update
);
160 return loadedCollection
;
163 @SuppressWarnings("unchecked")
164 private <T
extends Object
> Collection
<T
> load(Collection
<T
> collection
, List
<Object
> alreadyVisitedEntities
, boolean update
) {
168 if(collection
== null || collection
.isEmpty()) {
171 int length
= collection
.size();
172 Object
[] result
= new Object
[length
];
173 Iterator
<T
> collectionItr
= collection
.iterator();
175 // to avoid ConcurrentModificationException
176 alreadyVisitedEntities
.add(collection
);
177 while(collectionItr
.hasNext()) {
178 Object obj
= collectionItr
.next();
179 if(alreadyVisitedEntities
== null) {
180 result
[count
] = load(obj
, false, update
);
182 result
[count
] = loadRecursive(obj
, alreadyVisitedEntities
, update
);
190 for ( int i
= 0; i
< length
; i
++ ) {
191 collection
.add((T
)result
[i
]);
199 * Puts the (Key,Value) pair of ({@link java.util.UUID}, {@link eu.etaxonomy.cdm.model.common.CdmBase}),
200 * in the cache corresponding to the given cache id
206 public CdmBase
load(CdmBase cdmEntity
, boolean recursive
, boolean update
) {
207 if(cdmEntity
== null) {
211 // start by looking up the cdm entity in the cache
212 CdmBase cachedCdmEntity
= cdmCacher
.getFromCache(cdmEntity
);
214 if(cachedCdmEntity
!= null) {
215 // if cdm entity was found in cache then
216 logger
.info(" - object of type " + cdmEntity
.getClass().getName() + " with id " + cdmEntity
.getId() + " already exists");
217 // .. return if the cached and input objects are identical, else (this is a newly loaded object so) continue
218 if(cachedCdmEntity
== cdmEntity
) {
219 return cachedCdmEntity
;
223 CdmBase loadedCdmBase
;
224 if(isRecursiveEnabled
&& recursive
) {
225 logger
.info("---- starting recursive load for cdm entity " + cdmEntity
.getClass().getName() + " with id " + cdmEntity
.getId());
226 List
<Object
> alreadyVisitedEntities
= new ArrayList
<Object
>();
227 CdmBase cb
= loadRecursive(cdmEntity
, alreadyVisitedEntities
, update
);
228 alreadyVisitedEntities
.clear();
229 logger
.info("---- ending recursive load for cdm entity " + cdmEntity
.getClass().getName() + " with id " + cdmEntity
.getId() + "\n");
232 loadedCdmBase
= load(cdmEntity
);
234 return loadedCdmBase
;
239 protected CdmBase
load(CdmBase cdmEntity
) {
240 logger
.info("loading object of type " + cdmEntity
.getClass().getName() + " with id " + cdmEntity
.getId());
241 cdmCacher
.put((CdmBase
)ProxyUtils
.deproxy(cdmEntity
));
242 return cdmCacher
.getFromCache(cdmEntity
);
246 private CdmBase
loadRecursive(CdmBase cdmEntity
, List
<Object
> alreadyVisitedEntities
, boolean update
) {
248 CdmBase cachedCdmEntity
= load(cdmEntity
);
251 // we want to recursive through the cdmEntity (and not the cachedCdmEntity)
252 // since there could be new or deleted objects in the cdmEntity sub-graph
254 // start by getting the fields from the cdm entity
255 String className
= cdmEntity
.getClass().getName();
256 CdmModelFieldPropertyFromClass cmgmfc
= getFromCdmlibModelCache(className
);
258 alreadyVisitedEntities
.add(cdmEntity
);
259 List
<String
> fields
= cmgmfc
.getFields();
260 for(String field
: fields
) {
261 // retrieve the actual object corresponding to the field.
262 // this object will be either a CdmBase or a Collection / Map
263 // with CdmBase as the generic type
265 CdmBase cdmEntityInSubGraph
= getCdmBaseTypeFieldValue(cdmEntity
, cachedCdmEntity
, field
, alreadyVisitedEntities
, update
);
266 if(cdmEntityInSubGraph
!= null) {
267 //checkForIdenticalCdmEntity(alreadyVisitedEntities, cdmEntityInSubGraph);
268 if(!checkForIdenticalCdmEntity(alreadyVisitedEntities
, cdmEntityInSubGraph
)) {
269 logger
.info("recursive loading object of type " + cdmEntityInSubGraph
.getClass().getName() + " with id " + cdmEntityInSubGraph
.getId());
270 loadRecursive(cdmEntityInSubGraph
, alreadyVisitedEntities
, update
);
272 logger
.info("object of type " + cdmEntityInSubGraph
.getClass().getName() + " with id " + cdmEntityInSubGraph
.getId() + " already visited");
277 throw new CdmClientCacheException("CdmEntity with class " + cdmEntity
.getClass().getName() + " is not found in the cdmlib model cache. " +
278 "The cache may be corrupted or not in sync with the latest model version" );
281 return cachedCdmEntity
;
285 private CdmBase
getCdmBaseTypeFieldValue(CdmBase cdmEntity
,
286 CdmBase cachedCdmEntity
,
288 List
<Object
> alreadyVisitedEntities
,
291 // this method attempts to make sure that for any two objects found in
292 // the object graph, if they are equal then they should also be the same,
293 // which is crucial for the merge to work
294 if(cachedCdmEntity
== null) {
295 throw new CdmClientCacheException("When trying to set field value, the cached cdm entity cannot be null");
298 Class
<?
> clazz
= cdmEntity
.getClass();
300 // this call will search in the provided class as well as
301 // the super classes until it finds the field
302 Field field
= ReflectionUtils
.findField(clazz
, fieldName
);
305 throw new CdmClientCacheException("Field '" + fieldName
306 + "' not found when searching in class '" + clazz
.getName() + "' and its supercalsses");
308 field
.setAccessible(true);
309 Object o
= field
.get(cdmEntity
);
310 // resetting the value in cdm entity to the deproxied object
311 o
= ProxyUtils
.deproxy(o
);
312 field
.set(cdmEntity
, o
);
313 Object cachedo
= field
.get(cachedCdmEntity
);
314 CdmBase cdmEntityInSubGraph
= null;
316 if(update
|| ProxyUtils
.isProxy(cachedo
)) {
317 // if we are in update mode we have to make the field of the cached entity
318 // up-to-date by setting it to the value of the cdm entity being loaded
320 // if the cdm entity is a proxy then we always update to make sure that
321 // newly created entities are always up-to-date
323 // NOTE : the field is overridden in the case of the exception
325 field
.set(cachedCdmEntity
, o
);
329 if(o
!= null && !ProxyUtils
.isProxy(o
)) {
330 if(CdmBase
.class.isAssignableFrom(o
.getClass())) {
331 logger
.info("found initialised cdm entity '" + fieldName
+ "' in object of type " + clazz
.getName() + " with id " + cdmEntity
.getId());
333 cdmEntityInSubGraph
= (CdmBase
)o
;
334 CdmBase cachedCdmEntityInSubGraph
= cdmCacher
.getFromCache(cdmEntityInSubGraph
);
336 if(cachedCdmEntityInSubGraph
!= null) {
337 if(cachedCdmEntityInSubGraph
!= cdmEntityInSubGraph
) {
338 // exception : is the case where
339 // the field has been already initialised, cached and
340 // is not the same as the one in the cache, in which case we set the value
341 // of the field to the one found in the cache
342 logger
.info("setting cached + real value to '" + fieldName
+ "' in object of type " + clazz
.getName() + " with id " + cdmEntity
.getId());
343 field
.set(cachedCdmEntity
, cachedCdmEntityInSubGraph
);
344 field
.set(cdmEntity
, cachedCdmEntityInSubGraph
);
346 // since the field value object in cdmEntity
347 // is the same as the field value object in cachedCdmEntity
348 // we are sure that the its subgraph is also correctly loaded,
349 // so we can exit the recursion
353 } else if(o
instanceof Map
&& !checkForIdenticalCdmEntity(alreadyVisitedEntities
, o
)) {
354 loadRecursive((Map
)o
, alreadyVisitedEntities
, update
);
355 } else if(o
instanceof Collection
&& !checkForIdenticalCdmEntity(alreadyVisitedEntities
, o
)) {
356 loadRecursive((Collection
)o
, alreadyVisitedEntities
, update
);
359 // we return the original cdm entity in the sub graph because we
360 // want to continue to recurse on the input cdm entity graph
361 // and not the one in the cache
362 return cdmEntityInSubGraph
;
363 } catch (SecurityException e
) {
364 throw new CdmClientCacheException(e
);
365 } catch (IllegalArgumentException e
) {
366 throw new CdmClientCacheException(e
);
367 } catch (IllegalAccessException e
) {
368 throw new CdmClientCacheException(e
);
372 private boolean checkForIdenticalCdmEntity(List
<Object
> objList
, Object objToCompare
) {
373 if(objToCompare
!= null) {
374 for(Object obj
: objList
) {
375 if(obj
== objToCompare
) {
384 public static boolean isRecursiveEnabled() {
385 return isRecursiveEnabled
;
388 public static void setRecursiveEnabled(boolean ire
) {
389 isRecursiveEnabled
= ire
;