package org.gcube.gcat.persistence.ckan; import java.util.concurrent.TimeUnit; import javax.cache.Cache; import javax.cache.CacheManager; import javax.cache.Caching; import javax.cache.configuration.MutableConfiguration; import javax.cache.expiry.CreatedExpiryPolicy; import javax.cache.expiry.Duration; import javax.cache.spi.CachingProvider; import org.gcube.common.authorization.utils.manager.SecretManager; import org.gcube.common.authorization.utils.manager.SecretManagerProvider; /** * @author Luca Frosini (ISTI - CNR) */ public abstract class CKANUserCache { private static final CacheManager cacheManager; private static final MutableConfiguration userCacheConfiguration; static { CachingProvider provider = Caching.getCachingProvider(); cacheManager = provider.getCacheManager(); userCacheConfiguration = new MutableConfiguration().setTypes(String.class, CKANUser.class) .setStoreByValue(false) .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 15))); } private CKANUserCache() { } public synchronized static CKANUser getCurrrentCKANUser() { SecretManager secretManager = SecretManagerProvider.instance.get(); String context = secretManager.getContext(); Cache userCache = cacheManager.getCache(context); if(userCache == null) { userCache = cacheManager.createCache(context, userCacheConfiguration); } String gcubeUsername = secretManager.getUser().getUsername(); CKANUser ckanUser = userCache.get(gcubeUsername); if(ckanUser == null) { ckanUser = new CKANUser(); ckanUser.retrieve(); userCache.put(gcubeUsername, ckanUser); } return ckanUser; } public synchronized static void removeUserFromCache() { SecretManager secretManager = SecretManagerProvider.instance.get(); String gcubeUsername = secretManager.getUser().getUsername(); removeUserFromCache(gcubeUsername); } public synchronized static void removeUserFromCache(String gcubeUsername) { SecretManager secretManager = SecretManagerProvider.instance.get(); String context = secretManager.getContext(); Cache userCache = cacheManager.getCache(context); if(userCache != null) { userCache.remove(gcubeUsername); } } public synchronized static void emptyUsersCache() { SecretManager secretManager = SecretManagerProvider.instance.get(); String context = secretManager.getContext(); cacheManager.destroyCache(context); } @Override protected void finalize() throws Throwable { super.finalize(); cacheManager.close(); } }