package org.gcube.gcat.persistence.ckan; import java.util.HashMap; import java.util.Map; 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; private static final Map> userCachePerContext; 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))); userCachePerContext = new HashMap>(); } private CKANUserCache() { } public static CKANUser getCurrrentCKANUser() { SecretManager secretManager = SecretManagerProvider.instance.get(); String context = secretManager.getContext(); Cache userCache = userCachePerContext.get(context); if(userCache == null) { userCache = cacheManager.createCache(context, userCacheConfiguration); userCachePerContext.put(context, userCache); } 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 static void removeUserFromCache() { SecretManager secretManager = SecretManagerProvider.instance.get(); String context = secretManager.getContext(); Cache userCache = userCachePerContext.get(context); if(userCache != null) { String gcubeUsername = secretManager.getUser().getUsername(); userCache.remove(gcubeUsername); } } @Override protected void finalize() throws Throwable { super.finalize(); cacheManager.close(); } }