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.gcat.utils.ContextUtility; public abstract class CKANUserCache { private static final CacheManager cacheManager; private static final String USERS_CACHE = "userCache"; 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() { String context = ContextUtility.getCurrentContext(); Cache userCache = userCachePerContext.get(context); if(userCache == null) { userCache = cacheManager.createCache(USERS_CACHE, userCacheConfiguration); userCachePerContext.put(context, userCache); } String gcubeUsername = ContextUtility.getUsername(); CKANUser ckanUser = userCache.get(gcubeUsername); if(ckanUser == null) { ckanUser = new CKANUser(); ckanUser.retrieve(); userCache.put(gcubeUsername, ckanUser); } return ckanUser; } @Override protected void finalize() throws Throwable { super.finalize(); cacheManager.close(); } }