Project

General

Profile

« Previous | Next » 

Revision ea22cad6

Added by Cherian Mathew about 9 years ago

migrated cache related classes to another package

View differences:

.gitattributes
335 335
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/application/CdmApplicationRemoteController.java -text
336 336
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/application/RemotingMonitoredGenericApplicationContext.java -text
337 337
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/application/RemotingMonitoredListableBeanFactory.java -text
338
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CachedCommonServiceImpl.java -text
339
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CdmClientCacheException.java -text
340
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CdmEntityCacheKey.java -text
341
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CdmModelCacher.java -text
342
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CdmModelFieldPropertyFromClass.java -text
343
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CdmRemoteCacheManager.java -text
344 338
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CdmServiceCacher.java -text
345
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CdmTransientEntityCacher.java -text
346
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/ICachedCommonService.java -text
347 339
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/CdmEagerLoadingException.java -text
348 340
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/CdmRemotingException.java -text
341
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/cache/CachedCommonServiceImpl.java -text
342
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/cache/CdmClientCacheException.java -text
343
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/cache/CdmEntityCacheKey.java -text
344
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/cache/CdmModelCacher.java -text
345
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/cache/CdmModelFieldPropertyFromClass.java -text
346
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/cache/CdmRemoteCacheManager.java -text
347
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/cache/CdmTransientEntityCacher.java -text
348
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/cache/ICachedCommonService.java -text
349 349
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/server/CDMServerException.java -text
350 350
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/source/CdmPersistentRemoteSource.java -text
351 351
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/source/CdmRemoteSource.java -text
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CachedCommonServiceImpl.java
1
// $Id$
2
/**
3
* Copyright (C) 2014 EDIT
4
* European Distributed Institute of Taxonomy
5
* http://www.e-taxonomy.eu
6
*
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.
9
*/
10
package eu.etaxonomy.cdm.api.cache;
11

  
12
import java.util.ArrayList;
13
import java.util.HashMap;
14
import java.util.HashSet;
15
import java.util.List;
16
import java.util.Map;
17
import java.util.Set;
18
import java.util.TreeMap;
19
import java.util.TreeSet;
20

  
21
import org.hibernate.collection.internal.PersistentList;
22
import org.hibernate.collection.internal.PersistentMap;
23
import org.hibernate.collection.internal.PersistentSet;
24
import org.hibernate.collection.internal.PersistentSortedMap;
25
import org.hibernate.collection.internal.PersistentSortedSet;
26
import org.hibernate.collection.spi.PersistentCollection;
27
import org.springframework.beans.factory.annotation.Autowired;
28
import org.springframework.stereotype.Component;
29

  
30
import eu.etaxonomy.cdm.api.service.ICommonService;
31
import eu.etaxonomy.cdm.model.common.CdmBase;
32
import eu.etaxonomy.cdm.model.common.PersistentMultiLanguageText;
33
import eu.etaxonomy.taxeditor.remoting.CdmRemotingException;
34
import eu.etaxonomy.taxeditor.session.ICdmEntitySessionManager;
35
import eu.etaxonomy.cdm.api.cache.CdmTransientEntityCacher.CollectionType;;
36

  
37
/**
38
 * @author cmathew
39
 * @date 14 Oct 2014
40
 *
41
 */
