I am upgrading ehcache version from 2.x to 3.x, I went through the ehcache doc at
but it was not much helpful. Can some one help me to re-write the entire logic in 3.x. Below is the code with 2.x.
/**
* A wrapper around net.sf.ehcache.CacheManager. Configured via cacheManager.xml. This class is independent of
* the second-level cache within Hibernate.
*/
public class CacheManager implements ICacheManager {
private static INcrLogger logger = NcrLoggerFactory.getLogger(CacheManager.class);
private static final String PATTERN = ".*";
public static final String ALL = "ALL";
private org.ehcache.CacheManager ehCacheManager;
private String configFileName;
private Configuration configuration;
/**
* {@inheritDoc}
*/
@SuppressWarnings("rawtypes")
public void changeTimeToLive(String cacheName, int newTimeToLive) {
CacheConfiguration config = (CacheConfiguration) getConfiguration().getCacheConfigurations()
.get(cacheName);
if (config == null) {
throw new NcrRuntimeException(
StringServices.getString(LoggerKeys.DEFAULT_BUNDLE_NAME, LoggerKeys.LOG_1_ARGS,
new String[] {"cannot change timeToLive on defaultCache: " + cacheName}));
}
config.setTimeToLiveSeconds(newTimeToLive);
getCacheManager().removeCache(cacheName);
getCacheManager().addCache(
new Cache(cacheName, config.getMaxElementsInMemory(), config.getMemoryStoreEvictionPolicy(),
config.isOverflowToDisk(), getConfiguration().getDiskStoreConfiguration().getPath(),
config.isEternal(), config.getTimeToLiveSeconds(), config.getTimeToIdleSeconds(),
config.isDiskPersistent(), config.getDiskExpiryThreadIntervalSeconds(), null));
}
/**
* {@inheritDoc}
*/
public void addCache(String cacheName) {
CacheConfiguration config = (CacheConfiguration) getConfiguration().getCacheConfigurations()
.get("defaultCache");
if (config == null) {
throw new NcrRuntimeException(StringServices.getString(LoggerKeys.DEFAULT_BUNDLE_NAME,
LoggerKeys.LOG_1_ARGS, new String[] {"cannot create cache: " + cacheName}));
}
getCacheManager().addCache(new Cache(cacheName, (int) config.getMaxEntriesLocalHeap(),
config.getMemoryStoreEvictionPolicy(), config.isOverflowToDisk(),
getConfiguration().getDiskStoreConfiguration().getPath(), config.isEternal(),
config.getTimeToLiveSeconds(), config.getTimeToIdleSeconds(), config.isDiskPersistent(),
config.getDiskExpiryThreadIntervalSeconds(), null));
}
/**
* Fetches a Cache for a given cacheName.
* @param cacheName name of cache
* @return Cache An instance of the Cache
*/
@SuppressWarnings("unchecked")
protected <K, V> Cache<K, V> getCache(String cacheName) {
Cache<K, V> cache = getCacheManager().getCache(cacheName);
if (cache == null) {
/*String errorMsg = StringServices.getString(LoggerKeys.DEFAULT_BUNDLE_NAME,
LoggerKeys.NOT_CONFIGURED, new String[] {getCacheManager().getName(), cacheName});*/
String errorMsg = logger.error(LoggerKeys.NOT_CONFIGURED,new String[] {getCacheManager().getName(), cacheName});
throw new NcrRuntimeException(errorMsg);
}
logger.debug(
"CACHE: found cache: " + cacheName + " using cache manager: " + getCacheManager().getName());
return cache;
}
/**
* {@inheritDoc}
*/
public boolean cacheExists(String cacheName) {
return getCacheManager().cacheExists(cacheName);
}
/**
* {@inheritDoc}
*/
public Object getElement(String cacheName, Object elementKey) {
Cache aCache = getCache(cacheName);
Object value = null;
Element element = aCache.get(elementKey);
if (element != null) {
value = element.getObjectValue();
} else {
}
return value;
}
/**
* {@inheritDoc}
*/
public synchronized void putElement(String cacheName, Object elementKey, Object anObject) {
Cache aCache = getCache(cacheName);
Element element = new Element(elementKey, anObject);
aCache.put(element);
}
/**
* {@inheritDoc}
*/
public synchronized void removeElement(String cacheName, Object elementKey) {
Cache aCache = getCache(cacheName);
aCache.remove(elementKey);
}
/**
* Returns the CacheManager instance.
* @return CacheManager instance of the CacheManager
*/
protected org.ehcache.CacheManager getCacheManager() {
if (ehCacheManager == null) {
createCacheManager();
}
return ehCacheManager;
}
/**
* Creates new the CacheManager instance if not exist.
*/
protected synchronized void createCacheManager() {
try {
if (ehCacheManager == null) {
InputStream ehcacheStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(getConfigFileName());
Configuration configuration = ConfigurationBuilder.parseConfiguration(ehcacheStream);
try {
ApplicationContext context = SpringUtil.getApplicationContext();
String cacheName = configuration.getName();
if (context.containsBean("earName")) {
cacheName = context.getBean("earName") + "_" + cacheName;
if (logger.isInfoEnabled()) {
logger.info("Giving new cache name [" + cacheName + "]");
}
}
configuration.setName(cacheName);
} catch (Exception e) {
logger.warn(LoggerKeys.LOG_1_ARGS, new String[] {
"Unable to construct a cache name based on earName. Cause: " + e.getMessage()});
}
setEhCacheManager(org.ehcache.CacheManager.newInstance(configuration));
setConfiguration(configuration);
}
} catch (CacheException e) {
String errorMsg = StringServices.getString(LoggerKeys.DEFAULT_BUNDLE_NAME,
LoggerKeys.CREATION_ERROR, new String[] {"CacheManager"});
throw new NcrRuntimeException(errorMsg, e);
}
}
/**
* {@inheritDoc}
*/
public synchronized void remove() {
try {
if (ehCacheManager != null) {
ehCacheManager.shutdown();
setEhCacheManager(null);
}
} catch (CacheException e) {
String errorMsg = StringServices.getString(LoggerKeys.DEFAULT_BUNDLE_NAME,
LoggerKeys.CLEARING_ERROR, new String[] {"CacheManager"});
throw new NcrRuntimeException(errorMsg, e);
}
}
/**
* Clear the Operational data Cache for the input object name.
* @param cacheName name of the Cache Object that need to be removed from the cache
*/
public void clearCache(String cacheName) {
int i = cacheName.indexOf(PATTERN);
if (i != -1) {
String cacheNamePattern = cacheName.substring(0, i);
String[] names = getCacheManager().getCacheNames();
for (int j = 0; j < names.length; j++) {
if (names[j].startsWith(cacheNamePattern)) {
clearACache(names[j]);
}
}
} else {
clearACache(cacheName);
}
}
/**
* Clear the specified cache and all the related statistics.
* @param cacheName name of the cache to clear
*/
private void clearACache(String cacheName) {
Cache cache = getCache(cacheName);
// cache.clearStatistics();
cache.flush();
cache.removeAll();
}
/**
* Log the Cache Statistics.
* @param cacheName name of the Cache Object for Statistics Report
*/
public void logCacheStatistics(String cacheName) {
try {
Timestamp currTime = new Timestamp(System.currentTimeMillis());
org.ehcache.CacheManager cacheManager = getCacheManager();
if (cacheManager != null) {
StringBuilder cacheStatisticsSB = new StringBuilder(
"!!!!!!!!Cache Statistics Report at: " + currTime + " !!!!!!!!");
if (cacheName.equals(ALL)) {
String[] cachename = cacheManager.getCacheNames();
int length = cachename.length;
if (length == 0) {
cacheStatisticsSB.append("\nNo Cache found for Statistics");
}
for (int i = 0; i < length; i++) {
Cache cache = cacheManager.getCache(cachename[i]);
logStatistics(cache, cacheStatisticsSB);
}
} else {
logStatistics(cacheManager.getCache(cacheName), cacheStatisticsSB);
}
cacheStatisticsSB.append("\nEnd Cache Statistics Report");
if (logger.isInfoEnabled()) {
}
}
} catch (CacheException e) {
String errorMsg = StringServices.getString(LoggerKeys.DEFAULT_BUNDLE_NAME,
LoggerKeys.LOGGING_ERROR, new String[] {"statistics"});
throw new NcrRuntimeException(errorMsg, e);
}
}
/**
* Log the Cache Statistics for Operational data for the send Cache instance.
* @param cache Instance of the Cache
*/
@SuppressWarnings("deprecation")
protected void logStatistics(Cache cache, StringBuilder cacheStatisticsSB) {
cacheStatisticsSB.append("\nStart of Cache Statistics Report for " + cache.getName());
cacheStatisticsSB.append("\nHits : " + cache.getStatistics().cacheHitCount());
// cacheStatisticsSB.append("\nMemory Store Hits : " +
// cache.getStatistics().getInMemoryHits());
cacheStatisticsSB
.append("\nDisk Store Hits : " + cache.getStatistics().localDiskHitCount());
cacheStatisticsSB.append("\nMissed Retrievals : " + cache.getStatistics().cacheMissCount());
cacheStatisticsSB.append("\nCurrent Size : " + cache.getMemoryStoreSize());
// cacheStatisticsSB.append("\nMaximum Size : " + cache.getMaxElementsInMemory());
cacheStatisticsSB.append("\nEnd of Cache Statistics Report for " + cache.getName());
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public Map<Object, Object> getAll(String cacheName) {
Cache cache = getCache(cacheName);
List<Object> keys = cache.getKeys();
Map<Object, Object> map = new Hashtable<Object, Object>();
Iterator<Object> it = keys.iterator();
while (it.hasNext()) {
Object key = it.next();
map.put(key, cache.get(key).getObjectValue());
}
return map;
}
/**
* sets the cache manager attribute.
* @param ehcacheManager
*/
protected void setEhCacheManager(org.ehcache.CacheManager ehcacheManager) {
this.ehCacheManager = ehcacheManager;
}
/**
* Getter for the configFileName.
* @return Returns the configFileName
*/
protected String getConfigFileName() {
return configFileName;
}
/**
* Setter for the configFileName value.
* @param configFileName the configFileName to set
*/
public void setConfigFileName(String configFileName) {
this.configFileName = configFileName;
}
protected Configuration getConfiguration() {
return configuration;
}
protected void setConfiguration(Configuration configuration) {
this.configuration = configuration;
}
/**
* {@inheritDoc}
*/
public void clear() {
clearCache(".*");
}
}