private final Cache cdmlibModelCache;
-
public CacheLoader(ICdmCacher cdmCacher) {
this.cdmCacher = cdmCacher;
this.cdmlibModelCache = CdmRemoteCacheManager.getInstance().getCdmModelGetMethodsCache();
}
-
public CdmModelFieldPropertyFromClass getFromCdmlibModelCache(String className) {
Element e = cdmlibModelCache.get(className);
if (e == null) {
* cache.
* <p>
* <b>WARNING: Recursive updating of the cached entity will not take place
- * in case there is a cached entity which is the same object as
+ * in case there is a cached entity which is the same/identical object as
* <code>cdmEntity</code>.</b>
*
* For in depth details on the mechanism see
* all fields of the cached entity will be overwritten by setting
* them to the value of the cdm entity being loaded
* @return
+ * The cached object which is identical with the input entity in case
+ * the object did not yet exist in the cache
*/
private <T extends CdmBase> T loadRecursive(T cdmEntity, List<Object> alreadyVisitedEntities, boolean update) {
* <code>cdmEntity</code>. In case the cached field value contains a proxy
* object the value will always be overwritten (Q: This might only occur in
* case of uninitialized proxies, since initialized proxies are expected to
- * be replaces by the target entity.)
+ * be replaced by the target entity.)
*
* @param cdmEntity
* the entity to be loaded into the cache
if(cachedCdmEntityInSubGraph != null) {
if(cachedCdmEntityInSubGraph != cdmEntityInSubGraph) {
// exception : is the case where
- // the field has been already initialised, cached and
+ // the field has been already initialized, cached and
// is not the same as the one in the cache, in which case we set the value
// of the field to the one found in the cache
logger.debug("setting cached + real value to '" + fieldName + "' in object of type " + clazz.getName() + " with id " + cdmEntity.getId());
} else {
// since the field value object in cdmEntity
// is the same as the field value object in cachedCdmEntity
- // we are sure that the its subgraph is also correctly loaded,
+ // we are sure that the subgraph is also correctly loaded,
// so we can exit the recursion
return null;
}
// want to continue to recurse on the input cdm entity graph
// and not the one in the cache
return cdmEntityInSubGraph;
- } catch (SecurityException e) {
- throw new CdmClientCacheException(e);
- } catch (IllegalArgumentException e) {
- throw new CdmClientCacheException(e);
- } catch (IllegalAccessException e) {
+ } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new CdmClientCacheException(e);
}
}
+/**
+ * Copyright (C) 2014 EDIT
+ * European Distributed Institute of Taxonomy
+ * http://www.e-taxonomy.eu
+ *
+ * The contents of this file are subject to the Mozilla Public License Version 1.1
+ * See LICENSE.TXT at the top of this package for the full license terms.
+ */
package eu.etaxonomy.cdm.cache;
public class CdmClientCacheException extends RuntimeException {
-
- public CdmClientCacheException(String message) {
+
+ private static final long serialVersionUID = -7933042695466513846L;
+
+ public CdmClientCacheException(String message) {
super(message);
}
+/**
+ * Copyright (C) 2015 EDIT
+ * European Distributed Institute of Taxonomy
+ * http://www.e-taxonomy.eu
+ *
+ * The contents of this file are subject to the Mozilla Public License Version 1.1
+ * See LICENSE.TXT at the top of this package for the full license terms.
+ */
package eu.etaxonomy.cdm.cache;
import eu.etaxonomy.cdm.model.common.CdmBase;
public class CdmEntityCacheKey<T extends CdmBase> {
private Class<T> persistenceClass;
- private int persistenceId;
-
+ private int persistenceId; //see #7709 for why we use id, not uuid
public CdmEntityCacheKey(T cdmBase) {
this.persistenceClass = (Class<T>)cdmBase.getClass();
this.persistenceId = cdmBase.getId();
}
- /**
- * @param clazz
- * @param uuid
- */
public CdmEntityCacheKey(Class<T> clazz, int id) {
this.persistenceClass = clazz;
this.persistenceId = id;
}
-
-
public Class<? extends T> getPersistenceClass() {
return persistenceClass;
}
public int getPersistenceId() {
return persistenceId;
}
+
@Override
public boolean equals(Object obj) {
if(obj == null || !(obj instanceof CdmEntityCacheKey)) {
return false;
}
-
if(this == obj) {
return true;
}
&& this.persistenceId == that.persistenceId) {
return true;
}
-
return false;
}
@Override
public String toString() {
- return this.persistenceClass.getName() + String.valueOf(this.persistenceId);
+ return this.persistenceClass.getName() +":" + String.valueOf(this.persistenceId);
}
}
+/**
+ * Copyright (C) 2015 EDIT
+ * European Distributed Institute of Taxonomy
+ * http://www.e-taxonomy.eu
+ *
+ * The contents of this file are subject to the Mozilla Public License Version 1.1
+ * See LICENSE.TXT at the top of this package for the full license terms.
+ */
package eu.etaxonomy.cdm.cache;
import java.io.File;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
-
/**
* This class is serializing and deserializing the CDM model for performance purposes.
* To serialize see comments on {@link #main(String[])} and on
public static final String CDM_MAP_SER_FOLDER = "/eu/etaxonomy/cdm/mappings/";
public static final String CDM_MAP_SER_FILE_PATH = CDM_MAP_SER_FOLDER + CDM_MAP_SER_FILE;
-
public void cacheGetterFields(Cache cache) throws IOException, ClassNotFoundException, URISyntaxException {
Map<String, CdmModelFieldPropertyFromClass> modelClassMap = loadModelClassMap();
return modelClassMap;
}
-
public Map<String, CdmModelFieldPropertyFromClass> generateModelClassMap() {
// A SessionFactory is set up once for an application!
Map<String, ClassMetadata> classMetaDataMap = sessionFactory.getAllClassMetadata();
// Metadata metadata = new MetadataSources( registry ).getMetadataBuilder().applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE ).build();
-
for(ClassMetadata classMetaData : classMetaDataMap.values()) {
Class<?> mappedClass = classMetaData.getMappedClass();
StandardServiceRegistryBuilder.destroy( registry );
e.printStackTrace();
}
-
-
return modelClassMap;
}
-
public static Configuration buildConfiguration(String hibernateConfigFilePath) {
Configuration configuration = new Configuration().configure(hibernateConfigFilePath);
configuration.buildMappings();
}
}
-
-
public static void main(String argv[]) {
// To re-create the serialised cdm map run,
// See also https://dev.e-taxonomy.eu/redmine/projects/edit/wiki/TaxonomicEditorDevelopersGuide#Model-Change-Actions
//Note AM: does not fully work for me, but running the main from the IDE works.
-
CdmModelCacher cdmModelCacher = new CdmModelCacher();
Map<String, CdmModelFieldPropertyFromClass> modelClassMap = cdmModelCacher.generateModelClassMap();
try{
}catch(Exception ex){
ex.printStackTrace();
}
-
}
}
+/**
+ * Copyright (C) 2015 EDIT
+ * European Distributed Institute of Taxonomy
+ * http://www.e-taxonomy.eu
+ *
+ * The contents of this file are subject to the Mozilla Public License Version 1.1
+ * See LICENSE.TXT at the top of this package for the full license terms.
+ */
package eu.etaxonomy.cdm.cache;
import javax.sql.DataSource;
* When changing this class please also adapt https://dev.e-taxonomy.eu/redmine/projects/edit/wiki/TaxonomicEditorDevelopersGuide#Model-Change-Actions
*
* @author a.mueller
- *
*/
public class CdmModelCacherConnectionProvider extends DatasourceConnectionProviderImpl{
private static final long serialVersionUID = 454393966637126346L;
CdmDataSource dataSource = CdmDataSource.NewH2EmbeddedInstance("cdmTest", username, "", path);
return dataSource;
}
-
-
-
}
+/**
+ * Copyright (C) 2015 EDIT
+ * European Distributed Institute of Taxonomy
+ * http://www.e-taxonomy.eu
+ *
+ * The contents of this file are subject to the Mozilla Public License Version 1.1
+ * See LICENSE.TXT at the top of this package for the full license terms.
+ */
package eu.etaxonomy.cdm.cache;
import java.io.Serializable;
private List<String> fields = new ArrayList<>();
-
public CdmModelFieldPropertyFromClass(String className) {
this.setClassName(className);
}
public String getParentClassName() {
return parentClassName;
}
-
public void setParentClassName(String parentClassName) {
this.parentClassName = parentClassName;
}
public List<String> getFields() {
return fields;
}
-
public void setFields(List<String> fields) {
this.fields = fields;
}
public String getClassName() {
return className;
}
-
public void setClassName(String className) {
this.className = className;
}
+/**
+ * Copyright (C) 2015 EDIT
+ * European Distributed Institute of Taxonomy
+ * http://www.e-taxonomy.eu
+ *
+ * The contents of this file are subject to the Mozilla Public License Version 1.1
+ * See LICENSE.TXT at the top of this package for the full license terms.
+ */
package eu.etaxonomy.cdm.cache;
import java.io.IOException;
import java.net.URISyntaxException;
+import org.apache.log4j.Logger;
+
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.SizeOfPolicyConfiguration;
-import org.apache.log4j.Logger;
-
public class CdmRemoteCacheManager {
+ @SuppressWarnings("unused")
private static final Logger logger = Logger.getLogger(CdmRemoteCacheManager.class);
-
private Cache cdmlibModelCache;
private static CdmRemoteCacheManager cdmRemoteCacheManager = null;
}
public static CdmRemoteCacheManager getInstance(){
-
if(cdmRemoteCacheManager == null) {
cdmRemoteCacheManager = new CdmRemoteCacheManager();
}
}
private CdmRemoteCacheManager() {
-
try {
// NOTE:Programmatically creating the cache manager may solve the problem of
// recreating data written to disk on startup
sizeOfConfig.setMaxDepthExceededBehavior("abort");
CacheConfiguration modelcc = new CacheConfiguration(CDM_MODEL_CACHE_NAME, 0)
- .eternal(true)
- .statistics(true)
- .sizeOfPolicy(sizeOfConfig)
- .overflowToOffHeap(false);
+ .eternal(true)
+ .statistics(true)
+ .sizeOfPolicy(sizeOfConfig)
+ .overflowToOffHeap(false);
cdmlibModelCache = new Cache(modelcc);
CdmModelCacher cmdmc = new CdmModelCacher();
cmdmc.cacheGetterFields(cdmlibModelCache);
- } catch (CacheException e) {
- throw new CdmClientCacheException(e);
- } catch (ClassNotFoundException e) {
- throw new CdmClientCacheException(e);
- } catch (IOException e) {
- throw new CdmClientCacheException(e);
- } catch (URISyntaxException e) {
+ } catch (CacheException | ClassNotFoundException | IOException | URISyntaxException e) {
throw new CdmClientCacheException(e);
}
-
}
-
public Cache getCdmModelGetMethodsCache(){
return cdmlibModelCache;
}
*
* @author a.kohlbecker
* @since Oct 14, 2018
- *
*/
public class CdmTransientEntityAndUuidCacher extends CdmTransientEntityCacher implements ICdmEntityUuidCacher {
private Map<UUID, CdmEntityCacheKey<?>> uuidKeyMap = new HashMap<>();
- /**
- * @param cacheId
- */
public CdmTransientEntityAndUuidCacher(String cacheId) {
super(cacheId);
}
- /**
- * @param sessionOwner
- */
public CdmTransientEntityAndUuidCacher(Object sessionOwner) {
super(sessionOwner);
}
uuidKeyMap.put(cdmEntityToCache.getUuid(), key);
}
-
@Override
public void dispose() {
super.dispose();
uuidKeyMap.clear();
}
-
-
}
*
* @author cmathew
* @since 14 Oct 2014
- *
*/
public class CdmTransientEntityCacher implements ICdmCacher {
cache = new Cache(getEntityCacheConfiguration(cacheId));
- createCacheManager().removeCache(cache.getName());
- createCacheManager().addCache(cache);
+ getCacheManager().removeCache(cache.getName());
+ getCacheManager().addCache(cache);
cacheLoader = new CacheLoader(this);
}
this(generateCacheId(sessionOwner));
}
- public static String generateCacheId(Object sessionOwner) {
+//****************************** STATIC METHODS *********************************/
+
+ /**
+ * Generates an id for this session.
+ * @param sessionOwner
+ * @return
+ */
+ private static String generateCacheId(Object sessionOwner) {
return sessionOwner.getClass().getName() + String.valueOf(sessionOwner.hashCode());
}
+ public static <T extends CdmBase> CdmEntityCacheKey<T> generateKey(Class<T> clazz, int id) {
+ return new CdmEntityCacheKey<T>(clazz, id);
+ }
+
+ public static <T extends CdmBase> CdmEntityCacheKey<T> generateKey(T cdmBase) {
+ Class<T> entityClass = (Class<T>)cdmBase.getClass();
+ return new CdmEntityCacheKey<T>(entityClass, cdmBase.getId());
+ }
+
+ public static void setPermanentCacher(CdmCacher permanentCacher) {
+ permanentCache = permanentCacher;
+ }
+
//****************************** METHODS *********************************/
/**
* Returns the default cache configuration.
- *
- * @return
*/
private CacheConfiguration getEntityCacheConfiguration(String cacheId) {
SizeOfPolicyConfiguration sizeOfConfig = new SizeOfPolicyConfiguration();
.statistics(true)
.sizeOfPolicy(sizeOfConfig)
.overflowToOffHeap(false);
-
- }
-
- public static void setPermanentCacher(CdmCacher permanentCacher) {
- permanentCache = permanentCacher;
}
public LiveCacheStatistics getCacheStatistics() {
return cache.getLiveCacheStatistics();
}
return null;
-
}
/**
* Returns the cache corresponding to the cache id
- *
- * @param cacheId
- * @return
*/
private Cache getCache() {
- return createCacheManager().getCache(cacheId);
+ return getCacheManager().getCache(cacheId);
}
/**
- * @return
+ * @return the singleton cacheManager
*/
- protected CacheManager createCacheManager() {
+ protected CacheManager getCacheManager() {
CacheManager cacheManager = CacheManager.create();
return cacheLoader.load(cdmEntity, true, update);
}
-
- /* ################### to be implemented by subclass in taxeditor ########################
- private CdmBase load(CdmEntityIdentifier cei, boolean update) {
- return CdmApplicationState.getCommonService().findWithUpdate(cei.getCdmClass(), cei.getId());
- }
-
-
- public UpdateResult load(UpdateResult result, boolean update) {
- // probably a good time to broadcast to other sessions
-
- Set<CdmBase> updatedObjects = result.getUpdatedObjects();
- Set<CdmBase> reloadedObjects = new HashSet<CdmBase>();
- Set<CdmEntityIdentifier> updatedCdmIds = result.getUpdatedCdmIds();
- boolean updatedCdmIdsIsEmpty = updatedCdmIds.isEmpty();
-
- // if the cdm identifier set contains identifiers of objects already
- // present in the updated objects set reomve them
- for(CdmBase updatedObject : updatedObjects) {
- if(updatedObject != null && exists(new CdmEntityCacheKey(updatedObject.getClass(), updatedObject.getId()))) {
- CdmEntityIdentifier cdmEntityIdentifier = new CdmEntityIdentifier(updatedObject.getId(), updatedObject.getClass());
- if(!updatedCdmIdsIsEmpty && updatedCdmIds.contains(cdmEntityIdentifier)) {
- updatedCdmIds.remove(cdmEntityIdentifier);
- }
- reloadedObjects.add(cacheLoader.load(updatedObject, true, update));
- }
- }
-
- // remote load cdm identifiers of objects which already exist
- // in the cache
-
- for(CdmEntityIdentifier cei : updatedCdmIds) {
- if(exists(new CdmEntityCacheKey(cei.getCdmClass(), cei.getId()))) {
- reloadedObjects.add(load(cei, update));
- }
-
- }
- updatedObjects.clear();
- result.addUpdatedObjects(reloadedObjects);
- return result;
- }
- */
-
public MergeResult<CdmBase> load(MergeResult<CdmBase> mergeResult, boolean update) {
return cacheLoader.load(mergeResult, true, update);
}
return cacheLoader.getFromCdmlibModelCache(className);
}
-
public void addNewEntity(CdmBase newEntity) {
if(newEntity != null && newEntity.getId() == 0 && newEntity.getUuid() != null) {
newEntitiesMap.put(newEntity.getUuid(), newEntity);
}
/**
- * Puts the passed <code>cdmEntity</code> into the cache as long it does
- * not yet exist in the caches.
+ * Puts the passed <code>cdmEntity</code> into the according caches
+ * (cache, newEntitiesMap, permanentCache) as long it does not yet exist there.
* <p>
* The adjacent <b>ENTITY GRAPH WILL NOT BE LOADED RECURSIVELY</b>
*/
cachedCdmEntity = getFromCache(key);
if(cachedCdmEntity == null) {
CdmBase cdmEntityToCache = cdmEntity;
- CdmBase newEntity = newEntitiesMap.get(cdmEntity.getUuid());
- if(newEntity != null) {
- newEntity.setId(cdmEntity.getId());
- cdmEntityToCache = newEntity;
+ CdmBase newInMapEntity = newEntitiesMap.get(cdmEntity.getUuid());
+ if(newInMapEntity != null) {
+ newInMapEntity.setId(cdmEntity.getId());
+ cdmEntityToCache = newInMapEntity;
}
putToCache(key, cdmEntityToCache);
cdmEntityToCache.initListener();
newEntitiesMap.remove(cdmEntity.getUuid());
if (logger.isDebugEnabled()){logger.debug(" - object of type " + cdmEntityToCache.getClass().getName() + " with id " + cdmEntityToCache.getId() + " put in cache");}
return;
+ }else{
+ logger.debug(" - object of type " + cdmEntity.getClass().getName() + " with id " + cdmEntity.getId() + " already exists");
}
- logger.debug(" - object of type " + cdmEntity.getClass().getName() + " with id " + cdmEntity.getId() + " already exists");
}
- /**
- * @param key
- * @param cdmEntityToCache
- */
protected void putToCache(CdmEntityCacheKey<?> key, CdmBase cdmEntityToCache) {
getCache().put(new Element(key, cdmEntityToCache));
}
-
private Element getCacheElement(CdmEntityCacheKey<?> key) {
return getCache().get(key);
}
-
public <T extends CdmBase> T getFromCache(CdmEntityCacheKey<T> id) {
Element e = getCacheElement(id);
return cachedCdmEntity;
}
- public CdmBase getFromCache(CdmBase cdmBase, Class<? extends CdmBase> clazz) {
-
- cdmBase = CdmBase.deproxy(cdmBase, clazz);
- return getFromCache(cdmBase);
- }
-
public List<CdmBase> getAllEntities() {
List<CdmBase> entities = new ArrayList<>();
Map<String, CdmBase> elementsMap = getCache().getAllWithLoader(getCache().getKeys(), null);
@Override
public void dispose() {
- createCacheManager().removeCache(cache.getName());
+ getCacheManager().removeCache(cache.getName());
cache.dispose();
newEntitiesMap.clear();
}
-
- public static <T extends CdmBase> CdmEntityCacheKey<T> generateKey(Class<T> clazz, int id) {
- return new CdmEntityCacheKey<T>(clazz, id);
- }
-
-
- public static <T extends CdmBase> CdmEntityCacheKey<T> generateKey(T cdmBase) {
- Class<T> entityClass = (Class<T>)cdmBase.getClass();
- return new CdmEntityCacheKey<T>(entityClass, cdmBase.getId());
- }
-
@Override
public <T extends CdmBase> T load(T cdmEntity) {
return load(cdmEntity, true);
/**
* @author cmathew
* @since 9 Feb 2015
- *
*/
public class EntityCacherDebugResult {
public EntityCacherDebugResult() {
}
-
public <T extends CdmBase> EntityCacherDebugResult(CdmTransientEntityCacher cacher, Collection<T> rootEntities) {
this.cacher = cacher;
init();
debugOutput.append(out);
clear();
}
-
}
}
System.out.println(toString(duplicateCdmEntityMap, notInCacheList, rootEntity));
}
-
@Override
public String toString() {
return debugOutput.toString();
List<CdmEntityInfo> notInCacheList,
CdmBase rootEntity) {
-
StringBuilder sb = new StringBuilder();
sb.append(System.getProperty("line.separator"));
sb.append("<<< Root Entity " + rootEntity.getUserFriendlyTypeName() + " with id " + rootEntity.getId() + " >>>");
return caches;
}
-
private void debug(CdmBase cdmEntity, boolean recursive) {
if(cdmEntity == null) {
return;
} else if (obj instanceof Collection) {
debug((Collection<T>)obj, alreadyVisitedEntities, cei);
}
-
logger.info("No caching yet for type " + obj.getClass().getName());
-
-
}
private <T extends Object> void debug(Map<T,T> map,
cei.addChild(childCei);
debugRecursive(obj, alreadyVisitedEntities, childCei);
}
-
}
-
}
private void debugRecursive(CdmBase cdmEntity,
List<CdmEntityInfo> alreadyVisitedEntities,
CdmEntityInfo cei) {
- CdmBase cachedCdmEntityInSubGraph = null;
-
if(cei.getObject() instanceof CdmBase) {
CdmBase cb = (CdmBase)cei.getObject();
cb = (CdmBase) ProxyUtils.deproxy(cb);
- cachedCdmEntityInSubGraph = cacher.getFromCache(cb);
+ CdmBase cachedCdmEntityInSubGraph = cacher.getFromCache(cb);
if(cachedCdmEntityInSubGraph != cb) {
cei.setNotInCacheDetail(cachedCdmEntityInSubGraph == null ? NotInCacheDetail.NOT_FOUND : NotInCacheDetail.COPY_ENTITY);
// found a cdm entity which is not in cache - need to record this
}
}
-
// we want to recursive through the cdmEntity (and not the cachedCdmEntity)
// since there could be new or deleted objects in the cdmEntity sub-graph
// we return the original cdm entity in the sub graph because we
// want to continue to recurse on the input cdm entity graph
// and not the one in the cache
-
return childCei;
- } catch (SecurityException e) {
- throw new CdmClientCacheException(e);
- } catch (IllegalArgumentException e) {
- throw new CdmClientCacheException(e);
- } catch (IllegalAccessException e) {
+ } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new CdmClientCacheException(e);
}
}
-
private CdmEntityInfo getDuplicate(List<CdmEntityInfo> alreadyVisitedEntities, Object objectToCompare) {
if(objectToCompare != null ) {
for(CdmEntityInfo cei: alreadyVisitedEntities) {
public CdmEntityInfo getParent() {
return parent;
}
-
public void setParent(CdmEntityInfo parent) {
this.parent = parent;
}
public List<CdmEntityInfo> getChildren() {
return children;
}
-
public void setChildren(List<CdmEntityInfo> children) {
this.children = children;
}
public Field getField() {
return field;
}
-
public void setField(Field field) {
this.field = field;
}
-
public String getLabel() {
String label;
String fieldName = "";
this.isProxy = isProxy;
}
- /**
- * @return the notInCacheDetail
- */
public NotInCacheDetail getNotInCacheDetail() {
return notInCacheDetail;
}
-
- /**
- * @param notInCacheDetail the notInCacheDetail to set
- */
public void setNotInCacheDetail(NotInCacheDetail notInCacheDetail) {
this.notInCacheDetail = notInCacheDetail;
}
-
}
enum NotInCacheDetail {
this.label = label;
}
- /**
- * @return
- */
public Object getLabel() {
return label;
}
/**
* @author cmathew
* @since 17 Feb 2015
- *
*/
public class ProxyUtils {
-
-
public static enum CollectionType {
SET,
LIST,
LazyInitializer hli = ((HibernateProxy)o).getHibernateLazyInitializer();
if(!hli.isUninitialized()) {
return hli.getImplementation();
-
}
}
PersistentCollection pc = ((PersistentCollection)o);
if(pc.wasInitialized()) {
return ProxyUtils.getObject(pc);
-
}
}
return o;
}
########################################### ########################################### */
-
-
-
public static void setRoleValueInOwner(Object owner, String role, Object value) {
if(role == null || role.isEmpty()) {
throw new ProxyUtilsException("Role cannot be null or an empty string");
import eu.etaxonomy.cdm.model.ICdmEntityUuidCacher;
import eu.etaxonomy.cdm.model.common.CdmBase;
import eu.etaxonomy.cdm.model.permission.CRUD;
-import eu.etaxonomy.cdm.model.permission.PermissionClass;
import eu.etaxonomy.cdm.model.permission.GrantedAuthorityImpl;
+import eu.etaxonomy.cdm.model.permission.PermissionClass;
import eu.etaxonomy.cdm.model.permission.User;
import eu.etaxonomy.cdm.persistence.permission.CdmAuthority;
import eu.etaxonomy.cdm.persistence.permission.CdmAuthorityParsingException;
/**
* @author a.kohlbecker
* @since May 19, 2017
- *
*/
public class CdmUserHelper implements UserHelper, Serializable {
@Qualifier("cdmRepository")
protected CdmRepository repo;
- AuthenticationProvider runAsAuthenticationProvider;
+ private AuthenticationProvider runAsAuthenticationProvider;
@Autowired(required=false)
@Qualifier("runAsAuthenticationProvider")
super();
}
- /**
- * @return
- */
protected ICdmPermissionEvaluator permissionEvaluator() {
return permissionEvaluator;
}
- /**
- * @return
- */
protected CdmRepository repo() {
return repo;
}
return false;
}
-
@Override
public boolean userIsAnnonymous() {
Authentication authentication = getAuthentication();
return false;
}
- /**
- * {@inheritDoc}
- */
@Override
public boolean userIs(RoleProbe roleProbe) {
return roleProbe.checkForRole(getAuthentication());
return false;
}
- /**
- * @param cdmType
- * @param entitiyUuid
- * @return
- */
protected CdmBase entity(Class<? extends CdmBase> cdmType, UUID entitiyUuid) {
CdmBase entity = entityFromCache(cdmType, entitiyUuid);
if(entity == null){
SecurityContextHolder.clearContext();
}
-
private EnumSet<CRUD> crudSetFromArgs(Object[] args) {
EnumSet<CRUD> crudSet = EnumSet.noneOf(CRUD.class);
for(int i = 0; i < args.length; i++){
return crudSet;
}
-
private SecurityContext currentSecurityContext() {
if(securityContextAccess != null){
return securityContextAccess.currentSecurityContext();
return SecurityContextHolder.getContext();
}
- /**
- * @return
- */
@Override
public Authentication getAuthentication() {
return currentSecurityContext().getAuthentication();
}
- /**
- * {@inheritDoc}
- *
- */
@Override
public CdmAuthority createAuthorityFor(String username, CdmBase cdmEntity, EnumSet<CRUD> crud, String property) {
return createAuthorityFor(username, cdmEntity, crud, property);
}
- /**
- * @param username
- * @param cdmType
- * @param entitiyUuid
- * @param crud
- * @return
- */
@Override
public CdmAuthority createAuthorityFor(String username, Class<? extends CdmBase> cdmType, UUID entitiyUuid, EnumSet<CRUD> crud, String property) {
return createAuthorityFor(username, cdmEntity, crud, property);
}
- /**
- * {@inheritDoc}
- */
@Override
public CdmAuthority createAuthorityForCurrentUser(CdmBase cdmEntity, EnumSet<CRUD> crud, String property) {
return createAuthorityFor(userName(), cdmEntity, crud, property);
}
- /**
- * @param cdmType
- * @param entitiyId
- * @param crud
- * @return
- */
@Override
public CdmAuthority createAuthorityForCurrentUser(Class<? extends CdmBase> cdmType, Integer entitiyId, EnumSet<CRUD> crud, String property) {
return createAuthorityFor(userName(), cdmType, entitiyId, crud, property);
}
- /**
- * @param cdmType
- * @param entitiyUuid
- * @param crud
- * @return
- */
@Override
public CdmAuthority createAuthorityForCurrentUser(Class<? extends CdmBase> cdmType, UUID entitiyUuid, EnumSet<CRUD> crud, String property) {
return createAuthorityFor(userName(), cdmType, entitiyUuid, crud, property);
}
- /**
- * {@inheritDoc}
- */
@Override
public void removeAuthorityForCurrentUser(CdmAuthority cdmAuthority) {
removeAuthorityForCurrentUser(userName(), cdmAuthority);
}
- /**
- * {@inheritDoc}
- */
@Override
public void removeAuthorityForCurrentUser(String username, CdmAuthority cdmAuthority) {
repo().commitTransaction(txStatus);
}
- /**
- * {@inheritDoc}
- */
@Override
public Collection<CdmAuthority> findUserPermissions(CdmBase cdmEntity, EnumSet<CRUD> crud) {
Set<CdmAuthority> matches = new HashSet<>();
return matches;
}
- // @Override
@Override
public <T extends CdmBase> Collection<CdmAuthority> findUserPermissions(Class<T> cdmType, EnumSet<CRUD> crud) {
Set<CdmAuthority> matches = new HashSet<>();
return matches;
}
- /**
- * @param securityContextAccess the securityContextAccess to set
- */
@Override
public void setSecurityContextAccess(SecurityContextAccess securityContextAccess) {
this.securityContextAccess = securityContextAccess;
}
- /**
- * @return the runAsAutheticator
- */
public RunAsAuthenticator getRunAsAutheticator() {
if(runAsAutheticator == null){
throw new RuntimeException("RunAsAuthenticator is missing! The application needs to be configured with security context.");
return runAsAutheticator;
}
- /**
- * @return the cache
- */
public ICdmEntityUuidCacher getCache() {
return null;
}
- /**
- * @param cdmType
- * @param entitiyUuid
- * @return
- */
private CdmBase entityFromCache(Class<? extends CdmBase> cdmType, UUID entitiyUuid) {
CdmBase entity = null;
if(getCache() != null){
@Override
public CdmUserHelper withCache(ICdmEntityUuidCacher cache){
-
return new CachingCdmUserHelper(cache);
}
class CachingCdmUserHelper extends CdmUserHelper{
-
private static final long serialVersionUID = -5010082174809972831L;
private ICdmEntityUuidCacher cache;
this.cache = cache;
}
- /**
- * @return the cache
- */
@Override
public ICdmEntityUuidCacher getCache() {
return cache;
protected ICdmPermissionEvaluator permissionEvaluator() {
return CdmUserHelper.this.permissionEvaluator;
}
-
}
}