42
@Component
43
public class CachedCommonServiceImpl implements ICachedCommonService {
44

  
45

  
46
    @Autowired
47
    private ICommonService commonService;
48

  
49
    private static boolean cacheEnabled = true;
50

  
51
    @Autowired
52
    private ICdmEntitySessionManager cdmEntitySessionManager;
53

  
54

  
55
    public static boolean isCacheEnabled() {
56
        return cacheEnabled;
57
    }
58

  
59
    public static void setCacheEnabled(boolean cacheEnabled) {
60
        CachedCommonServiceImpl.cacheEnabled = cacheEnabled;
61
    }
62

  
63
    /* (non-Javadoc)
64
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#find(java.lang.Class, int)
65
     */
66
    @Override
67
    public CdmBase find(Class<? extends CdmBase> clazz, int id) {
68
        if(cacheEnabled) {
69
            CdmBase cdmEntity = CdmBase.deproxy(commonService.find(clazz, id),clazz);
70
            return cdmEntitySessionManager.load(cdmEntity);
71
        } else {
72
            return CdmBase.deproxy(commonService.find(clazz, id),clazz);
73
        }
74
    }
75

  
76
    /* (non-Javadoc)
77
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#initializeCollection(org.hibernate.collection.spi.PersistentCollection)
78
     */
79
    @Override
80
    public PersistentCollection initializeCollection(PersistentCollection col) {
81
            PersistentCollection pc = commonService.initializeCollection(col);
82
            return pc;
83
    }
84

  
85
    @Override
86
    public void updatePersistentCollection(CollectionField colf) {
87
    	if(cacheEnabled) {
88
    		cdmEntitySessionManager.load(colf.getCollection());
89
    	}
90
    }
91

  
92
    /* (non-Javadoc)
93
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#isEmpty(org.hibernate.collection.spi.PersistentCollection)
94
     */
95
    @Override
96
    public boolean isEmpty(PersistentCollection col) {
97
            return commonService.isEmpty(col);
98

  
99
    }
100

  
101

  
102
    /* (non-Javadoc)
103
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#size(org.hibernate.collection.spi.PersistentCollection)
104
     */
105
    @Override
106
    public int size(PersistentCollection col) {
107
        return commonService.size(col);
108
    }
109

  
110

  
111
    /* (non-Javadoc)
112
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#get(org.hibernate.collection.spi.PersistentCollection, int)
113
     */
114
    @Override
115
    public Object get(PersistentCollection col, int index) {
116
        return commonService.get(col, index);
117
    }
118

  
119

  
120
    /* (non-Javadoc)
121
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#contains(org.hibernate.collection.spi.PersistentCollection, java.lang.Object)
122
     */
123
    @Override
124
    public boolean contains(PersistentCollection col, Object element) {
125
        return commonService.contains(col, element);
126
    }
127

  
128

  
129
    /* (non-Javadoc)
130
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#containsKey(org.hibernate.collection.spi.PersistentCollection, java.lang.Object)
131
     */
132
    @Override
133
    public boolean containsKey(PersistentCollection col, Object key) {
134
        return commonService.containsKey(col, key);
135
    }
136

  
137

  
138
    /* (non-Javadoc)
139
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#containsValue(org.hibernate.collection.spi.PersistentCollection, java.lang.Object)
140
     */
141
    @Override
142
    public boolean containsValue(PersistentCollection col, Object element) {
143
        return commonService.containsValue(col, element);
144
    }
145

  
146
    @SuppressWarnings("rawtypes")
147
	@Override
148
    public CollectionField getCollectionField(PersistentCollection pc) {
149
        if(pc != null) {
150
            if(pc instanceof PersistentSet) {
151
                return new CollectionField(new HashSet((Set)pc), CollectionType.SET);
152
            }
153
            if(pc instanceof PersistentSortedSet) {
154
                return new CollectionField(new TreeSet((Set)pc), CollectionType.SET);
155
            }
156
            if(pc instanceof PersistentList) {
157
                return new CollectionField(new ArrayList((List)pc), CollectionType.LIST);
158
            }
159
            if(pc instanceof PersistentMap || pc instanceof PersistentMultiLanguageText) {
160
                return new CollectionField(new HashMap((Map)pc), CollectionType.MAP);
161
            }
162
            if(pc instanceof PersistentSortedMap) {
163
                return new CollectionField(new TreeMap((Map)pc), CollectionType.MAP);
164
            }
165
            throw new CdmRemotingException("Cannot get Collection field for type " + pc.getClass().getName());
166
        }
167
        return null;
168
    }
169

  
170
    public class CollectionField {
171
        private final Object col;
172
        private final CollectionType type;
173
        public CollectionField(Object col, CollectionType type) {
174
            this.col = col;
175
            this.type = type;
176
        }
177

  
178
        public Object getCollection() {
179
            return this.col;
180
        }
181

  
182
        public CollectionType getType() {
183
            return this.type;
184
        }
185
    }
186

  
187

  
188

  
189
}
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CdmClientCacheException.java
1
package eu.etaxonomy.cdm.api.cache;
2

  
3
public class CdmClientCacheException extends RuntimeException {
4
	
5
	public CdmClientCacheException(String message) {
6
		super(message);
7
	}
8

  
9
	public CdmClientCacheException(Exception e) {
10
		super(e);
11
	}
12
}
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CdmEntityCacheKey.java
1
package eu.etaxonomy.cdm.api.cache;
2

  
3
import eu.etaxonomy.cdm.model.common.CdmBase;
4

  
5
public class CdmEntityCacheKey {
6

  
7
	private Class<? extends CdmBase> persistenceClass;
8
	private int persistenceId;
9
	
10
	public CdmEntityCacheKey(CdmBase cdmBase) {
11
		this.persistenceClass = cdmBase.getClass();
12
		this.persistenceId = cdmBase.getId();
13
	}
14
	
15
	public CdmEntityCacheKey(Class<? extends CdmBase> clazz, int id) {
16
		this.persistenceClass = clazz;
17
		this.persistenceId = id;
18
	}
19
	
20

  
21
	
22
	public Class<? extends CdmBase> getPersistenceClass() {
23
		return persistenceClass;
24
	}
25
	
26
	public int getPersistenceId() {
27
		return persistenceId;
28
	}
29
	@Override
30
	public boolean equals(Object obj) {
31
		if(obj == null || !(obj instanceof CdmEntityCacheKey)) {
32
			return false;
33
		}
34
		
35
		if(this == obj) {
36
			return true;
37
		}
38
		CdmEntityCacheKey that = (CdmEntityCacheKey) obj;
39
		if(this.persistenceClass.equals(that.persistenceClass) && this.persistenceId == that.persistenceId) {
40
			return true;
41
		}
42
		
43
		return false;
44
	}
45
	
46
	@Override
47
	public int hashCode() {
48
		return (this.persistenceClass.getName() + String.valueOf(this.persistenceId)).hashCode();
49
	}
50
	
51
	@Override
52
	public String toString() {
53
		return this.persistenceClass.getName() + String.valueOf(this.persistenceId);
54
	}
55

  
56
}
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CdmModelCacher.java
1
package eu.etaxonomy.cdm.api.cache;
2

  
3
import java.lang.reflect.Field;
4
import java.lang.reflect.Method;
5
import java.util.ArrayList;
6
import java.util.Arrays;
7
import java.util.Iterator;
8
import java.util.List;
9

  
10
import net.sf.ehcache.Cache;
11
import net.sf.ehcache.Element;
12

  
13
import org.apache.log4j.Logger;
14
import org.hibernate.cfg.Configuration;
15
import org.hibernate.mapping.PersistentClass;
16
import org.hibernate.mapping.Property;
17
import org.hibernate.property.Getter;
18

  
19

  
20
public class CdmModelCacher {
21

  
22

  
23
	private static final Logger logger = Logger.getLogger(CdmModelCacher.class);
24

  
25
	private List<CdmModelFieldPropertyFromClass> cmgmfcList = new ArrayList<CdmModelFieldPropertyFromClass>();
26

  
27
	public void cacheGetters() {
28

  
29
		Configuration configuration = new Configuration().configure("/eu/etaxonomy/cdm/mappings/hibernate.cfg.xml");
30
		configuration.buildMappings();
31
		Iterator<PersistentClass> classMappingIterator = configuration.getClassMappings();	  	  	  
32

  
33
		Cache cache = CdmRemoteCacheManager.getInstance().getCdmModelGetMethodsCache();
34
		cache.removeAll();
35

  
36
		while(classMappingIterator.hasNext()) {
37
			PersistentClass persistentClass = classMappingIterator.next();
38
			Class mappedClass = persistentClass.getMappedClass();
39
			String mappedClassName = mappedClass.getName();
40

  
41
			CdmModelFieldPropertyFromClass cmgmfc = new CdmModelFieldPropertyFromClass(mappedClassName);
42
			Iterator propertyIt = persistentClass.getPropertyIterator();	   
43

  
44
			logger.info("Adding class : " + mappedClassName + " to cache");
45
						
46
			while(propertyIt.hasNext())
47
			{
48
				Property property = (Property)propertyIt.next();
49
				Getter getter = property.getGetter(mappedClass);	      
50
				if(getter != null && getter.getMember() != null) {	   
51
					Field field = (Field)getter.getMember();
52
					String getMethod = getMethodNameFromFieldName(field.getName(), field.getType().getName());					
53
					logger.info(" - getMethod : " + getMethod + " for type " + field.getType().getName());
54
					cmgmfc.addGetMethods(getMethod);
55
				}
56
			}
57
			cache.put(new Element(mappedClassName, cmgmfc));
58

  
59
		}
60
		cache.flush();
61
	}
62
	
63
	public void cacheGetterFields() {
64

  
65
		Configuration configuration = new Configuration().configure("/eu/etaxonomy/cdm/mappings/hibernate.cfg.xml");
66
		configuration.buildMappings();
67
		Iterator<PersistentClass> classMappingIterator =   configuration.getClassMappings();	  	  	  
68

  
69
		Cache cache = CdmRemoteCacheManager.getInstance().getCdmModelGetMethodsCache();
70
		cache.removeAll();
71

  
72
		while(classMappingIterator.hasNext()) {
73
			PersistentClass persistentClass = classMappingIterator.next();
74
			Class mappedClass = persistentClass.getMappedClass();
75
			String mappedClassName = mappedClass.getName();
76

  
77
			CdmModelFieldPropertyFromClass cmgmfc = new CdmModelFieldPropertyFromClass(mappedClassName);
78
			Iterator propertyIt = persistentClass.getPropertyIterator();	   
79

  
80
			logger.info("Adding class : " + mappedClassName + " to cache");
81
						
82
			while(propertyIt.hasNext())
83
			{
84
				Property property = (Property)propertyIt.next();
85
				Getter getter = property.getGetter(mappedClass);	      
86
				if(getter != null && getter.getMember() != null) {	   
87
					Field field = (Field)getter.getMember();
88
					//String getMethod = getMethodNameFromFieldName(field.getName(), field.getType().getName());					
89
					logger.info(" - contains field '" + field.getName() + "' of type '" + field.getType().getName() + "'");
90
					cmgmfc.addGetMethods(field.getName());
91
				}
92
			}
93
			cache.put(new Element(mappedClassName, cmgmfc));
94

  
95
		}
96
		cache.flush();
97
	}
98
	
99
	public void checkGetterMethods() {
100

  
101
		Configuration configuration = new Configuration().configure("/eu/etaxonomy/cdm/mappings/hibernate.cfg.xml");
102
		configuration.buildMappings();
103
		Iterator<PersistentClass> classMappingIterator =   configuration.getClassMappings();	  	  	  
104

  
105
		Cache cache = CdmRemoteCacheManager.getInstance().getCdmModelGetMethodsCache();
106
		cache.removeAll();
107

  
108
		while(classMappingIterator.hasNext()) {
109
			PersistentClass persistentClass = classMappingIterator.next();
110
			Class mappedClass = persistentClass.getMappedClass();
111
			String mappedClassName = mappedClass.getName();
112
			
113
			Iterator propertyIt = persistentClass.getPropertyIterator();	   
114
			
115
			Method[] methods = mappedClass.getMethods();
116

  
117
			while(propertyIt.hasNext())
118
			{
119
				Property property = (Property)propertyIt.next();
120
				Getter getter = property.getGetter(mappedClass);	      
121
				if(getter != null && getter.getMember() != null) {	   
122
					Field field = (Field)getter.getMember();
123
					String getMethod = getMethodNameFromFieldName(field.getName(), field.getType().getName());					
124
					
125
					boolean foundMethod = false;
126
					for(Method method : methods) {
127
						if(method.getName().equals(getMethod)) {
128
							foundMethod = true;
129
							break;
130
						}
131
					}
132
					if(!foundMethod) {
133
						logger.info("Inferred method " + getMethod + " does not exist in class " + mappedClassName);
134
						//throw new CdmClientCacheException("Inferred method " + getMethod + " does not exist in class " + mappedClassName);
135
					}
136
				}
137
			}
138
			
139

  
140
		}
141
		
142
	}
143

  
144
	public List<CdmModelFieldPropertyFromClass> getCdmModelGetMethodFromClassList() {
145
		cmgmfcList.clear();
146
		Configuration configuration = new Configuration().configure("/eu/etaxonomy/cdm/mappings/hibernate.cfg.xml");
147
		configuration.buildMappings();
148
		Iterator<PersistentClass> classMappingIterator =   configuration.getClassMappings();	  	  	  					 
149

  
150
		while(classMappingIterator.hasNext()) {
151
			PersistentClass persistentClass = classMappingIterator.next();
152
			Class mappedClass = persistentClass.getMappedClass();
153
			String mappedClassName = mappedClass.getName();
154

  
155
			CdmModelFieldPropertyFromClass cmgmfc = new CdmModelFieldPropertyFromClass(mappedClassName);
156
			Iterator propertyIt = persistentClass.getPropertyIterator();	   
157

  
158
			while(propertyIt.hasNext())
159
			{
160
				Property property = (Property)propertyIt.next();
161
				Getter getter = property.getGetter(mappedClass);	      
162
				if(getter != null && getter.getMember() != null) {	
163
					Field field = (Field)getter.getMember();
164
					String getMethod = getMethodNameFromFieldName(getter.getMember().getName(),field.getType().getName());		    	 
165
					cmgmfc.addGetMethods(getMethod);
166
				}
167
			}
168
			cmgmfcList.add(cmgmfc);
169
		}
170
		return cmgmfcList;
171

  
172
	}
173

  
174
	public static String getMethodNameFromFieldName(String fieldName, String type) {
175
		String prefix = type != null && type.toLowerCase().endsWith("boolean") ? "is" : "get";		
176
		String getMethod =  prefix + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
177
		return getMethod;
178
	}
179
	
180

  
181

  
182

  
183

  
184
}
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CdmModelFieldPropertyFromClass.java
1
package eu.etaxonomy.cdm.api.cache;
2

  
3
import java.io.Serializable;
4
import java.util.ArrayList;
5
import java.util.List;
6

  
7
public class CdmModelFieldPropertyFromClass implements Serializable {
8

  
9
	private static final long serialVersionUID = 5726395976531887526L;
10
	private String className;
11
	private String parentClassName;
12
	
13
	private List<String> fields = new ArrayList<String>();
14
	
15
	
16
	public CdmModelFieldPropertyFromClass(String className) {
17
		this.setClassName(className);
18
	}
19
	
20
	public String getParentClassName() {
21
		return parentClassName;
22
	}
23

  
24
	public void setParentClassName(String parentClassName) {
25
		this.parentClassName = parentClassName;
26
	}
27

  
28
	public List<String> getFields() {
29
		return fields;
30
	}
31

  
32
	public void setFields(List<String> fields) {
33
		this.fields = fields;
34
	}
35
	
36
	public void addGetMethods(String getMethod) {
37
		this.fields.add(getMethod);
38
	}
39

  
40
	public String getClassName() {
41
		return className;
42
	}
43

  
44
	public void setClassName(String className) {
45
		this.className = className;
46
	}
47
	
48

  
49
	
50
	
51
}
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CdmRemoteCacheManager.java
1
package eu.etaxonomy.cdm.api.cache;
2

  
3
import java.io.File;
4
import java.io.IOException;
5
import java.io.InputStream;
6

  
7
import net.sf.ehcache.Cache;
8
import net.sf.ehcache.CacheException;
9
import net.sf.ehcache.CacheManager;
10

  
11
import org.springframework.core.io.ClassPathResource;
12
import org.springframework.core.io.Resource;
13
import org.springframework.stereotype.Component;
14

  
15
import eu.etaxonomy.cdm.common.CdmUtils;
16

  
17

  
18
public class CdmRemoteCacheManager {	
19
	
20
	private CacheManager cdmlibModelCacheManager;
21
	
22
	private static CdmRemoteCacheManager cdmRemoteCacheManager = null;
23
	
24
    public static final Resource CDMLIB_CACHE_MANAGER_CONFIG_RESOURCE =
25
            new ClassPathResource("cdmlib-ehcache.xml");
26
    
27
	
28
    public enum CdmCacheManagerType {
29
    	CDMLIB_MODEL,
30
    	DEFAULT
31
    }
32

  
33
    public static CdmRemoteCacheManager getInstance(){
34
    	if(cdmRemoteCacheManager == null) {    		
35
    		cdmRemoteCacheManager = new CdmRemoteCacheManager();  		
36
    	}
37
    	return cdmRemoteCacheManager;
38
    }
39
    private CdmRemoteCacheManager() {
40
    	
41
    	System.setProperty("ehcache.disk.store.dir", CdmUtils.getCdmHomeDir().getAbsolutePath() + File.separator + "cdmlib-model");    			
42
    	try {
43
    		// NOTE:Programmatically creating the cache manager may solve the problem of 
44
    		//      recreating data written to disk on startup
45
    		//      see https://stackoverflow.com/questions/1729605/ehcache-persist-to-disk-issues
46
    		//String cacheFilePath = CDMLIB_CACHE_MANAGER_CONFIG_RESOURCE.getFile().getAbsolutePath();
47
    		InputStream in = this.getClass().getClassLoader().getResourceAsStream("cdmlib-ehcache.xml");
48
			cdmlibModelCacheManager = new CacheManager(in);
49
			
50
		} catch (CacheException e) {
51
			throw new CdmClientCacheException(e);
52
		}
53
//		} catch (IOException e) {
54
//			throw new CdmClientCacheException(e);
55
//		}
56
    }
57
    
58
	public Cache getCdmModelGetMethodsCache(){
59
		return cdmlibModelCacheManager.getCache("cdmModelGetMethodsCache");
60
	}
61
	
62
	public void shutdown(CdmCacheManagerType ccmt) {
63
		CacheManager cm;
64
		switch(ccmt) {		
65
		case CDMLIB_MODEL:			
66
			cdmlibModelCacheManager.shutdown();
67
			break;
68
		case DEFAULT:
69
			cm = CacheManager.create();
70
			cm.shutdown();
71
			break;
72
		default:
73
			//do nothing
74
		}		
75
	}
76
	
77
	public static void checkCacheProperties() {
78
		String pathToCache = System.getProperty("ehcache.disk.store.dir");
79
		if(pathToCache == null || pathToCache.isEmpty()) {
80
			throw new CdmClientCacheException("'ehcache.disk.store.dir' property is not set");
81
		}
82
	}
83

  
84
}
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CdmServiceCacher.java
5 5
import org.springframework.beans.factory.annotation.Autowired;
6 6
import org.springframework.stereotype.Component;
7 7

  
8
import eu.etaxonomy.cdm.api.cache.CdmCacher;
9 8
import eu.etaxonomy.cdm.api.service.ITermService;
10 9
import eu.etaxonomy.cdm.model.common.CdmBase;
10
import eu.etaxonomy.taxeditor.remoting.cache.CdmTransientEntityCacher;
11 11

  
12 12
/**
13 13
 * Class which uses CDM services to cache cdm entities
......
25 25

  
26 26
	@Autowired
27 27
	ITermService termService;
28
	
28

  
29 29
	@Override
30 30
	protected void setup() {
31
		CdmTransientEntityCacher.setDefaultCacher(this);		
31
		CdmTransientEntityCacher.setDefaultCacher(this);
32 32
	}
33
	
33

  
34 34
	@Override
35 35
	protected CdmBase findByUuid(UUID uuid) {
36 36
		CdmBase term = termService.findWithoutFlush(uuid);
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/CdmTransientEntityCacher.java
1
// $Id$
2
/**
3
 * Copyright (C) 2014 EDIT
4
 * European Distributed Institute of Taxonomy
5
 * http://www.e-taxonomy.eu
6
 *
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.
9
 */
