com.alachisoft.ncache.jsr107.NCacheManager Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ncache-professional-client Show documentation
Show all versions of ncache-professional-client Show documentation
NCache Professional client for java.
package com.alachisoft.ncache.jsr107;
import com.alachisoft.ncache.client.CacheManager;
import com.alachisoft.ncache.jsr107.spi.NCacheCachingProvider;
import com.alachisoft.ncache.runtime.exceptions.ConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.configuration.CompleteConfiguration;
import javax.cache.configuration.Configuration;
import javax.cache.spi.CachingProvider;
import javax.management.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.net.URI;
import java.util.Collections;
import java.util.HashSet;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NCacheManager implements javax.cache.CacheManager {
protected static final int DEFAULT_SIZE = 1000;
protected static MBeanServer mBeanServer = MBeanServerFactory.createMBeanServer();
protected final NCacheCachingProvider jCacheCachingProvider;
protected final URI uri;
protected final Properties props;
protected final ConcurrentHashMap allCaches = new ConcurrentHashMap();
protected final ClassLoader classloader;
protected final ExecutorService executorService = Executors.newSingleThreadExecutor();
protected final ConcurrentMap cfgMXBeans = new ConcurrentHashMap();
protected final ConcurrentMap statMXBeans = new ConcurrentHashMap();
protected volatile boolean closed = false;
public NCacheManager() {
this.jCacheCachingProvider = new NCacheCachingProvider();
this.props = new Properties();
//ConfigurationManager.getInstance();
uri = null;
classloader = null;
//throw new NullPointerException();
}
public NCacheManager(final NCacheCachingProvider jCacheCachingProvider, final ClassLoader classloader, final URI uri, final Properties props) {
this.jCacheCachingProvider = jCacheCachingProvider;
this.uri = uri;
this.props = props;
this.classloader = classloader;
}
public static HashSet GetCacheNames(String path) throws ConfigurationException {
File file = null;
HashSet cacheNames = new HashSet();
try {
//String path = DirectoryUtil.getConfigPath(fileName);
file = new File(path);
if (!file.exists()) {
return cacheNames;
}
Document configuration = null;
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
}
configuration = builder.parse(file);
NodeList cacheList = configuration.getElementsByTagName("cache");
for (int i = 0; i < cacheList.getLength(); i++) {
Node cache = cacheList.item(i);
if (cache.hasAttributes()) {
String cacheName = cache.getAttributes().getNamedItem("id").getNodeValue();
if (cacheName != null || !cacheName.equals(""))
cacheNames.add(cacheName.toLowerCase());
}
}
} catch (Exception e) {
throw new ConfigurationException("An error occured while reading config file. " + e.getMessage());
} finally {
}
return cacheNames;
}
/**
* Get the CachingProvider that created and is responsible for the CacheManager.
*
* @return
*/
@Override
public CachingProvider getCachingProvider() {
return jCacheCachingProvider;
}
/**
* Get the URI of the CacheManager.
*
* @return
*/
@Override
public URI getURI() {
return uri;
}
/**
* Get the ClassLoader used by the CacheManager.
*
* @return
*/
@Override
public ClassLoader getClassLoader() {
return classloader;
}
/**
* Get the Properties that were used to create this CacheManager.
*
* @return
*/
@Override
public Properties getProperties() {
return props;
}
/**
* @param cacheName - the name of the Cache
* @param configuration - a Configuration for the Cache
* @return
* @throws IllegalArgumentException
*/
@Override
public > Cache createCache(String cacheName, C configuration) throws IllegalArgumentException {
checkManagerStatus();
if (configuration == null) {
throw new NullPointerException();
}
NCacheCache jCache = allCaches.get(cacheName);
if (jCache != null) {
throw new CacheException("Cache with same name already exist");
}
try {
com.alachisoft.ncache.client.Cache tayzGrid = CacheManager.getCache(cacheName);
//CompleteConfiguration config=(MutableConfiguration)configuration;
final NCacheConfiguration cfg = new NCacheConfiguration(configuration);
jCache = new NCacheCache(this, cfg, tayzGrid);
NCacheCache previous = allCaches.putIfAbsent(cacheName, jCache);
if (previous != null) {
previous.setClose();
}
if (cfg.isStatisticsEnabled()) {
enableStatistics(cacheName, true);
}
if (cfg.isManagementEnabled()) {
enableManagement(cacheName, true);
}
return jCache;
} catch (Exception ex) {
throw new CacheException(ex);
}
}
/**
* Looks up a managed Cache given its name.
*
* @param cacheName - the name of the managed Cache to acquire
* @param type - the expected Class of the key
* @param valueType - the expected Class of the value
* @return
* @throws IllegalStateException, IllegalArgumentException, SecurityException
*/
@Override
public Cache getCache(String cacheName, Class type, Class valueType) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
NCacheCache jCache = allCaches.get(cacheName);
if (jCache != null) {
return jCache;
} else {
try {
com.alachisoft.ncache.client.Cache tayzGrid = CacheManager.getCache(cacheName);
jCache = new NCacheCache(this, new NCacheConfiguration(cacheName, null, type, valueType), tayzGrid);
} catch (Exception ex) {
}
}
final NCacheCache previous = allCaches.putIfAbsent(cacheName, jCache);
return jCache;
}
/**
* Looks up a managed Cache given its name.
*
* @param cacheName - the name of the cache to look for
* @return
*/
@Override
public Cache getCache(String cacheName) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
Cache jCache = allCaches.get(cacheName);
if (jCache == null) {
com.alachisoft.ncache.client.Cache tayzGrid;
try {
tayzGrid = CacheManager.getCache(cacheName);
jCache = new NCacheCache(this, new NCacheConfiguration(cacheName, null, String.class, Object.class), tayzGrid);
} catch (Exception ex) {
}
return allCaches.get(cacheName);
}
if (jCache.getConfiguration(CompleteConfiguration.class).getKeyType() != Object.class ||
jCache.getConfiguration(CompleteConfiguration.class).getValueType() != Object.class) {
throw new IllegalArgumentException();
}
return jCache;
}
/**
* Obtains an Iterable over the names of Caches managed by the CacheManager.
*
* @return
*/
@Override
public Iterable getCacheNames() {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
// List cacheName = new ArrayList();
//
// for(com.alachisoft.tayzgrid.web.caching.Cache cache : TayzGrid.getCaches())
// {
// cacheName.add(cache.toString());
// }
//
// return cacheName;
return Collections.unmodifiableSet(new HashSet(allCaches.keySet()));
}
/**
* Destroys a specifically named and managed Cache. Once destroyed a new Cache of the same name but with a different Configuration may be configured.
*
* @param cacheName
*/
@Override
public void destroyCache(String cacheName) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
checkManagerStatus();
final Cache jCache = allCaches.get(cacheName);
allCaches.remove(cacheName);
if (jCache != null) {
jCache.close();
}
}
/**
* Controls whether management is enabled. If enabled the CacheMXBean for each cache is registered in the platform MBean server. The platform MBeanServer is obtained using ManagementFactory.getPlatformMBeanServer().
*
* @param cacheName - the name of the cache to register
* @param enabled - true to enable management, false to disable.
*/
@Override
public void enableManagement(final String cacheName, final boolean enabled) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
checkManagerStatus();
if (cacheName == null) throw new NullPointerException();
final NCacheCache jCache = allCaches.get(cacheName);
if (jCache == null) {
throw new NullPointerException();
}
enableManagement(enabled, jCache);
}
private void enableManagement(final boolean enabled, final NCacheCache jCache) {
try {
if (enabled) {
registerObject(getOrCreateCfgObject(jCache));
} else {
unregisterObject(cfgMXBeans.remove(jCache));
}
((NCacheConfiguration) jCache.getConfiguration(NCacheConfiguration.class)).setManagementEnabled(enabled);
} catch (NotCompliantMBeanException e) {
throw new CacheException(e);
} catch (InstanceAlreadyExistsException e) {
// throw new CacheException(e);
} catch (MBeanRegistrationException e) {
throw new CacheException(e);
} catch (InstanceNotFoundException e) {
// throw new CacheException(e);
} catch (MalformedObjectNameException e) {
throw new CacheException(e);
}
}
/**
* Enables or disables statistics gathering for a managed Cache at runtime.
*
* @param cacheName - the name of the cache to register
* @param enabled - true to enable statistics, false to disable.
*/
@Override
public void enableStatistics(final String cacheName, final boolean enabled) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
checkManagerStatus();
if (cacheName == null) throw new NullPointerException();
final NCacheCache jCache = allCaches.get(cacheName);
if (jCache == null) {
throw new NullPointerException();
}
enableStatistics(enabled, jCache);
}
private void enableStatistics(final boolean enabled, final NCacheCache jCache) {
try {
if (enabled) {
registerObject(getOrCreateStatObject(jCache));
} else {
unregisterObject(statMXBeans.remove(jCache));
}
((NCacheConfiguration) jCache.getConfiguration(NCacheConfiguration.class)).setStatisticsEnabled(enabled);
} catch (NotCompliantMBeanException e) {
throw new CacheException(e);
} catch (InstanceAlreadyExistsException e) {
// throw new CacheException(e);
} catch (MBeanRegistrationException e) {
throw new CacheException(e);
} catch (InstanceNotFoundException e) {
// throw new CacheException(e);
} catch (MalformedObjectNameException e) {
throw new CacheException("Illegal ObjectName for Management Bean. " +
"CacheManager=[" + getURI().toString() + "], Cache=[" + jCache.getName() + "]", e);
}
}
public NCacheStatisticsMXBean getMBeanServer(String cache) {
return statMXBeans.get(allCaches.get(cache));
}
private void registerObject(final NCacheMXBean cacheMXBean) throws NotCompliantMBeanException,
InstanceAlreadyExistsException, MBeanRegistrationException, MalformedObjectNameException {
final ObjectName objectName = new ObjectName(cacheMXBean.getObjectName());
if (mBeanServer.queryNames(objectName, null).isEmpty()) {
mBeanServer.registerMBean(cacheMXBean, objectName);
}
}
private void unregisterObject(final NCacheMXBean cacheMXBean) throws MBeanRegistrationException, InstanceNotFoundException, MalformedObjectNameException {
if (cacheMXBean == null) return;
final String name = cacheMXBean.getObjectName();
final ObjectName objectName = new ObjectName(name);
for (ObjectName n : mBeanServer.queryNames(objectName, null)) {
mBeanServer.unregisterMBean(n);
}
}
private NCacheManagementMXBean getOrCreateCfgObject(final NCacheCache jCache) {
NCacheManagementMXBean cacheMXBean = (NCacheManagementMXBean) cfgMXBeans.get(jCache);
if (cacheMXBean == null) {
cacheMXBean = new NCacheManagementMXBean(jCache);
final NCacheManagementMXBean previous = (NCacheManagementMXBean) cfgMXBeans.putIfAbsent(jCache, cacheMXBean);
if (previous != null) {
cacheMXBean = previous;
}
}
return cacheMXBean;
}
private NCacheStatisticsMXBean getOrCreateStatObject(final NCacheCache jCache) {
NCacheStatisticsMXBean cacheMXBean = statMXBeans.get(jCache);
if (cacheMXBean == null) {
cacheMXBean = new NCacheStatisticsMXBean(jCache);
final NCacheStatisticsMXBean previous = statMXBeans.putIfAbsent(jCache, cacheMXBean);
if (previous != null) {
cacheMXBean = previous;
}
}
return cacheMXBean;
}
/**
* Closes the CacheManager.
*/
@Override
public void close() {
try
{
if(!closed)
jCacheCachingProvider.shutdown(this);
}
catch (SecurityException e){
throw new CacheException(e);
}
}
/**
* Determines whether the CacheManager instance has been closed
*
* @return
*/
@Override
public boolean isClosed() {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
return closed;
}
public void removeCache(String name) {
allCaches.remove(name);
}
/**
* Provides a standard mechanism to access the underlying concrete caching implementation to provide access to further, proprietary features.
*
* @param type - the proprietary class or interface of the underlying concrete CacheManager. It is this type that is returned.
* @return
*/
@Override
public T unwrap(Class type) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
if (type.isAssignableFrom(getClass()))
return type.cast(this);
if (type.isAssignableFrom(javax.cache.CacheManager.class))
return type.cast(javax.cache.CacheManager.class);
throw new IllegalArgumentException();
}
protected void checkManagerStatus() {
if (closed) throw new IllegalStateException();
}
public ExecutorService getExecutorService() {
return executorService;
}
public void shutdown() {
for (Cache jCache : allCaches.values()) {
try
{
allCaches.remove(jCache.getName());
jCache.close();
}
catch(Exception ignored){}
}
allCaches.clear();
closed = true;
}
void shutdown(final NCacheCache jCache) {
final Cache r = allCaches.remove(jCache.getName());
if (r == jCache) {
enableStatistics(false, jCache);
enableManagement(false, jCache);
((NCacheCache) jCache).shutdown();
}
}
}