factory class added

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/data-catalogue/ckan-util-library@130932 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Costantino Perciante 2016-08-01 16:02:51 +00:00
parent e257569657
commit 7c662a0c93
2 changed files with 84 additions and 0 deletions

View File

@ -0,0 +1,65 @@
package org.gcube.datacatalogue.ckanutillibrary;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Please invoke this method to retrieve an object of this kind per scope.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class CkanUtilsFactory {
private static final Logger logger = LoggerFactory.getLogger(CkanUtilsFactory.class);
private static final long MAX_LIFETIME = 1000 * 60 * 5; // 5 MINUTES
private static CkanUtilsFactory instance = new CkanUtilsFactory();
private static ConcurrentHashMap<String, CacheBean> cache;
private class CacheBean{
CKanUtilsImpl utils;
long ttl;
public CacheBean(long ttl, CKanUtilsImpl utils){
this.ttl = ttl;
this.utils = utils;
}
}
private CkanUtilsFactory(){
logger.debug("Ckan factory object build");
cache = new ConcurrentHashMap<String, CacheBean>();
}
/**
* Get the factory instance
* @return
*/
public static CkanUtilsFactory getFactory(){
logger.debug("Factory requested");
return instance;
}
public CKanUtilsImpl getUtilsPerScope(String scope) throws Exception{
if(scope == null || scope.isEmpty())
throw new IllegalArgumentException("Invalid scope given!");
if(cache.containsKey(scope) && !expired(cache.get(scope))){
return cache.get(scope).utils;
}
else{
logger.debug("Creating utils for scope " + scope);
CKanUtilsImpl utils = new CKanUtilsImpl(scope);
cache.put(scope, new CacheBean(System.currentTimeMillis(), utils));
return utils;
}
}
private boolean expired(CacheBean cacheBean) {
boolean expired = (cacheBean.ttl + MAX_LIFETIME <= System.currentTimeMillis());
logger.debug("expired is " + expired);
return expired;
}
}

View File

@ -18,6 +18,25 @@ public class TestCKanLib {
CKanUtilsImpl instance;
//@Test
public void factoryTest() throws Exception{
CkanUtilsFactory factory = CkanUtilsFactory.getFactory();
while(true){
factory.getUtilsPerScope("/gcube");
Thread.sleep(60* 1000 * 3);
factory.getUtilsPerScope("/gcube");
break;
}
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
factory.getUtilsPerScope("/gcube");
}
}
//@Test
public void before() throws Exception{