10
package eu.etaxonomy.cdm.api.cache;
11

  
12
import java.io.Serializable;
13
import java.lang.reflect.Field;
14
import java.lang.reflect.InvocationTargetException;
15
import java.lang.reflect.Method;
16
import java.util.ArrayList;
17
import java.util.Collection;
18
import java.util.HashSet;
19
import java.util.Iterator;
20
import java.util.List;
21
import java.util.Map;
22
import java.util.Set;
23
import java.util.UUID;
24

  
25
import javassist.util.proxy.ProxyFactory;
26

  
27
import net.sf.ehcache.Cache;
28
import net.sf.ehcache.Element;
29
import net.sf.ehcache.config.CacheConfiguration;
30
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
31

  
32
import org.apache.log4j.Logger;
33
import org.hibernate.collection.spi.PersistentCollection;
34
import org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer;
35
import org.springframework.beans.factory.annotation.Autowired;
36
import org.springframework.util.ReflectionUtils;
37

  
38
import eu.etaxonomy.cdm.api.service.ICommonService;
39
import eu.etaxonomy.cdm.model.common.CdmBase;
40
import eu.etaxonomy.taxeditor.session.ICdmEntitySessionManager;
41

  
42
/**
43
 * 
44
 * This cache guarantees that
45
 *  - all objects put will be ancestors of CdmBase
46
 *  - all CdmBase objects in the cache will be already de-proxied
47
 *  - after any CdmBase object is put in the cache, 
48
 *  all non-null / non-proxy CdmBase objects in the sub-graph 
49
 *  will also be present in the cache.
50
 *   
51
 * @author cmathew
52
 * @date 14 Oct 2014
53
 *
54
 */
55

  
56
public class CdmTransientEntityCacher  {
57

  
58
	private static final Logger logger = Logger.getLogger(CdmTransientEntityCacher.class);
59

  
60
    
61
    private ICdmEntitySessionManager cdmEntitySessionManager;
62
    
63
	private static CdmServiceCacher cdmServiceCacher;
64
    
65
	private String cacheId;
66

  
67
	private Cache cache; 
68

  
69
	private Cache cdmlibModelCache;
70

  
71
	private static boolean isRecursiveEnabled = true;
72

  
73
    public static enum CollectionType {
74
        SET,
75
        LIST,
76
        MAP;
77

  
78
        @Override
79
        public String toString() {
80
            return this.name().toLowerCase();
81
        }
82
    }
83
    
84
	private CdmTransientEntityCacher() {
85
		
86
	}
87
	
88
	public CdmTransientEntityCacher(String cacheId, ICdmEntitySessionManager cdmEntitySessionManager) {
89
		this.cacheId = cacheId;
90

  
91
		cache = new Cache(getEntityCacheConfiguration(cacheId));    	    	
92
		cdmServiceCacher.getDefaultCacheManager().addCache(cache);
93

  
94
		cdmlibModelCache = CdmRemoteCacheManager.getInstance().getCdmModelGetMethodsCache();
95
		this.cdmEntitySessionManager = cdmEntitySessionManager;
96
	}
97

  
98
	public CdmTransientEntityCacher(Object obj, ICdmEntitySessionManager cdmEntitySessionManager) {
99
		this(obj.getClass().getName() +  String.valueOf(obj.hashCode()), cdmEntitySessionManager);
100
	}
101

  
102
	/**
103
	 * Returns the default cache configuration.
104
	 *
105
	 * @return
106
	 */
107
	private CacheConfiguration getEntityCacheConfiguration(String cacheId) {
108
		// For a better understanding on how to size caches, refer to
109
		// http://ehcache.org/documentation/configuration/cache-size
110
		return new CacheConfiguration(cacheId, 500)        
111
		.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU)
112
		.eternal(false)
113
		// default ttl and tti set to 2 hours
114
		.timeToLiveSeconds(60*60*2)
115
		.timeToIdleSeconds(60*60*2);
116

  
117
	}
118

  
119
	public static void setDefaultCacher(CdmServiceCacher css) {
120
		cdmServiceCacher = css;
121
	}
122
	
123
	/**
124
	 * Returns the cache corresponding to the cache id
125
	 *
126
	 * @param cacheId
127
	 * @return
128
	 */
129
	private Cache getCache() {
130
		return cdmServiceCacher.getDefaultCacheManager().getCache(cacheId);
131
	}
132

  
133
	@SuppressWarnings("unchecked")
134
	public <T extends Object> T load(T obj, boolean recursive) {
135
		if(obj instanceof CdmBase) {
136
			return load(obj, recursive);
137
		} else if (obj instanceof Map) {
138
			return (T) load((Map<T,T>)obj, recursive);
139
		} else if (obj instanceof Collection) {
140
			return (T) load((Collection<T>)obj, recursive);
141
		} 
142
		
143
		return obj;
144
	}
145
	
146
	@SuppressWarnings("unchecked")
147
	private <T extends Object> T loadRecursive(T obj, Set<CdmBase> alreadyVisitedEntities) {
148
		if(obj instanceof CdmBase) {
149
			return (T) loadRecursive((CdmBase)obj, alreadyVisitedEntities);
150
		} else if (obj instanceof Map) {
151
			return (T) load((Map<T,T>)obj, alreadyVisitedEntities);
152
		} else if (obj instanceof Collection) {
153
			return (T) load((Collection<T>)obj, alreadyVisitedEntities);
154
		} 
155
		
156
		logger.info("No caching yet for type " + obj.getClass().getName());
157
		
158
		return obj;
159
	}
160
	
161
	public <T extends Object> Map<T,T> load(Map<T,T> map, boolean recursive){
162
		if(isRecursiveEnabled && recursive) {
163
			logger.info("---- starting recursive load for cdm entity map");
164
			Set<CdmBase> alreadyVisitedEntities = new HashSet<CdmBase>();
165
			Map<T,T> cachedMap = load(map, alreadyVisitedEntities);
166
			alreadyVisitedEntities.clear();
167
			logger.info("---- ending recursive load for cdm entity map \n");
168
			return cachedMap;
169
		} else {
170
			return load(map, null);
171
		}
172
	}
173
	
174

  
175
	private <T extends Object> Map<T,T> load(Map<T,T> map, Set<CdmBase> alreadyVisitedEntities){
176
        if(map == null || map.isEmpty()) {
177
            return map;
178
        }
179

  
180
        int originalMapSize = map.size();
181
        Object[] result = new Object[ map.size() * 2 ];
182
        Iterator<Map.Entry<T,T>> iter = map.entrySet().iterator();
183
        int i=0;
184
        while ( iter.hasNext() ) {
185
            Map.Entry<T,T> e = (Map.Entry<T,T>) iter.next();
186
            result[i++] = e.getKey();
187
            result[i++] = e.getValue();
188
        }
189

  
190
        for(i=0; i<result.length;i++) {            
191
        	if(alreadyVisitedEntities == null) {
192
        		result[i] = load(result[i], false);
193
        	} else {        		      
194
        		result[i] = loadRecursive(result[i], alreadyVisitedEntities);
195
        	}
196
        }
197
        map.clear();
198
        for(i = 0; i < originalMapSize; i+=2 ) {
199
            map.put(
200
                    (T)result[i],
201
                    (T)result[i+1]
202
                );
203
        }
204
        return map;
205
	}
206
	
207
	public <T extends Object> Collection<T> load(Collection<T> collection, boolean recursive){
208
		Collection<T> loadedCollection;
209
		if(isRecursiveEnabled && recursive) {
210
			logger.info("---- starting recursive load for cdm entity collection");
211
			Set<CdmBase> alreadyVisitedEntities = new HashSet<CdmBase>();
212
			Collection<T> cachedCollection = load(collection, alreadyVisitedEntities);
213
			alreadyVisitedEntities.clear();
214
			logger.info("---- ending recursive load for cdm entity collection \n");
215
			loadedCollection = cachedCollection;
216
		} else {
217
			loadedCollection = load(collection, null);
218
		}		
219
		return loadedCollection;
220
	}
221
	
222
	@SuppressWarnings("unchecked")
223
	private <T extends Object> Collection<T> load(Collection<T> collection, Set<CdmBase> alreadyVisitedEntities){
224
		int length = collection.size();
225
		Object[] result = new Object[length];
226
		Iterator<T> collectionItr = collection.iterator();
227
		int count = 0;
228
		while(collectionItr.hasNext()) {
229
			if(alreadyVisitedEntities == null) {
230
        		result[count] = load(collectionItr.next(), false);
231
        	} else {        		      
232
        		result[count] = loadRecursive(collectionItr.next(), alreadyVisitedEntities);
233
        	}	
234
			count++;
235
		}
236
		
237
		collection.clear();
238
						
239
		for ( int i = 0; i < length; i++ ) {
240
			collection.add((T)result[i]);
241
		}
242
		
243
		return collection;
244
	}
245

  
246
	
247
	/**
248
	 * Puts the (Key,Value) pair of ({@link java.util.UUID}, {@link eu.etaxonomy.cdm.model.common.CdmBase}),
249
	 * in the cache corresponding to the given cache id
250
	 *
251
	 * @param cacheId
252
	 * @param uuid
253
	 * @param cdmEntity
254
	 */
255
	public CdmBase load(CdmBase cdmEntity, boolean recursive) {		
256
		CdmBase loadedCdmBase;
257
		if(isRecursiveEnabled && recursive) {
258
			logger.info("---- starting recursive load for cdm entity " + cdmEntity.getClass().getName() + " with id " + cdmEntity.getId());
259
			Set<CdmBase> alreadyVisitedEntities = new HashSet<CdmBase>();
260
			CdmBase cb =  loadRecursive(cdmEntity, alreadyVisitedEntities);
261
			alreadyVisitedEntities.clear();
262
			logger.info("---- ending recursive load for cdm entity " + cdmEntity.getClass().getName() + " with id " + cdmEntity.getId() + "\n");
263
			loadedCdmBase =  cb;
264
		} else {
265
			loadedCdmBase = load(cdmEntity);
266
		}		
267
		return loadedCdmBase;
268
		
269
	}
270

  
271
	
272
	private CdmBase load(CdmBase cdmEntity) {
273
		logger.info("loading object of type " + cdmEntity.getClass().getName() + " with id " + cdmEntity.getId());
274

  
275
		// start by looking up the cdm entity in the cache
276
		CdmBase cachedCdmEntity = getFromCache(cdmEntity);
277
		
278
		if(cachedCdmEntity != null) {
279
			// if cdm entity was found in cache then return ...
280
			logger.info(" - object of type " + cdmEntity.getClass().getName() + " with id " + cdmEntity.getId() + " already exists");
281
			return cachedCdmEntity;
282
		} else {        	
283
			// ... else save the entity in the cache    	
284
			getCache().put(new Element(generateKey(cdmEntity), cdmEntity));
285
			logger.info(" - object of type " + cdmEntity.getClass().getName() + " with id " + cdmEntity.getId() + " put in cache");
286
			return cdmEntity;
287
		}         
288
	}
289
	
290
	private CdmBase loadRecursive(CdmBase cdmEntity, Set<CdmBase> alreadyVisitedEntities) {
291

  
292
		CdmBase cachedCdmEntity = load(cdmEntity);
293
		
294
		// we want to recursive through the cdmEntity (and not the cachedCdmEntity)
295
		// since there could be new initialized object in the cdmEntity sub-graph
296
		
297
		// start by getting the fields from the cdm entity
298
		String className = cdmEntity.getClass().getName();
299
		CdmModelFieldPropertyFromClass cmgmfc = getFromCdmlibModelCache(className);
300
		if(cmgmfc != null) {
301
			alreadyVisitedEntities.add(cdmEntity);
302
			List<String> fields = cmgmfc.getFields();
303
			for(String field : fields) {
304
				// retrieve the actual object corresponding to the field.
305
				// this object will be either a CdmBase or a Collection / Map
306
				// with CdmBase as the generic type
307

  
308
				// In the case that the returned is either a Collection or a Map
309
				// the individual objects inside these also need to be loaded
310
				// by calling the corresponding cachify method in the
311
				// CdmEntityCachingUtils   
312

  
313
				CdmBase cdmEntityInSubGraph = getCdmBaseTypeFieldValue(cdmEntity, cachedCdmEntity, field, alreadyVisitedEntities);
314
				if(cdmEntityInSubGraph != null) {
315
					if(!alreadyVisitedEntities.contains(cdmEntityInSubGraph)) {												
316
						logger.info("recursive loading object of type " + cdmEntityInSubGraph.getClass().getName() + " with id " + cdmEntityInSubGraph.getId());
317
						loadRecursive(cdmEntityInSubGraph, alreadyVisitedEntities);
318
					} else {
319
						logger.info("object of type " + cdmEntityInSubGraph.getClass().getName() + " with id " + cdmEntityInSubGraph.getId() + "already visited");
320
					}
321
				}
322
			}
323
		} else {
324
			throw new CdmClientCacheException("CdmEntity with class " + cdmEntity.getClass().getName() + " is not found in the cdmlib model cache. " +
325
					"The cache may be corrupted or not in sync with the latest model version" );
326
		}
327
		return cachedCdmEntity;
328
	}
329

  
330
	
331
	private CdmBase getCdmBaseTypeFieldValue(CdmBase cdmEntity, 
332
			CdmBase cachedCdmEntity, 
333
			String fieldName,
334
			Set<CdmBase> alreadyVisitedEntities) {
335
		
336
		
337
		if(cachedCdmEntity == null) {
338
			throw new CdmClientCacheException("When trying to set field value, the cached cdm entity cannot be null");
339
		}
340
		
341
		Class<?> clazz = cdmEntity.getClass();
342
		try {
343
			// this call will search in the provided class as well as
344
			// the super classes until it finds the field
345
			Field field = ReflectionUtils.findField(clazz, fieldName);
346

  
347
			if(field == null) {
348
				throw new CdmClientCacheException("Field '" + fieldName 
349
						+ "' not found when searching in class '" + clazz.getName() + "' and its supercalsses");
350
			}
351
			field.setAccessible(true);
352
			Object o = field.get(cdmEntity);
353

  
354
			CdmBase cdmEntityInSubGraph = null;
355
			if(o != null 
356
					&& !ProxyFactory.isProxyClass(o.getClass()) 
357
					&& !(o instanceof PersistentCollection)	) {
358

  
359
				
360
				if(CdmBase.class.isAssignableFrom(o.getClass())) {
361
					logger.info("found initialised cdm entity '" + fieldName + "' in object of type " + clazz.getName() + " with id " + cdmEntity.getId());
362
					cdmEntityInSubGraph  = (CdmBase)o;
363
					CdmBase cachedCdmEntityInSubGraph = getFromCache(cdmEntityInSubGraph);
364

  
365
					if(cachedCdmEntityInSubGraph != null) {
366
						if(cachedCdmEntityInSubGraph != cdmEntityInSubGraph) {				
367
							field.set(cachedCdmEntity, cachedCdmEntityInSubGraph);
368
						}
369
					} else {
370
						field.set(cachedCdmEntity, cdmEntityInSubGraph);
371
					}
372
				} else if(o instanceof Map) {
373
					loadRecursive((Map)o, alreadyVisitedEntities);
374
				} else if(o instanceof Collection) {
375
					loadRecursive((Collection)o, alreadyVisitedEntities);
376
				}
377
			} 
378
			// we return the original cdm entity in the sub graph because we
379
			// want to continue to recurse on the input cdm entity graph
380
			// and not the one in the cache
381
			return cdmEntityInSubGraph;
382
		} catch (SecurityException e) {
383
			throw new CdmClientCacheException(e);
384
		} catch (IllegalArgumentException e) {
385
			throw new CdmClientCacheException(e);
386
		} catch (IllegalAccessException e) {
387
			throw new CdmClientCacheException(e);
388
		}        
389
	}
390

  
391
	public void put(CdmBase cdmEntity) {    	
392
		CdmEntityCacheKey id = new CdmEntityCacheKey(cdmEntity);
393
		Element cachedCdmEntityElement = getCacheElement(id);
394

  
395
		if(cachedCdmEntityElement == null) {
396
			cachedCdmEntityElement = cdmServiceCacher.getCacheElement(cdmEntity.getUuid());
397
			if(cachedCdmEntityElement != null) {
398
				logger.info("Cdm Entity with id : " + cdmEntity.getId() + " already exists in permanent cache. Ignoring put.");
399
				return;
400
			}
401
		}
402
		
403
		getCache().put(new Element(id, cdmEntity));       
404
	}
405

  
406

  
407
	private Element getCacheElement(CdmEntityCacheKey key) {
408
		return getCache().get(key);
409
	}
410

  
411
	public CdmModelFieldPropertyFromClass getFromCdmlibModelCache(String className) {
412
		Element e = cdmlibModelCache.get(className);
413
		if (e == null) {
414
			return null;
415
		} else {
416
			return (CdmModelFieldPropertyFromClass) e.getObjectValue();
417
		}
418
	}
419

  
420
	public CdmBase getFromCache(CdmEntityCacheKey id) {
421
		Element e = getCacheElement(id);
422
		if (e == null) {
423
			return null;
424
		} else {
425
			return (CdmBase) e.getObjectValue();
426
		}
427
	}
428

  
429
	public CdmBase getFromCache(Class<? extends CdmBase> clazz, int id) {
430
		CdmEntityCacheKey cacheId = generateKey(clazz,id);
431
		return getFromCache(cacheId);
432
	}
433

  
434
	public CdmBase getFromCache(CdmBase cdmBase) {
435
		
436
		CdmEntityCacheKey cacheId = generateKey(cdmBase);
437
		CdmBase cachedCdmEntity = getFromCache(cacheId);
438

  
439
		if(cachedCdmEntity == null) {
440
			// ... then try the permanent (uuid-based) cache
441
			cachedCdmEntity = cdmServiceCacher.getFromCache(cdmBase.getUuid());        	
442
		}
443

  
444
		return cachedCdmEntity;
445
	}
446
	
447
	public CdmBase getFromCache(CdmBase cdmBase, Class<? extends CdmBase> clazz) {
448
		
449
		cdmBase = CdmBase.deproxy(cdmBase, clazz);		
450
		CdmEntityCacheKey cacheId = generateKey(cdmBase);
451

  
452
		CdmBase cachedCdmEntity = getFromCache(cacheId);
453

  
454
		if(cachedCdmEntity == null) {
455
			// ... then try the permanent (uuid-based) cache
456
			cachedCdmEntity = cdmServiceCacher.getFromCache(cdmBase.getUuid());        	
457
		}
458

  
459
		return cachedCdmEntity;
460
	}
461

  
462
	public List<CdmBase> getAllEntities() {
463
		List<CdmBase> entities = new ArrayList<CdmBase>();
464
		Map<String, CdmBase> elementsMap = getCache().getAllWithLoader(getCache().getKeys(), null);
465
		for (Map.Entry<String, CdmBase> entry : elementsMap.entrySet()) {
466
			entities.add(entry.getValue());
467
		}
468
		return entities;
469
	}
470

  
471
	public boolean exists(CdmEntityCacheKey key) {
472
		return (getCacheElement(key) != null);
473
	}
474

  
475
	public boolean existsAndIsNotNull(CdmEntityCacheKey id) {
476
		return getFromCache(id) != null;
477
	}
478
	
479
	public void dispose() {
480
		cache.removeAll();
481
		cache.flush();
482
	}
483

  
484

  
485
	public static CdmEntityCacheKey generateKey(Class<? extends CdmBase> clazz, int id) {
486
		return new CdmEntityCacheKey(clazz, id);
487
	}
488

  
489

  
490
	public static CdmEntityCacheKey generateKey(CdmBase cdmBase) {
491
		Class<? extends CdmBase> entityClass = cdmBase.getClass();
492
		int id = cdmBase.getId();
493
		return new CdmEntityCacheKey(entityClass, id);
494
	}
495

  
496
	public static boolean isRecursiveEnabled() {
497
		return isRecursiveEnabled;
498
	}
499

  
500
	public static void  setRecursiveEnabled(boolean ire) {
501
		isRecursiveEnabled = ire;
502
	}
503

  
504
}
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/cdm/api/cache/ICachedCommonService.java
1
// $Id$
2
/**
3
 * Copyright (C) 2014 EDIT
4
 * European Distributed Institute of Taxonomy
5
 * http://www.e-taxonomy.eu
6
 *
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.
9
 */
10
package eu.etaxonomy.cdm.api.cache;
11

  
12
import org.hibernate.collection.spi.PersistentCollection;
13

  
14
import eu.etaxonomy.cdm.api.cache.CachedCommonServiceImpl.CollectionField;
15
import eu.etaxonomy.cdm.model.common.CdmBase;
16

  
17
/**
18
 * @author cmathew
19
 * @date 14 Oct 2014
20
 *
21
 */
22
public interface ICachedCommonService {
23

  
24
    public CdmBase find(Class<? extends CdmBase> clazz, int id);
25

  
26
    public PersistentCollection initializeCollection(PersistentCollection col);
27

  
28
	public void updatePersistentCollection(CollectionField colf);
29

  
30
    public boolean isEmpty(PersistentCollection col);
31

  
32
    public int size(PersistentCollection col);
33

  
34
    public Object get(PersistentCollection col, int index);
35

  
36
    public boolean contains(PersistentCollection col, Object element);
37

  
38
    public boolean containsKey(PersistentCollection col, Object key);
39

  
40
    public boolean containsValue(PersistentCollection col, Object element);
41

  
42
    public CollectionField getCollectionField(PersistentCollection pc);
43

  
44

  
45

  
46
}
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/cache/CachedCommonServiceImpl.java
1
// $Id$
2
/**
3
* Copyright (C) 2014 EDIT
4
* European Distributed Institute of Taxonomy
5
* http://www.e-taxonomy.eu
6
*
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.
9
*/
10
package eu.etaxonomy.taxeditor.remoting.cache;
11

  
12
import java.util.ArrayList;
13
import java.util.HashMap;
14
import java.util.HashSet;
15
import java.util.List;
16
import java.util.Map;
17
import java.util.Set;
18
import java.util.TreeMap;
19
import java.util.TreeSet;
20

  
21
import org.hibernate.collection.internal.PersistentList;
22
import org.hibernate.collection.internal.PersistentMap;
23
import org.hibernate.collection.internal.PersistentSet;
24
import org.hibernate.collection.internal.PersistentSortedMap;
25
import org.hibernate.collection.internal.PersistentSortedSet;
26
import org.hibernate.collection.spi.PersistentCollection;
27
import org.springframework.beans.factory.annotation.Autowired;
28
import org.springframework.stereotype.Component;
29

  
30
import eu.etaxonomy.cdm.api.service.ICommonService;
31
import eu.etaxonomy.cdm.model.common.CdmBase;
32
import eu.etaxonomy.cdm.model.common.PersistentMultiLanguageText;
33
import eu.etaxonomy.taxeditor.remoting.CdmRemotingException;
34
import eu.etaxonomy.taxeditor.remoting.cache.CdmTransientEntityCacher.CollectionType;
35
import eu.etaxonomy.taxeditor.session.ICdmEntitySessionManager;
36

  
37
/**
38
 * @author cmathew
39
 * @date 14 Oct 2014
40
 *
41
 */
42
@Component
43
public class CachedCommonServiceImpl implements ICachedCommonService {
44

  
45

  
46
    @Autowired
47
    private ICommonService commonService;
48

  
49
    private static boolean cacheEnabled = true;
50

  
51
    @Autowired
52
    private ICdmEntitySessionManager cdmEntitySessionManager;
53

  
54

  
55
    public static boolean isCacheEnabled() {
56
        return cacheEnabled;
57
    }
58

  
59
    public static void setCacheEnabled(boolean cacheEnabled) {
60
        CachedCommonServiceImpl.cacheEnabled = cacheEnabled;
61
    }
62

  
63
    /* (non-Javadoc)
64
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#find(java.lang.Class, int)
65
     */
66
    @Override
67
    public CdmBase find(Class<? extends CdmBase> clazz, int id) {
68
        if(cacheEnabled) {
69
            CdmBase cdmEntity = CdmBase.deproxy(commonService.find(clazz, id),clazz);
70
            return cdmEntitySessionManager.load(cdmEntity);
71
        } else {
72
            return CdmBase.deproxy(commonService.find(clazz, id),clazz);
73
        }
74
    }
75

  
76
    /* (non-Javadoc)
77
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#initializeCollection(org.hibernate.collection.spi.PersistentCollection)
78
     */
79
    @Override
80
    public PersistentCollection initializeCollection(PersistentCollection col) {
81
            PersistentCollection pc = commonService.initializeCollection(col);
82
            return pc;
83
    }
84

  
85
    @Override
86
    public void updatePersistentCollection(CollectionField colf) {
87
    	if(cacheEnabled) {
88
    		cdmEntitySessionManager.load(colf.getCollection());
89
    	}
90
    }
91

  
92
    /* (non-Javadoc)
93
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#isEmpty(org.hibernate.collection.spi.PersistentCollection)
94
     */
95
    @Override
96
    public boolean isEmpty(PersistentCollection col) {
97
            return commonService.isEmpty(col);
98

  
99
    }
100

  
101

  
102
    /* (non-Javadoc)
103
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#size(org.hibernate.collection.spi.PersistentCollection)
104
     */
105
    @Override
106
    public int size(PersistentCollection col) {
107
        return commonService.size(col);
108
    }
109

  
110

  
111
    /* (non-Javadoc)
112
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#get(org.hibernate.collection.spi.PersistentCollection, int)
113
     */
114
    @Override
115
    public Object get(PersistentCollection col, int index) {
116
        return commonService.get(col, index);
117
    }
118

  
119

  
120
    /* (non-Javadoc)
121
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#contains(org.hibernate.collection.spi.PersistentCollection, java.lang.Object)
122
     */
123
    @Override
124
    public boolean contains(PersistentCollection col, Object element) {
125
        return commonService.contains(col, element);
126
    }
127

  
128

  
129
    /* (non-Javadoc)
130
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#containsKey(org.hibernate.collection.spi.PersistentCollection, java.lang.Object)
131
     */
132
    @Override
133
    public boolean containsKey(PersistentCollection col, Object key) {
134
        return commonService.containsKey(col, key);
135
    }
136

  
137

  
138
    /* (non-Javadoc)
139
     * @see eu.etaxonomy.taxeditor.remoting.service.ICachedCommonService#containsValue(org.hibernate.collection.spi.PersistentCollection, java.lang.Object)
140
     */
141
    @Override
142
    public boolean containsValue(PersistentCollection col, Object element) {
143
        return commonService.containsValue(col, element);
144
    }
145

  
146
    @SuppressWarnings("rawtypes")
147
	@Override
148
    public CollectionField getCollectionField(PersistentCollection pc) {
149
        if(pc != null) {
150
            if(pc instanceof PersistentSet) {
151
                return new CollectionField(new HashSet((Set)pc), CollectionType.SET);
152
            }
153
            if(pc instanceof PersistentSortedSet) {
154
                return new CollectionField(new TreeSet((Set)pc), CollectionType.SET);
155
            }
156
            if(pc instanceof PersistentList) {
157
                return new CollectionField(new ArrayList((List)pc), CollectionType.LIST);
158
            }
159
            if(pc instanceof PersistentMap || pc instanceof PersistentMultiLanguageText) {
160
                return new CollectionField(new HashMap((Map)pc), CollectionType.MAP);
161
            }
162
            if(pc instanceof PersistentSortedMap) {
163
                return new CollectionField(new TreeMap((Map)pc), CollectionType.MAP);
164
            }
165
            throw new CdmRemotingException("Cannot get Collection field for type " + pc.getClass().getName());
166
        }
167
        return null;
168
    }
169

  
170
    public class CollectionField {
171
        private final Object col;
172
        private final CollectionType type;
173
        public CollectionField(Object col, CollectionType type) {
174
            this.col = col;
175
            this.type = type;
176
        }
177

  
178
        public Object getCollection() {
179
            return this.col;
180
        }
181

  
182
        public CollectionType getType() {
183
            return this.type;
184
        }
185
    }
186

  
187

  
188

  
189
}
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/cache/CdmClientCacheException.java
1
package eu.etaxonomy.taxeditor.remoting.cache;
2

  
3
public class CdmClientCacheException extends RuntimeException {
4
	
5
	public CdmClientCacheException(String message) {
6
		super(message);
7
	}
8

  
9
	public CdmClientCacheException(Exception e) {
10
		super(e);
11
	}
12
}
eu.etaxonomy.taxeditor.cdmlib/src/main/java/eu/etaxonomy/taxeditor/remoting/cache/CdmEntityCacheKey.java
1
package eu.etaxonomy.taxeditor.remoting.cache;
2

  
3
import eu.etaxonomy.cdm.model.common.CdmBase;
4

  
5
public class CdmEntityCacheKey {
6

  
7
	private Class<? extends CdmBase> persistenceClass;
8
	private int persistenceId;
9
	
10
	public CdmEntityCacheKey(CdmBase cdmBase) {
11
		this.persistenceClass = cdmBase.getClass();
12
		this.persistenceId = cdmBase.getId();
13
	}
14
	
15
	public CdmEntityCacheKey(Class<? extends CdmBase> clazz, int id) {
16
		this.persistenceClass = clazz;
17
		this.persistenceId = id;
18
	}
19
	
20

  
21
	
22
	public Class<? extends CdmBase> getPersistenceClass() {
23
		return persistenceClass;
24
	}
25
	
26
	public int getPersistenceId() {
27
		return persistenceId;
28
	}
29
	@Override
30
	public boolean equals(Object obj) {
31
		if(obj == null || !(obj instanceof CdmEntityCacheKey)) {
32
			return false;
33
		}
34
		
35
		if(this == obj) {
36
			return true;
37
		}
38
		CdmEntityCacheKey that = (CdmEntityCacheKey) obj;
39
		if(this.persistenceClass.equals(that.persistenceClass) && this.persistenceId == that.persistenceId) {
40
			return true;
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff