HHH-8159 - Apply fixups indicated by analysis tools

This commit is contained in:
Steve Ebersole 2013-04-30 13:27:38 -05:00
parent 09a54fdc54
commit 97e28200f0
54 changed files with 2312 additions and 2399 deletions

View File

@ -29,8 +29,10 @@ import java.util.Properties;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.util.ClassLoaderUtil;
import org.jboss.logging.Logger;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.nonstop.NonstopAccessStrategyFactory;
import org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion;
@ -40,7 +42,7 @@ import org.hibernate.cache.ehcache.internal.regions.EhcacheQueryResultsRegion;
import org.hibernate.cache.ehcache.internal.regions.EhcacheTimestampsRegion;
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory;
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactoryImpl;
import org.hibernate.cache.ehcache.internal.util.HibernateUtil;
import org.hibernate.cache.ehcache.internal.util.HibernateEhcacheUtils;
import org.hibernate.cache.ehcache.management.impl.ProviderMBeanRegistrationHelper;
import org.hibernate.cache.spi.CacheDataDescription;
import org.hibernate.cache.spi.CollectionRegion;
@ -51,7 +53,6 @@ import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.TimestampsRegion;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.Settings;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.service.spi.InjectService;
/**
@ -65,172 +66,169 @@ import org.hibernate.service.spi.InjectService;
*/
abstract class AbstractEhcacheRegionFactory implements RegionFactory {
/**
* The Hibernate system property specifying the location of the ehcache configuration file name.
* <p/>
* If not set, ehcache.xml will be looked for in the root of the classpath.
* <p/>
* If set to say ehcache-1.xml, ehcache-1.xml will be looked for in the root of the classpath.
*/
public static final String NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME = "net.sf.ehcache.configurationResourceName";
/**
* The Hibernate system property specifying the location of the ehcache configuration file name.
* <p/>
* If not set, ehcache.xml will be looked for in the root of the classpath.
* <p/>
* If set to say ehcache-1.xml, ehcache-1.xml will be looked for in the root of the classpath.
*/
public static final String NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME = "net.sf.ehcache.configurationResourceName";
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
AbstractEhcacheRegionFactory.class.getName()
);
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
AbstractEhcacheRegionFactory.class.getName()
);
/**
* MBean registration helper class instance for Ehcache Hibernate MBeans.
*/
protected final ProviderMBeanRegistrationHelper mbeanRegistrationHelper = new ProviderMBeanRegistrationHelper();
/**
* MBean registration helper class instance for Ehcache Hibernate MBeans.
*/
protected final ProviderMBeanRegistrationHelper mbeanRegistrationHelper = new ProviderMBeanRegistrationHelper();
/**
* Ehcache CacheManager that supplied Ehcache instances for this Hibernate RegionFactory.
*/
protected volatile CacheManager manager;
/**
* Ehcache CacheManager that supplied Ehcache instances for this Hibernate RegionFactory.
*/
protected volatile CacheManager manager;
/**
* Settings object for the Hibernate persistence unit.
*/
protected Settings settings;
/**
* Settings object for the Hibernate persistence unit.
*/
protected Settings settings;
/**
* {@link EhcacheAccessStrategyFactory} for creating various access strategies
*/
protected final EhcacheAccessStrategyFactory accessStrategyFactory =
new NonstopAccessStrategyFactory( new EhcacheAccessStrategyFactoryImpl() );
/**
* {@link EhcacheAccessStrategyFactory} for creating various access strategies
*/
protected final EhcacheAccessStrategyFactory accessStrategyFactory =
new NonstopAccessStrategyFactory( new EhcacheAccessStrategyFactoryImpl() );
/**
* Whether to optimize for minimals puts or minimal gets.
* <p/>
* Indicates whether when operating in non-strict read/write or read-only mode
* Hibernate should optimize the access patterns for minimal puts or minimal gets.
* In Ehcache we default to minimal puts since this should have minimal to no
* affect on unclustered users, and has great benefit for clustered users.
* <p/>
* This setting can be overridden by setting the "hibernate.cache.use_minimal_puts"
* property in the Hibernate configuration.
*
* @return true, optimize for minimal puts
*/
public boolean isMinimalPutsEnabledByDefault() {
return true;
}
/**
* {@inheritDoc}
* <p/>
* In Ehcache we default to minimal puts since this should have minimal to no
* affect on unclustered users, and has great benefit for clustered users.
*
* @return true, optimize for minimal puts
*/
@Override
public boolean isMinimalPutsEnabledByDefault() {
/**
* {@inheritDoc}
*/
public long nextTimestamp() {
return net.sf.ehcache.util.Timestamper.next();
}
return true;
}
/**
* {@inheritDoc}
*/
public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
return new EhcacheEntityRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties );
}
@Override
public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
return new EhcacheNaturalIdRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties );
}
@Override
public long nextTimestamp() {
return net.sf.ehcache.util.Timestamper.next();
}
/**
* {@inheritDoc}
*/
public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
return new EhcacheCollectionRegion(
accessStrategyFactory,
getCache( regionName ),
settings,
metadata,
properties
);
}
@Override
public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
return new EhcacheEntityRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties );
}
/**
* {@inheritDoc}
*/
public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException {
return new EhcacheQueryResultsRegion( accessStrategyFactory, getCache( regionName ), properties );
}
@Override
public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
return new EhcacheNaturalIdRegion(
accessStrategyFactory,
getCache( regionName ),
settings,
metadata,
properties
);
}
@InjectService
public void setClassLoaderService(ClassLoaderService classLoaderService) {
this.classLoaderService = classLoaderService;
}
@Override
public CollectionRegion buildCollectionRegion(
String regionName,
Properties properties,
CacheDataDescription metadata)
throws CacheException {
return new EhcacheCollectionRegion(
accessStrategyFactory,
getCache( regionName ),
settings,
metadata,
properties
);
}
private ClassLoaderService classLoaderService;
@Override
public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException {
return new EhcacheQueryResultsRegion( accessStrategyFactory, getCache( regionName ), properties );
}
/**
* {@inheritDoc}
*/
public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException {
return new EhcacheTimestampsRegion( accessStrategyFactory, getCache( regionName ), properties );
}
@InjectService
@SuppressWarnings("UnusedDeclaration")
public void setClassLoaderService(ClassLoaderService classLoaderService) {
this.classLoaderService = classLoaderService;
}
private Ehcache getCache(String name) throws CacheException {
try {
Ehcache cache = manager.getEhcache( name );
if ( cache == null ) {
LOG.unableToFindEhCacheConfiguration( name );
manager.addCache( name );
cache = manager.getEhcache( name );
LOG.debug( "started EHCache region: " + name );
}
HibernateUtil.validateEhcache( cache );
return cache;
}
catch ( net.sf.ehcache.CacheException e ) {
throw new CacheException( e );
}
private ClassLoaderService classLoaderService;
}
@Override
public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException {
return new EhcacheTimestampsRegion( accessStrategyFactory, getCache( regionName ), properties );
}
/**
* Load a resource from the classpath.
*/
protected URL loadResource(String configurationResourceName) {
URL url = null;
if ( classLoaderService != null ) {
url = classLoaderService.locateResource( configurationResourceName );
}
if ( url == null ) {
ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();
if ( standardClassloader != null ) {
url = standardClassloader.getResource( configurationResourceName );
}
if ( url == null ) {
url = AbstractEhcacheRegionFactory.class.getResource( configurationResourceName );
}
}
if ( LOG.isDebugEnabled() ) {
LOG.debugf(
"Creating EhCacheRegionFactory from a specified resource: %s. Resolved to URL: %s",
configurationResourceName,
url
);
}
if ( url == null ) {
private Ehcache getCache(String name) throws CacheException {
try {
Ehcache cache = manager.getEhcache( name );
if ( cache == null ) {
LOG.unableToFindEhCacheConfiguration( name );
manager.addCache( name );
cache = manager.getEhcache( name );
LOG.debug( "started EHCache region: " + name );
}
HibernateEhcacheUtils.validateEhcache( cache );
return cache;
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
LOG.unableToLoadConfiguration( configurationResourceName );
}
return url;
}
}
/**
* Default access-type used when the configured using JPA 2.0 config. JPA 2.0 allows <code>@Cacheable(true)</code> to be attached to an
* entity without any access type or usage qualification.
* <p/>
* We are conservative here in specifying {@link AccessType#READ_WRITE} so as to follow the mantra of "do no harm".
* <p/>
* This is a Hibernate 3.5 method.
*/
public AccessType getDefaultAccessType() {
return AccessType.READ_WRITE;
}
/**
* Load a resource from the classpath.
*/
protected URL loadResource(String configurationResourceName) {
URL url = null;
if ( classLoaderService != null ) {
url = classLoaderService.locateResource( configurationResourceName );
}
if ( url == null ) {
final ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();
if ( standardClassloader != null ) {
url = standardClassloader.getResource( configurationResourceName );
}
if ( url == null ) {
url = AbstractEhcacheRegionFactory.class.getResource( configurationResourceName );
}
}
if ( LOG.isDebugEnabled() ) {
LOG.debugf(
"Creating EhCacheRegionFactory from a specified resource: %s. Resolved to URL: %s",
configurationResourceName,
url
);
}
if ( url == null ) {
LOG.unableToLoadConfiguration( configurationResourceName );
}
return url;
}
/**
* Default access-type used when the configured using JPA 2.0 config. JPA 2.0 allows <code>@Cacheable(true)</code> to be attached to an
* entity without any access type or usage qualification.
* <p/>
* We are conservative here in specifying {@link AccessType#READ_WRITE} so as to follow the mantra of "do no harm".
* <p/>
* This is a Hibernate 3.5 method.
*/
public AccessType getDefaultAccessType() {
return AccessType.READ_WRITE;
}
}

View File

@ -37,45 +37,99 @@ import static org.jboss.logging.Logger.Level.WARN;
* <p/>
* New messages must be added after the last message defined to ensure message codes are unique.
*/
@MessageLogger( projectCode = "HHH" )
@MessageLogger(projectCode = "HHH")
public interface EhCacheMessageLogger extends CoreMessageLogger {
@LogMessage( level = WARN )
@Message( value = "Attempt to restart an already started EhCacheProvider. Use sessionFactory.close() between repeated calls to "
+ "buildSessionFactory. Using previously created EhCacheProvider. If this behaviour is required, consider "
+ "using net.sf.ehcache.hibernate.SingletonEhCacheProvider.", id = 20001 )
void attemptToRestartAlreadyStartedEhCacheProvider();
/**
* Log a message (WARN) about attempt to start an already started Ehcache region factory
*/
@LogMessage(level = WARN)
@Message(
value = "Attempt to restart an already started EhCacheRegionFactory. Use sessionFactory.close() between " +
"repeated calls to buildSessionFactory. Using previously created EhCacheRegionFactory. If this " +
"behaviour is required, consider using org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory.",
id = 20001
)
void attemptToRestartAlreadyStartedEhCacheProvider();
@LogMessage( level = WARN )
@Message( value = "Could not find configuration [%s]; using defaults.", id = 20002 )
void unableToFindConfiguration( String name );
/**
* Log a message (WARN) about inability to find configuration file
*
* @param name The name of the configuration file
*/
@LogMessage(level = WARN)
@Message(value = "Could not find configuration [%s]; using defaults.", id = 20002)
void unableToFindConfiguration(String name);
@LogMessage( level = WARN )
@Message( value = "Could not find a specific ehcache configuration for cache named [%s]; using defaults.", id = 20003 )
void unableToFindEhCacheConfiguration( String name );
/**
* Log a message (WARN) about inability to find named cache configuration
*
* @param name The name of the cache configuration
*/
@LogMessage(level = WARN)
@Message(value = "Could not find a specific ehcache configuration for cache named [%s]; using defaults.", id = 20003)
void unableToFindEhCacheConfiguration(String name);
@LogMessage( level = WARN )
@Message( value = "A configurationResourceName was set to %s but the resource could not be loaded from the classpath. Ehcache will configure itself using defaults.", id = 20004 )
void unableToLoadConfiguration( String configurationResourceName );
/**
* Logs a message about not being able to resolve the configuration by resource name.
*
* @param configurationResourceName The resource name we attempted to resolve
*/
@LogMessage(level = WARN)
@Message(
value = "A configurationResourceName was set to %s but the resource could not be loaded from the classpath. " +
"Ehcache will configure itself using defaults.",
id = 20004
)
void unableToLoadConfiguration(String configurationResourceName);
@LogMessage( level = WARN )
@Message( value = "The default cache value mode for this Ehcache configuration is \"identity\". This is incompatible with clustered "
+ "Hibernate caching - the value mode has therefore been switched to \"serialization\"", id = 20005 )
void incompatibleCacheValueMode( );
/**
* Logs a message (WARN) about attempt to use an incompatible
* {@link net.sf.ehcache.config.TerracottaConfiguration.ValueMode}.
*/
@LogMessage(level = WARN)
@Message(
value = "The default cache value mode for this Ehcache configuration is \"identity\". " +
"This is incompatible with clustered Hibernate caching - the value mode has therefore been " +
"switched to \"serialization\"",
id = 20005
)
void incompatibleCacheValueMode();
@LogMessage( level = WARN )
@Message( value = "The value mode for the cache[%s] is \"identity\". This is incompatible with clustered Hibernate caching - "
+ "the value mode has therefore been switched to \"serialization\"", id = 20006 )
void incompatibleCacheValueModePerCache( String cacheName );
@LogMessage( level = WARN )
@Message( value = "read-only cache configured for mutable entity [%s]", id = 20007 )
void readOnlyCacheConfiguredForMutableEntity( String entityName );
/**
* Logs a message (WARN) about attempt to use an incompatible
* {@link net.sf.ehcache.config.TerracottaConfiguration.ValueMode}.
*
* @param cacheName The name of the cache whose config attempted to specify value mode.
*/
@LogMessage(level = WARN)
@Message(value = "The value mode for the cache[%s] is \"identity\". This is incompatible with clustered Hibernate caching - "
+ "the value mode has therefore been switched to \"serialization\"", id = 20006)
void incompatibleCacheValueModePerCache(String cacheName);
@LogMessage( level = WARN )
@Message( value = "Cache[%s] Key[%s] Lockable[%s]\n"
+ "A soft-locked cache entry was expired by the underlying Ehcache. "
+ "If this happens regularly you should consider increasing the cache timeouts and/or capacity limits", id = 20008 )
void softLockedCacheExpired( String regionName, Object key, String lock);
/**
* Log a message (WARN) about an attempt to specify read-only caching for a mutable entity
*
* @param entityName The name of the entity
*/
@LogMessage(level = WARN)
@Message(value = "read-only cache configured for mutable entity [%s]", id = 20007)
void readOnlyCacheConfiguredForMutableEntity(String entityName);
/**
* Log a message (WARN) about expiry of soft-locked region.
*
* @param regionName The region name
* @param key The cache key
* @param lock The lock
*/
@LogMessage(level = WARN)
@Message(
value = "Cache[%s] Key[%s] Lockable[%s]\n" +
"A soft-locked cache entry was expired by the underlying Ehcache. If this happens regularly you " +
"should consider increasing the cache timeouts and/or capacity limits",
id = 20008
)
void softLockedCacheExpired(String regionName, Object key, String lock);
}

View File

@ -30,10 +30,11 @@ import java.util.Properties;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.Configuration;
import net.sf.ehcache.config.ConfigurationFactory;
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.util.HibernateUtil;
import org.hibernate.cache.ehcache.internal.util.HibernateEhcacheUtils;
import org.hibernate.cfg.Settings;
/**
@ -47,85 +48,88 @@ import org.hibernate.cfg.Settings;
*/
public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
EhCacheRegionFactory.class.getName()
);
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
EhCacheRegionFactory.class.getName()
);
public EhCacheRegionFactory() {
}
/**
* Creates a non-singleton EhCacheRegionFactory
*/
@SuppressWarnings("UnusedDeclaration")
public EhCacheRegionFactory() {
}
/**
* Creates a non-singleton EhCacheRegionFactory
*/
public EhCacheRegionFactory(Properties prop) {
super();
}
/**
* Creates a non-singleton EhCacheRegionFactory
*
* @param prop Not used
*/
@SuppressWarnings("UnusedDeclaration")
public EhCacheRegionFactory(Properties prop) {
super();
}
/**
* {@inheritDoc}
*/
public void start(Settings settings, Properties properties) throws CacheException {
this.settings = settings;
if ( manager != null ) {
LOG.attemptToRestartAlreadyStartedEhCacheProvider();
return;
}
@Override
public void start(Settings settings, Properties properties) throws CacheException {
this.settings = settings;
if ( manager != null ) {
LOG.attemptToRestartAlreadyStartedEhCacheProvider();
return;
}
try {
String configurationResourceName = null;
if ( properties != null ) {
configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME );
}
if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
Configuration configuration = ConfigurationFactory.parseConfiguration();
manager = new CacheManager( configuration );
}
else {
URL url;
try {
url = new URL( configurationResourceName );
}
catch ( MalformedURLException e ) {
url = loadResource( configurationResourceName );
}
Configuration configuration = HibernateUtil.loadAndCorrectConfiguration( url );
manager = new CacheManager( configuration );
}
mbeanRegistrationHelper.registerMBean( manager, properties );
}
catch ( net.sf.ehcache.CacheException e ) {
if ( e.getMessage().startsWith(
"Cannot parseConfiguration CacheManager. Attempt to create a new instance of " +
"CacheManager using the diskStorePath"
) ) {
throw new CacheException(
"Attempt to restart an already started EhCacheRegionFactory. " +
"Use sessionFactory.close() between repeated calls to buildSessionFactory. " +
"Consider using SingletonEhCacheRegionFactory. Error from ehcache was: " + e.getMessage()
);
}
else {
throw new CacheException( e );
}
}
}
try {
String configurationResourceName = null;
if ( properties != null ) {
configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME );
}
if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
final Configuration configuration = ConfigurationFactory.parseConfiguration();
manager = new CacheManager( configuration );
}
else {
URL url;
try {
url = new URL( configurationResourceName );
}
catch (MalformedURLException e) {
url = loadResource( configurationResourceName );
}
final Configuration configuration = HibernateEhcacheUtils.loadAndCorrectConfiguration( url );
manager = new CacheManager( configuration );
}
mbeanRegistrationHelper.registerMBean( manager, properties );
}
catch (net.sf.ehcache.CacheException e) {
if ( e.getMessage().startsWith(
"Cannot parseConfiguration CacheManager. Attempt to create a new instance of " +
"CacheManager using the diskStorePath"
) ) {
throw new CacheException(
"Attempt to restart an already started EhCacheRegionFactory. " +
"Use sessionFactory.close() between repeated calls to buildSessionFactory. " +
"Consider using SingletonEhCacheRegionFactory. Error from ehcache was: " + e.getMessage()
);
}
else {
throw new CacheException( e );
}
}
}
/**
* {@inheritDoc}
*/
public void stop() {
try {
if ( manager != null ) {
mbeanRegistrationHelper.unregisterMBean();
manager.shutdown();
manager = null;
}
}
catch ( net.sf.ehcache.CacheException e ) {
throw new CacheException( e );
}
}
@Override
public void stop() {
try {
if ( manager != null ) {
mbeanRegistrationHelper.unregisterMBean();
manager.shutdown();
manager = null;
}
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
}

View File

@ -30,10 +30,11 @@ import java.util.concurrent.atomic.AtomicInteger;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.Configuration;
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.util.HibernateUtil;
import org.hibernate.cache.ehcache.internal.util.HibernateEhcacheUtils;
import org.hibernate.cfg.Settings;
/**
@ -45,75 +46,80 @@ import org.hibernate.cfg.Settings;
* @author Alex Snaps
*/
public class SingletonEhCacheRegionFactory extends AbstractEhcacheRegionFactory {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
SingletonEhCacheRegionFactory.class.getName()
);
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
SingletonEhCacheRegionFactory.class.getName()
);
private static final AtomicInteger REFERENCE_COUNT = new AtomicInteger();
private static final AtomicInteger REFERENCE_COUNT = new AtomicInteger();
/**
* Returns a representation of the singleton EhCacheRegionFactory
*/
public SingletonEhCacheRegionFactory(Properties prop) {
super();
}
/**
* Constructs a SingletonEhCacheRegionFactory
*/
@SuppressWarnings("UnusedDeclaration")
public SingletonEhCacheRegionFactory() {
}
/**
* {@inheritDoc}
*/
public void start(Settings settings, Properties properties) throws CacheException {
this.settings = settings;
try {
String configurationResourceName = null;
if ( properties != null ) {
configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME );
}
if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
manager = CacheManager.create();
REFERENCE_COUNT.incrementAndGet();
}
else {
URL url;
try {
url = new URL( configurationResourceName );
}
catch ( MalformedURLException e ) {
if ( !configurationResourceName.startsWith( "/" ) ) {
configurationResourceName = "/" + configurationResourceName;
LOG.debugf(
"prepending / to %s. It should be placed in the root of the classpath rather than in a package.",
configurationResourceName
);
}
url = loadResource( configurationResourceName );
}
Configuration configuration = HibernateUtil.loadAndCorrectConfiguration( url );
manager = CacheManager.create( configuration );
REFERENCE_COUNT.incrementAndGet();
}
mbeanRegistrationHelper.registerMBean( manager, properties );
}
catch ( net.sf.ehcache.CacheException e ) {
throw new CacheException( e );
}
}
/**
* Constructs a SingletonEhCacheRegionFactory
*
* @param prop Not used
*/
@SuppressWarnings("UnusedDeclaration")
public SingletonEhCacheRegionFactory(Properties prop) {
super();
}
/**
* {@inheritDoc}
*/
public void stop() {
try {
if ( manager != null ) {
if ( REFERENCE_COUNT.decrementAndGet() == 0 ) {
manager.shutdown();
}
manager = null;
}
}
catch ( net.sf.ehcache.CacheException e ) {
throw new CacheException( e );
}
}
@Override
public void start(Settings settings, Properties properties) throws CacheException {
this.settings = settings;
try {
String configurationResourceName = null;
if ( properties != null ) {
configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME );
}
if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
manager = CacheManager.create();
REFERENCE_COUNT.incrementAndGet();
}
else {
URL url;
try {
url = new URL( configurationResourceName );
}
catch (MalformedURLException e) {
if ( !configurationResourceName.startsWith( "/" ) ) {
configurationResourceName = "/" + configurationResourceName;
LOG.debugf(
"prepending / to %s. It should be placed in the root of the classpath rather than in a package.",
configurationResourceName
);
}
url = loadResource( configurationResourceName );
}
final Configuration configuration = HibernateEhcacheUtils.loadAndCorrectConfiguration( url );
manager = CacheManager.create( configuration );
REFERENCE_COUNT.incrementAndGet();
}
mbeanRegistrationHelper.registerMBean( manager, properties );
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
@Override
public void stop() {
try {
if ( manager != null ) {
if ( REFERENCE_COUNT.decrementAndGet() == 0 ) {
manager.shutdown();
}
manager = null;
}
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
}

View File

@ -26,9 +26,9 @@ package org.hibernate.cache.ehcache;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl;
import org.hibernate.boot.registry.selector.StrategyRegistration;
import org.hibernate.boot.registry.selector.StrategyRegistrationProvider;
import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl;
import org.hibernate.cache.spi.RegionFactory;
/**
@ -49,7 +49,8 @@ public class StrategyRegistrationProviderImpl implements StrategyRegistrationPro
EhCacheRegionFactory.class,
"ehcache",
EhCacheRegionFactory.class.getSimpleName(),
"org.hibernate.cache.EhCacheRegionFactory" // legacy impl class name
// legacy impl class name
"org.hibernate.cache.EhCacheRegionFactory"
)
);
@ -59,7 +60,8 @@ public class StrategyRegistrationProviderImpl implements StrategyRegistrationPro
SingletonEhCacheRegionFactory.class,
"ehcache-singleton",
SingletonEhCacheRegionFactory.class.getSimpleName(),
"org.hibernate.cache.SingletonEhCacheRegionFactory" // legacy impl class name
// legacy impl class name
"org.hibernate.cache.SingletonEhCacheRegionFactory"
)
);

View File

@ -24,6 +24,7 @@
package org.hibernate.cache.ehcache.internal.nonstop;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
import org.jboss.logging.Logger;
import org.hibernate.cache.ehcache.EhCacheMessageLogger;
@ -35,61 +36,61 @@ import org.hibernate.cache.ehcache.EhCacheMessageLogger;
* @author Alex Snaps
*/
public final class HibernateNonstopCacheExceptionHandler {
/**
* Property name which set as "true" will throw exceptions on timeout with hibernate
*/
public static final String HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY = "ehcache.hibernate.propagateNonStopCacheException";
/**
* Property name which set as "true" will throw exceptions on timeout with hibernate
*/
public static final String HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY = "ehcache.hibernate.propagateNonStopCacheException";
/**
* Property name for logging the stack trace of the nonstop cache exception too. False by default
*/
public static final String HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY = "ehcache.hibernate.logNonStopCacheExceptionStackTrace";
/**
* Property name for logging the stack trace of the nonstop cache exception too. False by default
*/
public static final String HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY = "ehcache.hibernate.logNonStopCacheExceptionStackTrace";
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
HibernateNonstopCacheExceptionHandler.class.getName()
);
private static final HibernateNonstopCacheExceptionHandler INSTANCE = new HibernateNonstopCacheExceptionHandler();
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
HibernateNonstopCacheExceptionHandler.class.getName()
);
private static final HibernateNonstopCacheExceptionHandler INSTANCE = new HibernateNonstopCacheExceptionHandler();
/**
* private constructor
*/
private HibernateNonstopCacheExceptionHandler() {
// private
}
/**
* private constructor
*/
private HibernateNonstopCacheExceptionHandler() {
// private
}
/**
* Returns the singleton instance
*
* @return the singleton instance
*/
public static HibernateNonstopCacheExceptionHandler getInstance() {
return INSTANCE;
}
/**
* Returns the singleton instance
*
* @return the singleton instance
*/
public static HibernateNonstopCacheExceptionHandler getInstance() {
return INSTANCE;
}
/**
* Handle {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}.
* If {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY} system property is set to true,
* rethrows the {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}, otherwise logs the exception. While logging, if
* {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY} is set to true, logs the exception stack
* trace too, otherwise logs the exception message only
*
* @param nonStopCacheException
*/
public void handleNonstopCacheException(NonStopCacheException nonStopCacheException) {
if ( Boolean.getBoolean( HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY ) ) {
throw nonStopCacheException;
}
else {
if ( Boolean.getBoolean( HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY ) ) {
LOG.debug(
"Ignoring NonstopCacheException - " + nonStopCacheException.getMessage(),
nonStopCacheException
);
}
else {
LOG.debug( "Ignoring NonstopCacheException - " + nonStopCacheException.getMessage() );
}
}
}
/**
* Handle {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}.
* If {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY} system property is set to true,
* rethrows the {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}, otherwise logs the exception. While logging, if
* {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY} is set to true, logs the exception stack
* trace too, otherwise logs the exception message only
*
* @param nonStopCacheException The exception to handle
*/
public void handleNonstopCacheException(NonStopCacheException nonStopCacheException) {
if ( Boolean.getBoolean( HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY ) ) {
throw nonStopCacheException;
}
else {
if ( Boolean.getBoolean( HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY ) ) {
LOG.debug(
"Ignoring NonstopCacheException - " + nonStopCacheException.getMessage(),
nonStopCacheException
);
}
else {
LOG.debug( "Ignoring NonstopCacheException - " + nonStopCacheException.getMessage() );
}
}
}
}

View File

@ -41,49 +41,49 @@ import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy;
*/
public class NonstopAccessStrategyFactory implements EhcacheAccessStrategyFactory {
private final EhcacheAccessStrategyFactory actualFactory;
/**
* Constructor accepting the actual factory
*
* @param actualFactory
*/
public NonstopAccessStrategyFactory(EhcacheAccessStrategyFactory actualFactory) {
this.actualFactory = actualFactory;
}
/**
* {@inheritDoc}
*/
public EntityRegionAccessStrategy createEntityRegionAccessStrategy(EhcacheEntityRegion entityRegion, AccessType accessType) {
return new NonstopAwareEntityRegionAccessStrategy(
actualFactory.createEntityRegionAccessStrategy( entityRegion, accessType ),
HibernateNonstopCacheExceptionHandler.getInstance()
);
}
@Override
public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion naturalIdRegion,
AccessType accessType) {
return new NonstopAwareNaturalIdRegionAccessStrategy(
actualFactory.createNaturalIdRegionAccessStrategy(
naturalIdRegion,
accessType
), HibernateNonstopCacheExceptionHandler.getInstance()
);
}
private final EhcacheAccessStrategyFactory actualFactory;
/**
* {@inheritDoc}
*/
public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(EhcacheCollectionRegion collectionRegion,
AccessType accessType) {
return new NonstopAwareCollectionRegionAccessStrategy(
actualFactory.createCollectionRegionAccessStrategy(
collectionRegion,
accessType
), HibernateNonstopCacheExceptionHandler.getInstance()
);
}
* Constructor accepting the actual factory
*
* @param actualFactory The wrapped RegionAccessStrategy factory
*/
public NonstopAccessStrategyFactory(EhcacheAccessStrategyFactory actualFactory) {
this.actualFactory = actualFactory;
}
@Override
public EntityRegionAccessStrategy createEntityRegionAccessStrategy(
EhcacheEntityRegion entityRegion,
AccessType accessType) {
return new NonstopAwareEntityRegionAccessStrategy(
actualFactory.createEntityRegionAccessStrategy( entityRegion, accessType ),
HibernateNonstopCacheExceptionHandler.getInstance()
);
}
@Override
public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(
EhcacheNaturalIdRegion naturalIdRegion,
AccessType accessType) {
return new NonstopAwareNaturalIdRegionAccessStrategy(
actualFactory.createNaturalIdRegionAccessStrategy(
naturalIdRegion,
accessType
), HibernateNonstopCacheExceptionHandler.getInstance()
);
}
@Override
public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(
EhcacheCollectionRegion collectionRegion,
AccessType accessType) {
return new NonstopAwareCollectionRegionAccessStrategy(
actualFactory.createCollectionRegionAccessStrategy(
collectionRegion,
accessType
), HibernateNonstopCacheExceptionHandler.getInstance()
);
}
}

View File

@ -38,188 +38,139 @@ import org.hibernate.cache.spi.access.SoftLock;
* @author Alex Snaps
*/
public class NonstopAwareCollectionRegionAccessStrategy implements CollectionRegionAccessStrategy {
private final CollectionRegionAccessStrategy actualStrategy;
private final HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler;
/**
* Constructor accepting the actual {@link CollectionRegionAccessStrategy} and the {@link HibernateNonstopCacheExceptionHandler}
*
* @param actualStrategy
* @param hibernateNonstopExceptionHandler
* @param actualStrategy The wrapped strategy
* @param hibernateNonstopExceptionHandler The exception handler
*/
public NonstopAwareCollectionRegionAccessStrategy(CollectionRegionAccessStrategy actualStrategy,
HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
public NonstopAwareCollectionRegionAccessStrategy(
CollectionRegionAccessStrategy actualStrategy,
HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
this.actualStrategy = actualStrategy;
this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler;
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#getRegion()
*/
@Override
public CollectionRegion getRegion() {
return actualStrategy.getRegion();
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evict(java.lang.Object)
*/
@Override
public void evict(Object key) throws CacheException {
try {
actualStrategy.evict( key );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll()
*/
@Override
public void evictAll() throws CacheException {
try {
actualStrategy.evictAll();
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long)
*/
@Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
return actualStrategy.get( key, txTimestamp );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
*/
@Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
try {
return actualStrategy.lockItem( key, version );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion()
*/
@Override
public SoftLock lockRegion() throws CacheException {
try {
return actualStrategy.lockRegion();
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object,
* boolean)
*/
@Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version, minimalPutOverride );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)
*/
@Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#remove(java.lang.Object)
*/
@Override
public void remove(Object key) throws CacheException {
try {
actualStrategy.remove( key );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll()
*/
@Override
public void removeAll() throws CacheException {
try {
actualStrategy.removeAll();
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
*/
@Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
try {
actualStrategy.unlockItem( key, lock );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockRegion(org.hibernate.cache.spi.access.SoftLock)
*/
@Override
public void unlockRegion(SoftLock lock) throws CacheException {
try {
actualStrategy.unlockRegion( lock );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}

View File

@ -38,253 +38,186 @@ import org.hibernate.cache.spi.access.SoftLock;
* @author Alex Snaps
*/
public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAccessStrategy {
private final EntityRegionAccessStrategy actualStrategy;
private final HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler;
/**
* Constructor accepting the actual {@link EntityRegionAccessStrategy} and the {@link HibernateNonstopCacheExceptionHandler}
*
* @param actualStrategy
* @param hibernateNonstopExceptionHandler
* @param actualStrategy The wrapped EntityRegionAccessStrategy
* @param hibernateNonstopExceptionHandler The exception handler
*/
public NonstopAwareEntityRegionAccessStrategy(EntityRegionAccessStrategy actualStrategy,
HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
public NonstopAwareEntityRegionAccessStrategy(
EntityRegionAccessStrategy actualStrategy,
HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
this.actualStrategy = actualStrategy;
this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler;
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#getRegion()
*/
@Override
public EntityRegion getRegion() {
return actualStrategy.getRegion();
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#afterInsert(java.lang.Object, java.lang.Object, java.lang.Object)
*/
@Override
public boolean afterInsert(Object key, Object value, Object version) throws CacheException {
try {
return actualStrategy.afterInsert( key, value, version );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#afterUpdate(java.lang.Object, java.lang.Object, java.lang.Object,
* java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
*/
@Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock)
throws CacheException {
try {
return actualStrategy.afterUpdate( key, value, currentVersion, previousVersion, lock );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evict(java.lang.Object)
*/
@Override
public void evict(Object key) throws CacheException {
try {
actualStrategy.evict( key );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll()
*/
@Override
public void evictAll() throws CacheException {
try {
actualStrategy.evictAll();
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long)
*/
@Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
return actualStrategy.get( key, txTimestamp );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#insert(java.lang.Object, java.lang.Object, java.lang.Object)
*/
@Override
public boolean insert(Object key, Object value, Object version) throws CacheException {
try {
return actualStrategy.insert( key, value, version );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
*/
@Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
try {
return actualStrategy.lockItem( key, version );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion()
*/
@Override
public SoftLock lockRegion() throws CacheException {
try {
return actualStrategy.lockRegion();
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object,
* boolean)
*/
@Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version, minimalPutOverride );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)
*/
@Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#remove(java.lang.Object)
*/
@Override
public void remove(Object key) throws CacheException {
try {
actualStrategy.remove( key );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll()
*/
@Override
public void removeAll() throws CacheException {
try {
actualStrategy.removeAll();
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
*/
@Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
try {
actualStrategy.unlockItem( key, lock );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockRegion(org.hibernate.cache.spi.access.SoftLock)
*/
@Override
public void unlockRegion(SoftLock lock) throws CacheException {
try {
actualStrategy.unlockRegion( lock );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#update(java.lang.Object, java.lang.Object, java.lang.Object,
* java.lang.Object)
*/
@Override
public boolean update(Object key, Object value, Object currentVersion, Object previousVersion)
throws CacheException {
try {
return actualStrategy.update( key, value, currentVersion, previousVersion );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
}
}

View File

@ -38,28 +38,28 @@ import org.hibernate.cache.spi.access.SoftLock;
* @author Alex Snaps
*/
public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegionAccessStrategy {
private final NaturalIdRegionAccessStrategy actualStrategy;
private final HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler;
/**
* Constructor accepting the actual {@link NaturalIdRegionAccessStrategy} and the {@link HibernateNonstopCacheExceptionHandler}
*
* @param actualStrategy
* @param hibernateNonstopExceptionHandler
* @param actualStrategy The wrapped NaturalIdRegionAccessStrategy
* @param hibernateNonstopExceptionHandler The exception handler
*/
public NonstopAwareNaturalIdRegionAccessStrategy(NaturalIdRegionAccessStrategy actualStrategy,
HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
public NonstopAwareNaturalIdRegionAccessStrategy(
NaturalIdRegionAccessStrategy actualStrategy,
HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
this.actualStrategy = actualStrategy;
this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler;
}
@Override
public boolean insert(Object key, Object value) throws CacheException {
try {
return actualStrategy.insert( key, value );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
@ -70,7 +70,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
try {
return actualStrategy.afterInsert( key, value );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
@ -81,7 +81,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
try {
return actualStrategy.update( key, value );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
@ -92,178 +92,129 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
try {
return actualStrategy.afterUpdate( key, value, lock );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#getRegion()
*/
@Override
public NaturalIdRegion getRegion() {
return actualStrategy.getRegion();
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evict(java.lang.Object)
*/
@Override
public void evict(Object key) throws CacheException {
try {
actualStrategy.evict( key );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll()
*/
@Override
public void evictAll() throws CacheException {
try {
actualStrategy.evictAll();
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long)
*/
@Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
return actualStrategy.get( key, txTimestamp );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
*/
@Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
try {
return actualStrategy.lockItem( key, version );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion()
*/
@Override
public SoftLock lockRegion() throws CacheException {
try {
return actualStrategy.lockRegion();
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object,
* boolean)
*/
@Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version, minimalPutOverride );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)
*/
@Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#remove(java.lang.Object)
*/
@Override
public void remove(Object key) throws CacheException {
try {
actualStrategy.remove( key );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll()
*/
@Override
public void removeAll() throws CacheException {
try {
actualStrategy.removeAll();
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
*/
@Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
try {
actualStrategy.unlockItem( key, lock );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockRegion(org.hibernate.cache.spi.access.SoftLock)
*/
@Override
public void unlockRegion(SoftLock lock) throws CacheException {
try {
actualStrategy.unlockRegion( lock );
}
catch ( NonStopCacheException nonStopCacheException ) {
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}

View File

@ -0,0 +1,5 @@
/**
* Support for handling non-stop caches. Really no idea. The Ehcache guys added this and tbh I really do not
* understand the intent
*/
package org.hibernate.cache.ehcache.internal.nonstop;

View File

@ -47,22 +47,26 @@ import org.hibernate.cfg.Settings;
* @author Alex Snaps
*/
public class EhcacheCollectionRegion extends EhcacheTransactionalDataRegion implements CollectionRegion {
/**
* Constructs an EhcacheCollectionRegion around the given underlying cache.
*
* @param accessStrategyFactory The factory for building needed CollectionRegionAccessStrategy instance
* @param underlyingCache The ehcache cache instance
* @param settings The Hibernate settings
* @param metadata Metadata about the data to be cached in this region
* @param properties Any additional[ properties
*/
public EhcacheCollectionRegion(
EhcacheAccessStrategyFactory accessStrategyFactory,
Ehcache underlyingCache,
Settings settings,
CacheDataDescription metadata,
Properties properties) {
super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
}
/**
* Constructs an EhcacheCollectionRegion around the given underlying cache.
*
* @param accessStrategyFactory
*/
public EhcacheCollectionRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Settings settings,
CacheDataDescription metadata, Properties properties) {
super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
}
/**
* {@inheritDoc}
*/
public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
return accessStrategyFactory.createCollectionRegionAccessStrategy( this, accessType );
}
}
@Override
public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
return getAccessStrategyFactory().createCollectionRegionAccessStrategy( this, accessType );
}
}

View File

@ -32,6 +32,7 @@ import java.util.Properties;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
import net.sf.ehcache.util.Timestamper;
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
@ -52,174 +53,163 @@ import org.hibernate.cache.spi.Region;
* @author Alex Snaps
*/
public abstract class EhcacheDataRegion implements Region {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
EhcacheDataRegion.class.getName()
);
private static final String CACHE_LOCK_TIMEOUT_PROPERTY = "net.sf.ehcache.hibernate.cache_lock_timeout";
private static final int DEFAULT_CACHE_LOCK_TIMEOUT = 60000;
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
EhcacheDataRegion.class.getName()
);
private static final String CACHE_LOCK_TIMEOUT_PROPERTY = "net.sf.ehcache.hibernate.cache_lock_timeout";
private static final int DEFAULT_CACHE_LOCK_TIMEOUT = 60000;
/**
* Ehcache instance backing this Hibernate data region.
*/
protected final Ehcache cache;
/**
* The {@link EhcacheAccessStrategyFactory} used for creating various access strategies
*/
protected final EhcacheAccessStrategyFactory accessStrategyFactory;
private final int cacheLockTimeout;
private final Ehcache cache;
private final EhcacheAccessStrategyFactory accessStrategyFactory;
private final int cacheLockTimeout;
/**
* Create a Hibernate data region backed by the given Ehcache instance.
*/
EhcacheDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Properties properties) {
this.accessStrategyFactory = accessStrategyFactory;
this.cache = cache;
String timeout = properties.getProperty(
CACHE_LOCK_TIMEOUT_PROPERTY,
Integer.toString( DEFAULT_CACHE_LOCK_TIMEOUT )
);
this.cacheLockTimeout = Timestamper.ONE_MS * Integer.decode( timeout );
}
/**
* Create a Hibernate data region backed by the given Ehcache instance.
*/
EhcacheDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Properties properties) {
this.accessStrategyFactory = accessStrategyFactory;
this.cache = cache;
final String timeout = properties.getProperty(
CACHE_LOCK_TIMEOUT_PROPERTY,
Integer.toString( DEFAULT_CACHE_LOCK_TIMEOUT )
);
this.cacheLockTimeout = Timestamper.ONE_MS * Integer.decode( timeout );
}
/**
* {@inheritDoc}
*/
public String getName() {
return cache.getName();
}
/**
* Ehcache instance backing this Hibernate data region.
*/
protected Ehcache getCache() {
return cache;
}
/**
* {@inheritDoc}
*/
public void destroy() throws CacheException {
try {
cache.getCacheManager().removeCache( cache.getName() );
}
catch ( IllegalStateException e ) {
//When Spring and Hibernate are both involved this will happen in normal shutdown operation.
//Do not throw an exception, simply log this one.
LOG.debug( "This can happen if multiple frameworks both try to shutdown ehcache", e );
}
catch ( net.sf.ehcache.CacheException e ) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
/**
* The {@link org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory} used for creating
* various access strategies
*/
protected EhcacheAccessStrategyFactory getAccessStrategyFactory() {
return accessStrategyFactory;
}
/**
* {@inheritDoc}
*/
public long getSizeInMemory() {
try {
return cache.calculateInMemorySize();
}
catch ( Throwable t ) {
if ( t instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) t );
}
return -1;
}
}
/**
* Return the Ehcache instance backing this Hibernate data region.
*
* @return The underlying ehcache cache
*/
public Ehcache getEhcache() {
return getCache();
}
/**
* {@inheritDoc}
*/
public long getElementCountInMemory() {
try {
return cache.getMemoryStoreSize();
}
catch ( net.sf.ehcache.CacheException ce ) {
if ( ce instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) ce );
return -1;
}
else {
throw new CacheException( ce );
}
}
}
@Override
public String getName() {
return getCache().getName();
}
/**
* {@inheritDoc}
*/
public long getElementCountOnDisk() {
try {
return cache.getDiskStoreSize();
}
catch ( net.sf.ehcache.CacheException ce ) {
if ( ce instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) ce );
return -1;
}
else {
throw new CacheException( ce );
}
}
}
@Override
public void destroy() throws CacheException {
try {
getCache().getCacheManager().removeCache( getCache().getName() );
}
catch (IllegalStateException e) {
//When Spring and Hibernate are both involved this will happen in normal shutdown operation.
//Do not throw an exception, simply log this one.
LOG.debug( "This can happen if multiple frameworks both try to shutdown ehcache", e );
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
/**
* {@inheritDoc}
*/
public Map toMap() {
try {
Map<Object, Object> result = new HashMap<Object, Object>();
for ( Object key : cache.getKeys() ) {
result.put( key, cache.get( key ).getObjectValue() );
}
return result;
}
catch ( Exception e ) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
return Collections.emptyMap();
}
else {
throw new CacheException( e );
}
}
}
@Override
public long getSizeInMemory() {
try {
return getCache().calculateInMemorySize();
}
catch (Throwable t) {
if ( t instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) t );
}
return -1;
}
}
/**
* {@inheritDoc}
*/
public long nextTimestamp() {
return Timestamper.next();
}
@Override
public long getElementCountInMemory() {
try {
return getCache().getMemoryStoreSize();
}
catch (net.sf.ehcache.CacheException ce) {
if ( ce instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) ce );
return -1;
}
else {
throw new CacheException( ce );
}
}
}
/**
* {@inheritDoc}
*/
public int getTimeout() {
return cacheLockTimeout;
}
@Override
public long getElementCountOnDisk() {
try {
return getCache().getDiskStoreSize();
}
catch (net.sf.ehcache.CacheException ce) {
if ( ce instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) ce );
return -1;
}
else {
throw new CacheException( ce );
}
}
}
/**
* Return the Ehcache instance backing this Hibernate data region.
*/
public Ehcache getEhcache() {
return cache;
}
@Override
public Map toMap() {
try {
final Map<Object, Object> result = new HashMap<Object, Object>();
for ( Object key : getCache().getKeys() ) {
result.put( key, getCache().get( key ).getObjectValue() );
}
return result;
}
catch (Exception e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
return Collections.emptyMap();
}
else {
throw new CacheException( e );
}
}
}
@Override
public long nextTimestamp() {
return Timestamper.next();
}
@Override
public int getTimeout() {
return cacheLockTimeout;
}
@Override
public boolean contains(Object key) {
return getCache().isKeyInCache( key );
}
/**
* Returns <code>true</code> if this region contains data for the given key.
* <p/>
* This is a Hibernate 3.5 method.
*/
public boolean contains(Object key) {
return cache.isKeyInCache( key );
}
}

View File

@ -46,22 +46,26 @@ import org.hibernate.cfg.Settings;
* @author Alex Snaps
*/
public class EhcacheEntityRegion extends EhcacheTransactionalDataRegion implements EntityRegion {
/**
* Constructs an EhcacheCollectionRegion around the given underlying cache.
*
* @param accessStrategyFactory The factory for building needed EntityRegionAccessStrategy instance
* @param underlyingCache The ehcache cache instance
* @param settings The Hibernate settings
* @param metadata Metadata about the data to be cached in this region
* @param properties Any additional[ properties
*/
public EhcacheEntityRegion(
EhcacheAccessStrategyFactory accessStrategyFactory,
Ehcache underlyingCache,
Settings settings,
CacheDataDescription metadata,
Properties properties) {
super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
}
/**
* Constructs an EhcacheEntityRegion around the given underlying cache.
*
* @param accessStrategyFactory
*/
public EhcacheEntityRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Settings settings,
CacheDataDescription metadata, Properties properties) {
super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
}
/**
* {@inheritDoc}
*/
public EntityRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
return accessStrategyFactory.createEntityRegionAccessStrategy( this, accessType );
}
}
@Override
public EntityRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
return getAccessStrategyFactory().createEntityRegionAccessStrategy( this, accessType );
}
}

View File

@ -28,6 +28,7 @@ import java.util.Properties;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
@ -48,119 +49,117 @@ import org.hibernate.cache.spi.GeneralDataRegion;
* @author Alex Snaps
*/
abstract class EhcacheGeneralDataRegion extends EhcacheDataRegion implements GeneralDataRegion {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
EhcacheGeneralDataRegion.class.getName()
);
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
EhcacheGeneralDataRegion.class.getName()
);
/**
* Constructs an EhcacheGeneralDataRegion around the given underlying cache.
*
* @param accessStrategyFactory The factory for building needed RegionAccessStrategy instance
* @param underlyingCache The ehcache cache instance
* @param properties Any additional[ properties
*/
public EhcacheGeneralDataRegion(
EhcacheAccessStrategyFactory accessStrategyFactory,
Ehcache underlyingCache,
Properties properties) {
super( accessStrategyFactory, underlyingCache, properties );
}
/**
* Creates an EhcacheGeneralDataRegion using the given Ehcache instance as a backing.
*/
public EhcacheGeneralDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Properties properties) {
super( accessStrategyFactory, cache, properties );
}
@Override
public Object get(Object key) throws CacheException {
try {
LOG.debugf( "key: %s", key );
if ( key == null ) {
return null;
}
else {
final Element element = getCache().get( key );
if ( element == null ) {
LOG.debugf( "Element for key %s is null", key );
return null;
}
else {
return element.getObjectValue();
}
}
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
return null;
}
else {
throw new CacheException( e );
}
}
}
/**
* {@inheritDoc}
*/
public Object get(Object key) throws CacheException {
try {
LOG.debugf( "key: %s", key );
if ( key == null ) {
return null;
}
else {
Element element = cache.get( key );
if ( element == null ) {
LOG.debugf( "Element for key %s is null", key );
return null;
}
else {
return element.getObjectValue();
}
}
}
catch ( net.sf.ehcache.CacheException e ) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
return null;
}
else {
throw new CacheException( e );
}
}
}
@Override
public void put(Object key, Object value) throws CacheException {
LOG.debugf( "key: %s value: %s", key, value );
try {
final Element element = new Element( key, value );
getCache().put( element );
}
catch (IllegalArgumentException e) {
throw new CacheException( e );
}
catch (IllegalStateException e) {
throw new CacheException( e );
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
/**
* {@inheritDoc}
*/
public void put(Object key, Object value) throws CacheException {
LOG.debugf( "key: %s value: %s", key, value );
try {
Element element = new Element( key, value );
cache.put( element );
}
catch ( IllegalArgumentException e ) {
throw new CacheException( e );
}
catch ( IllegalStateException e ) {
throw new CacheException( e );
}
catch ( net.sf.ehcache.CacheException e ) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
@Override
public void evict(Object key) throws CacheException {
try {
getCache().remove( key );
}
catch (ClassCastException e) {
throw new CacheException( e );
}
catch (IllegalStateException e) {
throw new CacheException( e );
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
/**
* {@inheritDoc}
*/
public void evict(Object key) throws CacheException {
try {
cache.remove( key );
}
catch ( ClassCastException e ) {
throw new CacheException( e );
}
catch ( IllegalStateException e ) {
throw new CacheException( e );
}
catch ( net.sf.ehcache.CacheException e ) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
/**
* {@inheritDoc}
*/
public void evictAll() throws CacheException {
try {
cache.removeAll();
}
catch ( IllegalStateException e ) {
throw new CacheException( e );
}
catch ( net.sf.ehcache.CacheException e ) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
@Override
public void evictAll() throws CacheException {
try {
getCache().removeAll();
}
catch (IllegalStateException e) {
throw new CacheException( e );
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
}

View File

@ -47,20 +47,26 @@ import org.hibernate.cfg.Settings;
* @author Alex Snaps
*/
public class EhcacheNaturalIdRegion extends EhcacheTransactionalDataRegion implements NaturalIdRegion {
/**
* Constructs an EhcacheNaturalIdRegion around the given underlying cache.
*
* @param accessStrategyFactory
*/
public EhcacheNaturalIdRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Settings settings,
CacheDataDescription metadata, Properties properties) {
super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
}
/**
* Constructs an EhcacheNaturalIdRegion around the given underlying cache.
*
* @param accessStrategyFactory The factory for building needed NaturalIdRegionAccessStrategy instance
* @param underlyingCache The ehcache cache instance
* @param settings The Hibernate settings
* @param metadata Metadata about the data to be cached in this region
* @param properties Any additional[ properties
*/
public EhcacheNaturalIdRegion(
EhcacheAccessStrategyFactory accessStrategyFactory,
Ehcache underlyingCache,
Settings settings,
CacheDataDescription metadata,
Properties properties) {
super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
}
@Override
public NaturalIdRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
return accessStrategyFactory.createNaturalIdRegionAccessStrategy( this, accessType );
return getAccessStrategyFactory().createNaturalIdRegionAccessStrategy( this, accessType );
}
}
}

View File

@ -37,14 +37,18 @@ import org.hibernate.cache.spi.QueryResultsRegion;
* @author Alex Snaps
*/
public class EhcacheQueryResultsRegion extends EhcacheGeneralDataRegion implements QueryResultsRegion {
/**
* Constructs an EhcacheQueryResultsRegion around the given underlying cache.
*
* @param accessStrategyFactory
* @param accessStrategyFactory The factory for building needed CollectionRegionAccessStrategy instance
* @param underlyingCache The ehcache cache instance
* @param properties Any additional[ properties
*/
public EhcacheQueryResultsRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Properties properties) {
public EhcacheQueryResultsRegion(
EhcacheAccessStrategyFactory accessStrategyFactory,
Ehcache underlyingCache,
Properties properties) {
super( accessStrategyFactory, underlyingCache, properties );
}
}
}

View File

@ -38,13 +38,17 @@ import org.hibernate.cache.spi.TimestampsRegion;
* @author Alex Snaps
*/
public class EhcacheTimestampsRegion extends EhcacheGeneralDataRegion implements TimestampsRegion {
/**
* Constructs an EhcacheTimestampsRegion around the given underlying cache.
*
* @param accessStrategyFactory
* @param accessStrategyFactory The factory for building needed CollectionRegionAccessStrategy instance
* @param underlyingCache The ehcache cache instance
* @param properties Any additional[ properties
*/
public EhcacheTimestampsRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Properties properties) {
super(accessStrategyFactory, underlyingCache, properties);
public EhcacheTimestampsRegion(
EhcacheAccessStrategyFactory accessStrategyFactory,
Ehcache underlyingCache,
Properties properties) {
super( accessStrategyFactory, underlyingCache, properties );
}
}
}

View File

@ -51,13 +51,9 @@ import org.hibernate.cfg.Settings;
* @author Alex Snaps
*/
public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements TransactionalDataRegion {
private static final int LOCAL_LOCK_PROVIDER_CONCURRENCY = 128;
/**
* Hibernate settings associated with the persistence unit.
*/
protected final Settings settings;
private final Settings settings;
/**
* Metadata associated with the objects stored in the region.
@ -69,13 +65,14 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Construct an transactional Hibernate cache region around the given Ehcache instance.
*/
EhcacheTransactionalDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Settings settings,
CacheDataDescription metadata, Properties properties) {
EhcacheTransactionalDataRegion(
EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Settings settings,
CacheDataDescription metadata, Properties properties) {
super( accessStrategyFactory, cache, properties );
this.settings = settings;
this.metadata = metadata;
Object context = cache.getInternalContext();
final Object context = cache.getInternalContext();
if ( context instanceof CacheLockProvider ) {
this.lockProvider = (CacheLockProvider) context;
}
@ -85,7 +82,7 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
}
/**
* Return the hibernate settings
* Access the Hibernate settings associated with the persistence unit.
*
* @return settings
*/
@ -93,26 +90,26 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
return settings;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTransactionAware() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public CacheDataDescription getCacheDataDescription() {
return metadata;
}
/**
* Get the value mapped to this key, or null if no value is mapped to this key.
*
* @param key The cache key
*
* @return The cached data
*/
public final Object get(Object key) {
try {
Element element = cache.get( key );
final Element element = getCache().get( key );
if ( element == null ) {
return null;
}
@ -120,7 +117,7 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
return element.getObjectValue();
}
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@ -134,19 +131,24 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Map the given value to the given key, replacing any existing mapping for this key
*
* @param key The cache key
* @param value The data to cache
*
* @throws CacheException Indicates a problem accessing the cache
*/
public final void put(Object key, Object value) throws CacheException {
try {
Element element = new Element( key, value );
cache.put( element );
final Element element = new Element( key, value );
getCache().put( element );
}
catch ( IllegalArgumentException e ) {
catch (IllegalArgumentException e) {
throw new CacheException( e );
}
catch ( IllegalStateException e ) {
catch (IllegalStateException e) {
throw new CacheException( e );
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@ -159,18 +161,22 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Remove the mapping for this key (if any exists).
*
* @param key The cache key
*
* @throws CacheException Indicates a problem accessing the cache
*/
public final void remove(Object key) throws CacheException {
try {
cache.remove( key );
getCache().remove( key );
}
catch ( ClassCastException e ) {
catch (ClassCastException e) {
throw new CacheException( e );
}
catch ( IllegalStateException e ) {
catch (IllegalStateException e) {
throw new CacheException( e );
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@ -183,15 +189,17 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Remove all mapping from this cache region.
*
* @throws CacheException Indicates a problem accessing the cache
*/
public final void clear() throws CacheException {
try {
cache.removeAll();
getCache().removeAll();
}
catch ( IllegalStateException e ) {
catch (IllegalStateException e) {
throw new CacheException( e );
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@ -204,12 +212,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Attempts to write lock the mapping for the given key.
*
* @param key The cache key
*
* @throws CacheException Indicates a problem accessing the cache
*/
public final void writeLock(Object key) {
try {
lockProvider.getSyncForKey( key ).lock( LockType.WRITE );
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@ -222,12 +234,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Attempts to write unlock the mapping for the given key.
*
* @param key The cache key
*
* @throws CacheException Indicates a problem accessing the cache
*/
public final void writeUnlock(Object key) {
try {
lockProvider.getSyncForKey( key ).unlock( LockType.WRITE );
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@ -240,12 +256,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Attempts to read lock the mapping for the given key.
*
* @param key The cache key
*
* @throws CacheException Indicates a problem accessing the cache
*/
public final void readLock(Object key) {
try {
lockProvider.getSyncForKey( key ).lock( LockType.WRITE );
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@ -258,12 +278,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Attempts to read unlock the mapping for the given key.
*
* @param key The cache key
*
* @throws CacheException Indicates a problem accessing the cache
*/
public final void readUnlock(Object key) {
try {
lockProvider.getSyncForKey( key ).unlock( LockType.WRITE );
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@ -279,6 +303,8 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
* <p/>
* Independent locks are not locked by the cache when the cache is accessed directly. This means that for an independent lock
* lock holds taken through a region method will not block direct access to the cache via other means.
*
* @return true/false. See discussion above.
*/
public final boolean locksAreIndependentOfCache() {
return lockProvider instanceof StripedReadWriteLockSync;

View File

@ -0,0 +1,4 @@
/**
* Defines {@link org.hibernate.cache.spi.RegionFactory} support for the Ehcache integration
*/
package org.hibernate.cache.ehcache.internal.regions;

View File

@ -37,24 +37,34 @@ import org.hibernate.cfg.Settings;
* @author Alex Snaps
*/
abstract class AbstractEhcacheAccessStrategy<T extends EhcacheTransactionalDataRegion> {
/**
* The wrapped Hibernate cache region.
*/
protected final T region;
/**
* The settings for this persistence unit.
*/
protected final Settings settings;
private final T region;
private final Settings settings;
/**
* Create an access strategy wrapping the given region.
*
* @param region The wrapped region. Accessible to subclasses via {@link #region()}
* @param settings The Hibernate settings. Accessible to subclasses via {@link #settings()}
*/
AbstractEhcacheAccessStrategy(T region, Settings settings) {
this.region = region;
this.settings = settings;
}
/**
* The wrapped Hibernate cache region.
*/
protected T region() {
return region;
}
/**
* The settings for this persistence unit.
*/
protected Settings settings() {
return settings;
}
/**
* This method is a placeholder for method signatures supplied by interfaces pulled in further down the class
* hierarchy.
@ -84,6 +94,7 @@ abstract class AbstractEhcacheAccessStrategy<T extends EhcacheTransactionalDataR
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion()
* @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#lockRegion()
*/
@SuppressWarnings("UnusedDeclaration")
public final SoftLock lockRegion() {
return null;
}
@ -94,6 +105,7 @@ abstract class AbstractEhcacheAccessStrategy<T extends EhcacheTransactionalDataR
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockRegion(org.hibernate.cache.spi.access.SoftLock)
* @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#unlockRegion(org.hibernate.cache.spi.access.SoftLock)
*/
@SuppressWarnings("UnusedDeclaration")
public final void unlockRegion(SoftLock lock) throws CacheException {
region.clear();
}
@ -114,6 +126,7 @@ abstract class AbstractEhcacheAccessStrategy<T extends EhcacheTransactionalDataR
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll()
* @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#removeAll()
*/
@SuppressWarnings("UnusedDeclaration")
public final void removeAll() throws CacheException {
region.clear();
}
@ -134,7 +147,8 @@ abstract class AbstractEhcacheAccessStrategy<T extends EhcacheTransactionalDataR
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll()
* @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#evictAll()
*/
@SuppressWarnings("UnusedDeclaration")
public final void evictAll() throws CacheException {
region.clear();
}
}
}

View File

@ -44,384 +44,361 @@ import org.hibernate.cfg.Settings;
* @author Chris Dennis
* @author Alex Snaps
*/
abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransactionalDataRegion>
extends AbstractEhcacheAccessStrategy<T> {
abstract class AbstractReadWriteEhcacheAccessStrategy<T
extends EhcacheTransactionalDataRegion>
extends AbstractEhcacheAccessStrategy<T> {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
AbstractReadWriteEhcacheAccessStrategy.class.getName()
);
private final UUID uuid = UUID.randomUUID();
private final AtomicLong nextLockId = new AtomicLong();
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
AbstractReadWriteEhcacheAccessStrategy.class.getName()
);
private final Comparator versionComparator;
private final UUID uuid = UUID.randomUUID();
private final AtomicLong nextLockId = new AtomicLong();
/**
* Creates a read/write cache access strategy around the given cache region.
*/
public AbstractReadWriteEhcacheAccessStrategy(T region, Settings settings) {
super( region, settings );
this.versionComparator = region.getCacheDataDescription().getVersionComparator();
}
private final Comparator versionComparator;
/**
* Returns <code>null</code> if the item is not readable. Locked items are not readable, nor are items created
* after the start of this transaction.
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long)
* @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#get(java.lang.Object, long)
*/
public final Object get(Object key, long txTimestamp) throws CacheException {
readLockIfNeeded( key );
try {
Lockable item = (Lockable) region.get( key );
/**
* Creates a read/write cache access strategy around the given cache region.
*/
public AbstractReadWriteEhcacheAccessStrategy(T region, Settings settings) {
super( region, settings );
this.versionComparator = region.getCacheDataDescription().getVersionComparator();
}
boolean readable = item != null && item.isReadable( txTimestamp );
if ( readable ) {
return item.getValue();
}
else {
return null;
}
}
finally {
readUnlockIfNeeded( key );
}
}
/**
* Returns <code>null</code> if the item is not readable. Locked items are not readable, nor are items created
* after the start of this transaction.
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long)
* @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#get(java.lang.Object, long)
*/
public final Object get(Object key, long txTimestamp) throws CacheException {
readLockIfNeeded( key );
try {
final Lockable item = (Lockable) region().get( key );
/**
* Returns <code>false</code> and fails to put the value if there is an existing un-writeable item mapped to this
* key.
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)
* @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)
*/
@Override
public final boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
region.writeLock( key );
try {
Lockable item = (Lockable) region.get( key );
boolean writeable = item == null || item.isWriteable( txTimestamp, version, versionComparator );
if ( writeable ) {
region.put( key, new Item( value, version, region.nextTimestamp() ) );
return true;
}
else {
return false;
}
}
finally {
region.writeUnlock( key );
}
}
final boolean readable = item != null && item.isReadable( txTimestamp );
if ( readable ) {
return item.getValue();
}
else {
return null;
}
}
finally {
readUnlockIfNeeded( key );
}
}
/**
* Soft-lock a cache item.
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
* @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
*/
public final SoftLock lockItem(Object key, Object version) throws CacheException {
region.writeLock( key );
try {
Lockable item = (Lockable) region.get( key );
long timeout = region.nextTimestamp() + region.getTimeout();
final Lock lock = ( item == null ) ? new Lock( timeout, uuid, nextLockId(), version ) : item.lock(
timeout,
uuid,
nextLockId()
);
region.put( key, lock );
return lock;
}
finally {
region.writeUnlock( key );
}
}
/**
* Returns <code>false</code> and fails to put the value if there is an existing un-writeable item mapped to this
* key.
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)
* @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)
*/
@Override
public final boolean putFromLoad(
Object key,
Object value,
long txTimestamp,
Object version,
boolean minimalPutOverride)
throws CacheException {
region().writeLock( key );
try {
final Lockable item = (Lockable) region().get( key );
final boolean writeable = item == null || item.isWriteable( txTimestamp, version, versionComparator );
if ( writeable ) {
region().put( key, new Item( value, version, region().nextTimestamp() ) );
return true;
}
else {
return false;
}
}
finally {
region().writeUnlock( key );
}
}
/**
* Soft-unlock a cache item.
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
* @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
*/
public final void unlockItem(Object key, SoftLock lock) throws CacheException {
region.writeLock( key );
try {
Lockable item = (Lockable) region.get( key );
/**
* Soft-lock a cache item.
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
* @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
*/
public final SoftLock lockItem(Object key, Object version) throws CacheException {
region().writeLock( key );
try {
final Lockable item = (Lockable) region().get( key );
final long timeout = region().nextTimestamp() + region().getTimeout();
final Lock lock = (item == null) ? new Lock( timeout, uuid, nextLockId(), version ) : item.lock(
timeout,
uuid,
nextLockId()
);
region().put( key, lock );
return lock;
}
finally {
region().writeUnlock( key );
}
}
if ( ( item != null ) && item.isUnlockable( lock ) ) {
decrementLock( key, (Lock) item );
}
else {
handleLockExpiry( key, item );
}
}
finally {
region.writeUnlock( key );
}
}
/**
* Soft-unlock a cache item.
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
* @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
*/
public final void unlockItem(Object key, SoftLock lock) throws CacheException {
region().writeLock( key );
try {
final Lockable item = (Lockable) region().get( key );
private long nextLockId() {
return nextLockId.getAndIncrement();
}
if ( (item != null) && item.isUnlockable( lock ) ) {
decrementLock( key, (Lock) item );
}
else {
handleLockExpiry( key, item );
}
}
finally {
region().writeUnlock( key );
}
}
/**
* Unlock and re-put the given key, lock combination.
*/
protected void decrementLock(Object key, Lock lock) {
lock.unlock( region.nextTimestamp() );
region.put( key, lock );
}
private long nextLockId() {
return nextLockId.getAndIncrement();
}
/**
* Handle the timeout of a previous lock mapped to this key
*/
protected void handleLockExpiry(Object key, Lockable lock) {
LOG.softLockedCacheExpired( region.getName(), key, lock == null ? "(null)" : lock.toString() );
/**
* Unlock and re-put the given key, lock combination.
*/
protected void decrementLock(Object key, Lock lock) {
lock.unlock( region().nextTimestamp() );
region().put( key, lock );
}
long ts = region.nextTimestamp() + region.getTimeout();
// create new lock that times out immediately
Lock newLock = new Lock( ts, uuid, nextLockId.getAndIncrement(), null );
newLock.unlock( ts );
region.put( key, newLock );
}
/**
* Handle the timeout of a previous lock mapped to this key
*/
protected void handleLockExpiry(Object key, Lockable lock) {
LOG.softLockedCacheExpired( region().getName(), key, lock == null ? "(null)" : lock.toString() );
/**
* Read lock the entry for the given key if internal cache locks will not provide correct exclusion.
*/
private void readLockIfNeeded(Object key) {
if ( region.locksAreIndependentOfCache() ) {
region.readLock( key );
}
}
final long ts = region().nextTimestamp() + region().getTimeout();
// create new lock that times out immediately
final Lock newLock = new Lock( ts, uuid, nextLockId.getAndIncrement(), null );
newLock.unlock( ts );
region().put( key, newLock );
}
/**
* Read unlock the entry for the given key if internal cache locks will not provide correct exclusion.
*/
private void readUnlockIfNeeded(Object key) {
if ( region.locksAreIndependentOfCache() ) {
region.readUnlock( key );
}
}
/**
* Read lock the entry for the given key if internal cache locks will not provide correct exclusion.
*/
private void readLockIfNeeded(Object key) {
if ( region().locksAreIndependentOfCache() ) {
region().readLock( key );
}
}
/**
* Interface type implemented by all wrapper objects in the cache.
*/
protected static interface Lockable {
/**
* Read unlock the entry for the given key if internal cache locks will not provide correct exclusion.
*/
private void readUnlockIfNeeded(Object key) {
if ( region().locksAreIndependentOfCache() ) {
region().readUnlock( key );
}
}
/**
* Returns <code>true</code> if the enclosed value can be read by a transaction started at the given time.
*/
public boolean isReadable(long txTimestamp);
/**
* Interface type implemented by all wrapper objects in the cache.
*/
protected static interface Lockable {
/**
* Returns <code>true</code> if the enclosed value can be replaced with one of the given version by a
* transaction started at the given time.
*/
public boolean isWriteable(long txTimestamp, Object version, Comparator versionComparator);
/**
* Returns <code>true</code> if the enclosed value can be read by a transaction started at the given time.
*/
public boolean isReadable(long txTimestamp);
/**
* Returns the enclosed value.
*/
public Object getValue();
/**
* Returns <code>true</code> if the enclosed value can be replaced with one of the given version by a
* transaction started at the given time.
*/
public boolean isWriteable(long txTimestamp, Object version, Comparator versionComparator);
/**
* Returns <code>true</code> if the given lock can be unlocked using the given SoftLock instance as a handle.
*/
public boolean isUnlockable(SoftLock lock);
/**
* Returns the enclosed value.
*/
public Object getValue();
/**
* Locks this entry, stamping it with the UUID and lockId given, with the lock timeout occuring at the specified
* time. The returned Lock object can be used to unlock the entry in the future.
*/
public Lock lock(long timeout, UUID uuid, long lockId);
}
/**
* Returns <code>true</code> if the given lock can be unlocked using the given SoftLock instance as a handle.
*/
public boolean isUnlockable(SoftLock lock);
/**
* Wrapper type representing unlocked items.
*/
protected final static class Item implements Serializable, Lockable {
/**
* Locks this entry, stamping it with the UUID and lockId given, with the lock timeout occuring at the specified
* time. The returned Lock object can be used to unlock the entry in the future.
*/
public Lock lock(long timeout, UUID uuid, long lockId);
}
private static final long serialVersionUID = 1L;
private final Object value;
private final Object version;
private final long timestamp;
/**
* Wrapper type representing unlocked items.
*/
protected static final class Item implements Serializable, Lockable {
private static final long serialVersionUID = 1L;
private final Object value;
private final Object version;
private final long timestamp;
/**
* Creates an unlocked item wrapping the given value with a version and creation timestamp.
*/
Item(Object value, Object version, long timestamp) {
this.value = value;
this.version = version;
this.timestamp = timestamp;
}
/**
* Creates an unlocked item wrapping the given value with a version and creation timestamp.
*/
Item(Object value, Object version, long timestamp) {
this.value = value;
this.version = version;
this.timestamp = timestamp;
}
/**
* {@inheritDoc}
*/
public boolean isReadable(long txTimestamp) {
return txTimestamp > timestamp;
}
@Override
public boolean isReadable(long txTimestamp) {
return txTimestamp > timestamp;
}
/**
* {@inheritDoc}
*/
public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) {
return version != null && versionComparator.compare( version, newVersion ) < 0;
}
@Override
@SuppressWarnings("unchecked")
public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) {
return version != null && versionComparator.compare( version, newVersion ) < 0;
}
/**
* {@inheritDoc}
*/
public Object getValue() {
return value;
}
@Override
public Object getValue() {
return value;
}
/**
* {@inheritDoc}
*/
public boolean isUnlockable(SoftLock lock) {
return false;
}
@Override
public boolean isUnlockable(SoftLock lock) {
return false;
}
/**
* {@inheritDoc}
*/
public Lock lock(long timeout, UUID uuid, long lockId) {
return new Lock( timeout, uuid, lockId, version );
}
}
@Override
public Lock lock(long timeout, UUID uuid, long lockId) {
return new Lock( timeout, uuid, lockId, version );
}
}
/**
* Wrapper type representing locked items.
*/
protected final static class Lock implements Serializable, Lockable, SoftLock {
/**
* Wrapper type representing locked items.
*/
protected static final class Lock implements Serializable, Lockable, SoftLock {
private static final long serialVersionUID = 2L;
private static final long serialVersionUID = 2L;
private final UUID sourceUuid;
private final long lockId;
private final Object version;
private final UUID sourceUuid;
private final long lockId;
private final Object version;
private long timeout;
private boolean concurrent;
private int multiplicity = 1;
private long unlockTimestamp;
private long timeout;
private boolean concurrent;
private int multiplicity = 1;
private long unlockTimestamp;
/**
* Creates a locked item with the given identifiers and object version.
*/
Lock(long timeout, UUID sourceUuid, long lockId, Object version) {
this.timeout = timeout;
this.lockId = lockId;
this.version = version;
this.sourceUuid = sourceUuid;
}
/**
* Creates a locked item with the given identifiers and object version.
*/
Lock(long timeout, UUID sourceUuid, long lockId, Object version) {
this.timeout = timeout;
this.lockId = lockId;
this.version = version;
this.sourceUuid = sourceUuid;
}
@Override
public boolean isReadable(long txTimestamp) {
return false;
}
/**
* {@inheritDoc}
*/
public boolean isReadable(long txTimestamp) {
return false;
}
@Override
@SuppressWarnings({"SimplifiableIfStatement", "unchecked"})
public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) {
if ( txTimestamp > timeout ) {
// if timedout then allow write
return true;
}
if ( multiplicity > 0 ) {
// if still locked then disallow write
return false;
}
return version == null
? txTimestamp > unlockTimestamp
: versionComparator.compare( version, newVersion ) < 0;
}
/**
* {@inheritDoc}
*/
public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) {
if ( txTimestamp > timeout ) {
// if timedout then allow write
return true;
}
if ( multiplicity > 0 ) {
// if still locked then disallow write
return false;
}
return version == null ? txTimestamp > unlockTimestamp : versionComparator.compare(
version,
newVersion
) < 0;
}
@Override
public Object getValue() {
return null;
}
/**
* {@inheritDoc}
*/
public Object getValue() {
return null;
}
@Override
public boolean isUnlockable(SoftLock lock) {
return equals( lock );
}
/**
* {@inheritDoc}
*/
public boolean isUnlockable(SoftLock lock) {
return equals( lock );
}
@Override
@SuppressWarnings("SimplifiableIfStatement")
public boolean equals(Object o) {
if ( o == this ) {
return true;
}
else if ( o instanceof Lock ) {
return (lockId == ((Lock) o).lockId) && sourceUuid.equals( ((Lock) o).sourceUuid );
}
else {
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
if ( o == this ) {
return true;
}
else if ( o instanceof Lock ) {
return ( lockId == ( (Lock) o ).lockId ) && sourceUuid.equals( ( (Lock) o ).sourceUuid );
}
else {
return false;
}
}
@Override
public int hashCode() {
final int hash = (sourceUuid != null ? sourceUuid.hashCode() : 0);
int temp = (int) lockId;
for ( int i = 1; i < Long.SIZE / Integer.SIZE; i++ ) {
temp ^= (lockId >>> (i * Integer.SIZE));
}
return hash + temp;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int hash = ( sourceUuid != null ? sourceUuid.hashCode() : 0 );
int temp = (int) lockId;
for ( int i = 1; i < Long.SIZE / Integer.SIZE; i++ ) {
temp ^= ( lockId >>> ( i * Integer.SIZE ) );
}
return hash + temp;
}
/**
* Returns true if this Lock has been concurrently locked by more than one transaction.
*/
public boolean wasLockedConcurrently() {
return concurrent;
}
/**
* Returns true if this Lock has been concurrently locked by more than one transaction.
*/
public boolean wasLockedConcurrently() {
return concurrent;
}
@Override
public Lock lock(long timeout, UUID uuid, long lockId) {
concurrent = true;
multiplicity++;
this.timeout = timeout;
return this;
}
/**
* {@inheritDoc}
*/
public Lock lock(long timeout, UUID uuid, long lockId) {
concurrent = true;
multiplicity++;
this.timeout = timeout;
return this;
}
/**
* Unlocks this Lock, and timestamps the unlock event.
*/
public void unlock(long timestamp) {
if ( --multiplicity == 0 ) {
unlockTimestamp = timestamp;
}
}
/**
* Unlocks this Lock, and timestamps the unlock event.
*/
public void unlock(long timestamp) {
if ( --multiplicity == 0 ) {
unlockTimestamp = timestamp;
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder( "Lock Source-UUID:" + sourceUuid + " Lock-ID:" + lockId );
return sb.toString();
}
}
@Override
public String toString() {
return "Lock Source-UUID:" + sourceUuid + " Lock-ID:" + lockId;
}
}
}

View File

@ -32,42 +32,46 @@ import org.hibernate.cache.spi.access.EntityRegionAccessStrategy;
import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy;
/**
* Factory to create {@link EntityRegionAccessStrategy}
* Factory to create {@link org.hibernate.cache.spi.access.RegionAccessStrategy} instance
*
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
public interface EhcacheAccessStrategyFactory {
/**
* Create {@link EntityRegionAccessStrategy} for the input {@link EhcacheEntityRegion} and {@link AccessType}
*
* @param entityRegion
* @param accessType
* @param entityRegion The entity region being wrapped
* @param accessType The type of access to allow to the region
*
* @return the created {@link EntityRegionAccessStrategy}
*/
public EntityRegionAccessStrategy createEntityRegionAccessStrategy(EhcacheEntityRegion entityRegion, AccessType accessType);
public EntityRegionAccessStrategy createEntityRegionAccessStrategy(
EhcacheEntityRegion entityRegion,
AccessType accessType);
/**
* Create {@link CollectionRegionAccessStrategy} for the input {@link org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion} and {@link AccessType}
* Create {@link CollectionRegionAccessStrategy} for the input {@link EhcacheCollectionRegion} and {@link AccessType}
*
* @param collectionRegion
* @param accessType
* @param collectionRegion The collection region being wrapped
* @param accessType The type of access to allow to the region
*
* @return the created {@link CollectionRegionAccessStrategy}
*/
public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(EhcacheCollectionRegion collectionRegion,
AccessType accessType);
/**
* Create {@link NaturalIdRegionAccessStrategy} for the input {@link org.hibernate.cache.ehcache.internal.regions.EhcacheNaturalIdRegion} and {@link AccessType}
*
* @param naturalIdRegion
* @param accessType
*
* @return the created {@link NaturalIdRegionAccessStrategy}
*/
public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion naturalIdRegion,
AccessType accessType);
public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(
EhcacheCollectionRegion collectionRegion,
AccessType accessType);
/**
* Create {@link NaturalIdRegionAccessStrategy} for the input {@link EhcacheNaturalIdRegion} and {@link AccessType}
*
* @param naturalIdRegion The natural-id region being wrapped
* @param accessType The type of access to allow to the region
*
* @return the created {@link NaturalIdRegionAccessStrategy}
*/
public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(
EhcacheNaturalIdRegion naturalIdRegion,
AccessType accessType);
}

View File

@ -42,108 +42,108 @@ import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy;
*/
public class EhcacheAccessStrategyFactoryImpl implements EhcacheAccessStrategyFactory {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
EhcacheAccessStrategyFactoryImpl.class.getName()
);
/**
* {@inheritDoc}
*/
public EntityRegionAccessStrategy createEntityRegionAccessStrategy(EhcacheEntityRegion entityRegion, AccessType accessType) {
switch ( accessType ) {
case READ_ONLY:
if ( entityRegion.getCacheDataDescription().isMutable() ) {
LOG.readOnlyCacheConfiguredForMutableEntity( entityRegion.getName() );
}
return new ReadOnlyEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() );
case READ_WRITE:
return new ReadWriteEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() );
case NONSTRICT_READ_WRITE:
return new NonStrictReadWriteEhcacheEntityRegionAccessStrategy(
entityRegion,
entityRegion.getSettings()
);
case TRANSACTIONAL:
return new TransactionalEhcacheEntityRegionAccessStrategy(
entityRegion,
entityRegion.getEhcache(),
entityRegion.getSettings()
);
default:
throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
}
}
/**
* {@inheritDoc}
*/
public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(EhcacheCollectionRegion collectionRegion,
AccessType accessType) {
switch ( accessType ) {
case READ_ONLY:
if ( collectionRegion.getCacheDataDescription().isMutable() ) {
LOG.readOnlyCacheConfiguredForMutableEntity( collectionRegion.getName() );
}
return new ReadOnlyEhcacheCollectionRegionAccessStrategy(
collectionRegion,
collectionRegion.getSettings()
);
case READ_WRITE:
return new ReadWriteEhcacheCollectionRegionAccessStrategy(
collectionRegion,
collectionRegion.getSettings()
);
case NONSTRICT_READ_WRITE:
return new NonStrictReadWriteEhcacheCollectionRegionAccessStrategy(
collectionRegion,
collectionRegion.getSettings()
);
case TRANSACTIONAL:
return new TransactionalEhcacheCollectionRegionAccessStrategy(
collectionRegion, collectionRegion.getEhcache(), collectionRegion
.getSettings()
);
default:
throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
}
}
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
EhcacheAccessStrategyFactoryImpl.class.getName()
);
@Override
public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion naturalIdRegion,
public EntityRegionAccessStrategy createEntityRegionAccessStrategy(
EhcacheEntityRegion entityRegion,
AccessType accessType) {
switch ( accessType ) {
case READ_ONLY:
if ( naturalIdRegion.getCacheDataDescription().isMutable() ) {
LOG.readOnlyCacheConfiguredForMutableEntity( naturalIdRegion.getName() );
}
return new ReadOnlyEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion,
naturalIdRegion.getSettings()
);
case READ_WRITE:
return new ReadWriteEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion,
naturalIdRegion.getSettings()
);
case NONSTRICT_READ_WRITE:
return new NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion,
naturalIdRegion.getSettings()
);
case TRANSACTIONAL:
return new TransactionalEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion, naturalIdRegion.getEhcache(), naturalIdRegion
.getSettings()
);
default:
throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
}
switch ( accessType ) {
case READ_ONLY:
if ( entityRegion.getCacheDataDescription().isMutable() ) {
LOG.readOnlyCacheConfiguredForMutableEntity( entityRegion.getName() );
}
return new ReadOnlyEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() );
case READ_WRITE:
return new ReadWriteEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() );
case NONSTRICT_READ_WRITE:
return new NonStrictReadWriteEhcacheEntityRegionAccessStrategy(
entityRegion,
entityRegion.getSettings()
);
case TRANSACTIONAL:
return new TransactionalEhcacheEntityRegionAccessStrategy(
entityRegion,
entityRegion.getEhcache(),
entityRegion.getSettings()
);
default:
throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
}
}
@Override
public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(
EhcacheCollectionRegion collectionRegion,
AccessType accessType) {
switch ( accessType ) {
case READ_ONLY:
if ( collectionRegion.getCacheDataDescription().isMutable() ) {
LOG.readOnlyCacheConfiguredForMutableEntity( collectionRegion.getName() );
}
return new ReadOnlyEhcacheCollectionRegionAccessStrategy(
collectionRegion,
collectionRegion.getSettings()
);
case READ_WRITE:
return new ReadWriteEhcacheCollectionRegionAccessStrategy(
collectionRegion,
collectionRegion.getSettings()
);
case NONSTRICT_READ_WRITE:
return new NonStrictReadWriteEhcacheCollectionRegionAccessStrategy(
collectionRegion,
collectionRegion.getSettings()
);
case TRANSACTIONAL:
return new TransactionalEhcacheCollectionRegionAccessStrategy(
collectionRegion, collectionRegion.getEhcache(), collectionRegion
.getSettings()
);
default:
throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
}
}
@Override
public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(
EhcacheNaturalIdRegion naturalIdRegion,
AccessType accessType) {
switch ( accessType ) {
case READ_ONLY:
if ( naturalIdRegion.getCacheDataDescription().isMutable() ) {
LOG.readOnlyCacheConfiguredForMutableEntity( naturalIdRegion.getName() );
}
return new ReadOnlyEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion,
naturalIdRegion.getSettings()
);
case READ_WRITE:
return new ReadWriteEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion,
naturalIdRegion.getSettings()
);
case NONSTRICT_READ_WRITE:
return new NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion,
naturalIdRegion.getSettings()
);
case TRANSACTIONAL:
return new TransactionalEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion, naturalIdRegion.getEhcache(), naturalIdRegion
.getSettings()
);
default:
throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
}
}
}

View File

@ -42,58 +42,58 @@ public class NonStrictReadWriteEhcacheCollectionRegionAccessStrategy
/**
* Create a non-strict read/write access strategy accessing the given collection region.
*
* @param region The wrapped region
* @param settings The Hibernate settings
*/
public NonStrictReadWriteEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Settings settings) {
super( region, settings );
}
/**
* {@inheritDoc}
*/
@Override
public CollectionRegion getRegion() {
return region;
return region();
}
/**
* {@inheritDoc}
*/
@Override
public Object get(Object key, long txTimestamp) throws CacheException {
return region.get( key );
return region().get( key );
}
/**
* {@inheritDoc}
*/
@Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
if ( minimalPutOverride && region.contains( key ) ) {
if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
region.put( key, value );
region().put( key, value );
return true;
}
}
/**
* {@inheritDoc}
* <p/>
* Since this is a non-strict read/write strategy item locking is not used.
*/
@Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
/**
* {@inheritDoc}
* <p/>
* Since this is a non-strict read/write strategy item locking is not used.
*/
@Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
region.remove( key );
region().remove( key );
}
/**
* {@inheritDoc}
*/
@Override
public void remove(Object key) throws CacheException {
region.remove( key );
region().remove( key );
}
}

View File

@ -42,90 +42,97 @@ public class NonStrictReadWriteEhcacheEntityRegionAccessStrategy
/**
* Create a non-strict read/write access strategy accessing the given collection region.
*
* @param region The wrapped region
* @param settings The Hibernate settings
*/
public NonStrictReadWriteEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Settings settings) {
super( region, settings );
}
/**
* {@inheritDoc}
*/
@Override
public EntityRegion getRegion() {
return region;
return super.region();
}
/**
* {@inheritDoc}
*/
@Override
public Object get(Object key, long txTimestamp) throws CacheException {
return region.get( key );
return region().get( key );
}
/**
* {@inheritDoc}
*/
@Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
if ( minimalPutOverride && region.contains( key ) ) {
if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
region.put( key, value );
region().put( key, value );
return true;
}
}
/**
* {@inheritDoc}
* <p/>
* Since this is a non-strict read/write strategy item locking is not used.
*/
@Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
/**
* {@inheritDoc}
* <p/>
* Since this is a non-strict read/write strategy item locking is not used.
*/
@Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
region.remove( key );
region().remove( key );
}
/**
* {@inheritDoc}
* <p/>
* Returns <code>false</code> since this is an asynchronous cache access strategy.
*/
@Override
public boolean insert(Object key, Object value, Object version) throws CacheException {
return false;
}
/**
* {@inheritDoc}
* <p/>
* Returns <code>false</code> since this is a non-strict read/write cache access strategy
*/
@Override
public boolean afterInsert(Object key, Object value, Object version) throws CacheException {
return false;
}
/**
* {@inheritDoc}
* <p/>
* Removes the entry since this is a non-strict read/write cache strategy.
*/
@Override
public boolean update(Object key, Object value, Object currentVersion, Object previousVersion)
throws CacheException {
remove( key );
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock)
throws CacheException {
unlockItem( key, lock );
return false;
}
/**
* {@inheritDoc}
*/
@Override
public void remove(Object key) throws CacheException {
region.remove( key );
region().remove( key );
}
}

View File

@ -42,88 +42,95 @@ public class NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy
/**
* Create a non-strict read/write access strategy accessing the given NaturalId region.
*
* @param region The wrapped region
* @param settings The Hibernate settings
*/
public NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Settings settings) {
super( region, settings );
}
/**
* {@inheritDoc}
*/
@Override
public NaturalIdRegion getRegion() {
return region;
return region();
}
/**
* {@inheritDoc}
*/
@Override
public Object get(Object key, long txTimestamp) throws CacheException {
return region.get( key );
return region().get( key );
}
/**
* {@inheritDoc}
*/
@Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
if ( minimalPutOverride && region.contains( key ) ) {
if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
region.put( key, value );
region().put( key, value );
return true;
}
}
/**
* {@inheritDoc}
* <p/>
* Since this is a non-strict read/write strategy item locking is not used.
*/
@Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
/**
* {@inheritDoc}
* <p/>
* Since this is a non-strict read/write strategy item locking is not used.
*/
@Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
region.remove( key );
region().remove( key );
}
/**
* {@inheritDoc}
* <p/>
* Returns <code>false</code> since this is an asynchronous cache access strategy.
*/
public boolean insert(Object key, Object value ) throws CacheException {
return false;
}
/**
* Returns <code>false</code> since this is a non-strict read/write cache access strategy
*/
public boolean afterInsert(Object key, Object value ) throws CacheException {
return false;
}
/**
* Removes the entry since this is a non-strict read/write cache strategy.
*/
public boolean update(Object key, Object value ) throws CacheException {
remove( key );
@Override
public boolean insert(Object key, Object value) throws CacheException {
return false;
}
/**
* {@inheritDoc}
* <p/>
* Returns <code>false</code> since this is a non-strict read/write cache access strategy
*/
@Override
public boolean afterInsert(Object key, Object value) throws CacheException {
return false;
}
/**
* {@inheritDoc}
* <p/>
* Removes the entry since this is a non-strict read/write cache strategy.
*/
@Override
public boolean update(Object key, Object value) throws CacheException {
remove( key );
return false;
}
@Override
public boolean afterUpdate(Object key, Object value, SoftLock lock) throws CacheException {
unlockItem( key, lock );
return false;
}
/**
* {@inheritDoc}
*/
@Override
public void remove(Object key) throws CacheException {
region.remove( key );
region().remove( key );
}
}

View File

@ -42,46 +42,47 @@ public class ReadOnlyEhcacheCollectionRegionAccessStrategy
/**
* Create a read-only access strategy accessing the given collection region.
*
* @param region The wrapped region
* @param settings The Hibernate settings
*/
public ReadOnlyEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Settings settings) {
super( region, settings );
}
/**
* {@inheritDoc}
*/
@Override
public CollectionRegion getRegion() {
return region;
return region();
}
/**
* {@inheritDoc}
*/
@Override
public Object get(Object key, long txTimestamp) throws CacheException {
return region.get( key );
return region().get( key );
}
/**
* {@inheritDoc}
*/
@Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
if ( minimalPutOverride && region.contains( key ) ) {
if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
region.put( key, value );
region().put( key, value );
return true;
}
}
@Override
public SoftLock lockItem(Object key, Object version) throws UnsupportedOperationException {
return null;
}
/**
* {@inheritDoc}
* <p/>
* A no-op since this cache is read-only
*/
@Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
}
}

View File

@ -30,10 +30,6 @@ import org.hibernate.cache.spi.access.EntityRegionAccessStrategy;
import org.hibernate.cache.spi.access.SoftLock;
import org.hibernate.cfg.Settings;
/**
* @author Alex Snaps
*/
/**
* Ehcache specific read-only entity region access strategy
*
@ -45,6 +41,9 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc
/**
* Create a read-only access strategy accessing the given entity region.
*
* @param region The wrapped region
* @param settings The Hibernate settings
*/
public ReadOnlyEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Settings settings) {
super( region, settings );
@ -54,14 +53,14 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc
* {@inheritDoc}
*/
public EntityRegion getRegion() {
return region;
return region();
}
/**
* {@inheritDoc}
*/
public Object get(Object key, long txTimestamp) throws CacheException {
return region.get( key );
return region().get( key );
}
/**
@ -69,11 +68,11 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc
*/
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
if ( minimalPutOverride && region.contains( key ) ) {
if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
region.put( key, value );
region().put( key, value );
return true;
}
}
@ -100,7 +99,7 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc
* {@inheritDoc}
*/
public boolean afterInsert(Object key, Object value, Object version) throws CacheException {
region.put( key, value );
region().put( key, value );
return true;
}
@ -123,4 +122,4 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc
throws UnsupportedOperationException {
throw new UnsupportedOperationException( "Can't write to a readonly object" );
}
}
}

View File

@ -42,79 +42,87 @@ public class ReadOnlyEhcacheNaturalIdRegionAccessStrategy
/**
* Create a read-only access strategy accessing the given NaturalId region.
*
* @param region THe wrapped region
* @param settings The Hibermate settings
*/
public ReadOnlyEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Settings settings) {
super( region, settings );
}
/**
* {@inheritDoc}
*/
@Override
public NaturalIdRegion getRegion() {
return region;
return region();
}
/**
* {@inheritDoc}
*/
@Override
public Object get(Object key, long txTimestamp) throws CacheException {
return region.get( key );
return region().get( key );
}
/**
* {@inheritDoc}
*/
@Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
if ( minimalPutOverride && region.contains( key ) ) {
if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
region.put( key, value );
region().put( key, value );
return true;
}
}
@Override
public SoftLock lockItem(Object key, Object version) throws UnsupportedOperationException {
return null;
}
/**
* {@inheritDoc}
* <p/>
* A no-op since this cache is read-only
*/
@Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
region.remove( key );
}
/**
* This cache is asynchronous hence a no-op
*/
public boolean insert(Object key, Object value ) throws CacheException {
return false;
region().remove( key );
}
/**
* {@inheritDoc}
* <p/>
* This cache is asynchronous hence a no-op
*/
public boolean afterInsert(Object key, Object value ) throws CacheException {
region.put( key, value );
@Override
public boolean insert(Object key, Object value) throws CacheException {
return false;
}
@Override
public boolean afterInsert(Object key, Object value) throws CacheException {
region().put( key, value );
return true;
}
/**
* {@inheritDoc}
* <p/>
* Throws UnsupportedOperationException since this cache is read-only
*
* @throws UnsupportedOperationException always
*/
public boolean update(Object key, Object value ) throws UnsupportedOperationException {
@Override
public boolean update(Object key, Object value) throws UnsupportedOperationException {
throw new UnsupportedOperationException( "Can't write to a readonly object" );
}
/**
* {@inheritDoc}
* <p/>
* Throws UnsupportedOperationException since this cache is read-only
*
* @throws UnsupportedOperationException always
*/
@Override
public boolean afterUpdate(Object key, Object value, SoftLock lock) throws UnsupportedOperationException {
throw new UnsupportedOperationException( "Can't write to a readonly object" );
}

View File

@ -40,15 +40,16 @@ public class ReadWriteEhcacheCollectionRegionAccessStrategy
/**
* Create a read/write access strategy accessing the given collection region.
*
* @param region The wrapped region
* @param settings The Hibernate settings
*/
public ReadWriteEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Settings settings) {
super( region, settings );
}
/**
* {@inheritDoc}
*/
@Override
public CollectionRegion getRegion() {
return region;
return region();
}
}
}

View File

@ -42,21 +42,25 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
/**
* Create a read/write access strategy accessing the given entity region.
*
* @param region The wrapped region
* @param settings The Hibernate settings
*/
public ReadWriteEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Settings settings) {
super( region, settings );
}
/**
* {@inheritDoc}
*/
@Override
public EntityRegion getRegion() {
return region;
return region();
}
/**
* {@inheritDoc}
* <p/>
* A no-op since this is an asynchronous cache access strategy.
*/
@Override
public boolean insert(Object key, Object value, Object version) throws CacheException {
return false;
}
@ -66,12 +70,13 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
* <p/>
* Inserts will only succeed if there is no existing value mapped to this key.
*/
@Override
public boolean afterInsert(Object key, Object value, Object version) throws CacheException {
region.writeLock( key );
region().writeLock( key );
try {
Lockable item = (Lockable) region.get( key );
final Lockable item = (Lockable) region().get( key );
if ( item == null ) {
region.put( key, new Item( value, version, region.nextTimestamp() ) );
region().put( key, new Item( value, version, region().nextTimestamp() ) );
return true;
}
else {
@ -79,13 +84,16 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
}
}
finally {
region.writeUnlock( key );
region().writeUnlock( key );
}
}
/**
* {@inheritDoc}
* <p/>
* A no-op since this is an asynchronous cache access strategy.
*/
@Override
public boolean update(Object key, Object value, Object currentVersion, Object previousVersion)
throws CacheException {
return false;
@ -98,12 +106,13 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
* duration of this transaction. It is important to also note that updates will fail if the soft-lock expired during
* the course of this transaction.
*/
@Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock)
throws CacheException {
//what should we do with previousVersion here?
region.writeLock( key );
region().writeLock( key );
try {
Lockable item = (Lockable) region.get( key );
final Lockable item = (Lockable) region().get( key );
if ( item != null && item.isUnlockable( lock ) ) {
Lock lockItem = (Lock) item;
@ -112,7 +121,7 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
return false;
}
else {
region.put( key, new Item( value, currentVersion, region.nextTimestamp() ) );
region().put( key, new Item( value, currentVersion, region().nextTimestamp() ) );
return true;
}
}
@ -122,7 +131,7 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
}
}
finally {
region.writeUnlock( key );
region().writeUnlock( key );
}
}
}

View File

@ -42,22 +42,26 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
/**
* Create a read/write access strategy accessing the given NaturalId region.
*
* @param region The wrapped region
* @param settings The Hibernate settings
*/
public ReadWriteEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Settings settings) {
super( region, settings );
}
/**
* {@inheritDoc}
*/
@Override
public NaturalIdRegion getRegion() {
return region;
return region();
}
/**
* {@inheritDoc}
* <p/>
* A no-op since this is an asynchronous cache access strategy.
*/
public boolean insert(Object key, Object value ) throws CacheException {
@Override
public boolean insert(Object key, Object value) throws CacheException {
return false;
}
@ -66,12 +70,13 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
* <p/>
* Inserts will only succeed if there is no existing value mapped to this key.
*/
public boolean afterInsert(Object key, Object value ) throws CacheException {
region.writeLock( key );
@Override
public boolean afterInsert(Object key, Object value) throws CacheException {
region().writeLock( key );
try {
Lockable item = (Lockable) region.get( key );
final Lockable item = (Lockable) region().get( key );
if ( item == null ) {
region.put( key, new Item( value, null, region.nextTimestamp() ) );
region().put( key, new Item( value, null, region().nextTimestamp() ) );
return true;
}
else {
@ -79,15 +84,17 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
}
}
finally {
region.writeUnlock( key );
region().writeUnlock( key );
}
}
/**
* {@inheritDoc}
* <p/>
* A no-op since this is an asynchronous cache access strategy.
*/
public boolean update(Object key, Object value )
throws CacheException {
@Override
public boolean update(Object key, Object value) throws CacheException {
return false;
}
@ -98,20 +105,21 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
* duration of this transaction. It is important to also note that updates will fail if the soft-lock expired during
* the course of this transaction.
*/
@Override
public boolean afterUpdate(Object key, Object value, SoftLock lock) throws CacheException {
//what should we do with previousVersion here?
region.writeLock( key );
region().writeLock( key );
try {
Lockable item = (Lockable) region.get( key );
final Lockable item = (Lockable) region().get( key );
if ( item != null && item.isUnlockable( lock ) ) {
Lock lockItem = (Lock) item;
final Lock lockItem = (Lock) item;
if ( lockItem.wasLockedConcurrently() ) {
decrementLock( key, lockItem );
return false;
}
else {
region.put( key, new Item( value, null, region.nextTimestamp() ) );
region().put( key, new Item( value, null, region().nextTimestamp() ) );
return true;
}
}
@ -121,7 +129,7 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
}
}
finally {
region.writeUnlock( key );
region().writeUnlock( key );
}
}
}
}

View File

@ -53,44 +53,42 @@ public class TransactionalEhcacheCollectionRegionAccessStrategy
* @param ehcache the cache.
* @param settings the Hibernate settings.
*/
public TransactionalEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Ehcache ehcache, Settings settings) {
public TransactionalEhcacheCollectionRegionAccessStrategy(
EhcacheCollectionRegion region,
Ehcache ehcache,
Settings settings) {
super( region, settings );
this.ehcache = ehcache;
}
/**
* {@inheritDoc}
*/
@Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
Element element = ehcache.get( key );
final Element element = ehcache.get( key );
return element == null ? null : element.getObjectValue();
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
/**
* {@inheritDoc}
*/
@Override
public CollectionRegion getRegion() {
return region;
return region();
}
/**
* {@inheritDoc}
*/
@Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
/**
* {@inheritDoc}
*/
public boolean putFromLoad(Object key, Object value, long txTimestamp,
Object version, boolean minimalPutOverride) throws CacheException {
@Override
public boolean putFromLoad(
Object key,
Object value,
long txTimestamp,
Object version,
boolean minimalPutOverride) throws CacheException {
try {
if ( minimalPutOverride && ehcache.get( key ) != null ) {
return false;
@ -99,27 +97,22 @@ public class TransactionalEhcacheCollectionRegionAccessStrategy
ehcache.put( new Element( key, value ) );
return true;
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
/**
* {@inheritDoc}
*/
@Override
public void remove(Object key) throws CacheException {
try {
ehcache.remove( key );
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
/**
* {@inheritDoc}
*/
@Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
// no-op
}

View File

@ -52,48 +52,41 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca
* @param ehcache the cache.
* @param settings the Hibernate settings.
*/
public TransactionalEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Ehcache ehcache, Settings settings) {
public TransactionalEhcacheEntityRegionAccessStrategy(
EhcacheEntityRegion region,
Ehcache ehcache,
Settings settings) {
super( region, settings );
this.ehcache = ehcache;
}
/**
* {@inheritDoc}
*/
@Override
public boolean afterInsert(Object key, Object value, Object version) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
Element element = ehcache.get( key );
final Element element = ehcache.get( key );
return element == null ? null : element.getObjectValue();
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
/**
* {@inheritDoc}
*/
@Override
public EntityRegion getRegion() {
return region;
return region();
}
/**
* {@inheritDoc}
*/
@Override
public boolean insert(Object key, Object value, Object version)
throws CacheException {
//OptimisticCache? versioning?
@ -101,23 +94,23 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca
ehcache.put( new Element( key, value ) );
return true;
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
/**
* {@inheritDoc}
*/
@Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
/**
* {@inheritDoc}
*/
public boolean putFromLoad(Object key, Object value, long txTimestamp,
Object version, boolean minimalPutOverride) throws CacheException {
@Override
public boolean putFromLoad(
Object key,
Object value,
long txTimestamp,
Object version,
boolean minimalPutOverride) throws CacheException {
try {
if ( minimalPutOverride && ehcache.get( key ) != null ) {
return false;
@ -126,41 +119,37 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca
ehcache.put( new Element( key, value ) );
return true;
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
/**
* {@inheritDoc}
*/
@Override
public void remove(Object key) throws CacheException {
try {
ehcache.remove( key );
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
/**
* {@inheritDoc}
*/
@Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
// no-op
}
/**
* {@inheritDoc}
*/
public boolean update(Object key, Object value, Object currentVersion,
Object previousVersion) throws CacheException {
@Override
public boolean update(
Object key,
Object value,
Object currentVersion,
Object previousVersion) throws CacheException {
try {
ehcache.put( new Element( key, value ) );
return true;
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}

View File

@ -53,72 +53,64 @@ public class TransactionalEhcacheNaturalIdRegionAccessStrategy
* @param ehcache the cache.
* @param settings the Hibernate settings.
*/
public TransactionalEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Ehcache ehcache, Settings settings) {
public TransactionalEhcacheNaturalIdRegionAccessStrategy(
EhcacheNaturalIdRegion region,
Ehcache ehcache,
Settings settings) {
super( region, settings );
this.ehcache = ehcache;
}
/**
* {@inheritDoc}
*/
public boolean afterInsert(Object key, Object value ) {
@Override
public boolean afterInsert(Object key, Object value) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean afterUpdate(Object key, Object value, SoftLock lock) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
Element element = ehcache.get( key );
final Element element = ehcache.get( key );
return element == null ? null : element.getObjectValue();
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
/**
* {@inheritDoc}
*/
@Override
public NaturalIdRegion getRegion() {
return region;
return region();
}
/**
* {@inheritDoc}
*/
public boolean insert(Object key, Object value ) throws CacheException {
@Override
public boolean insert(Object key, Object value) throws CacheException {
//OptimisticCache? versioning?
try {
ehcache.put( new Element( key, value ) );
return true;
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
/**
* {@inheritDoc}
*/
@Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
/**
* {@inheritDoc}
*/
public boolean putFromLoad(Object key, Object value, long txTimestamp,
Object version, boolean minimalPutOverride) throws CacheException {
@Override
public boolean putFromLoad(
Object key,
Object value,
long txTimestamp,
Object version,
boolean minimalPutOverride) throws CacheException {
try {
if ( minimalPutOverride && ehcache.get( key ) != null ) {
return false;
@ -127,40 +119,33 @@ public class TransactionalEhcacheNaturalIdRegionAccessStrategy
ehcache.put( new Element( key, value ) );
return true;
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
/**
* {@inheritDoc}
*/
@Override
public void remove(Object key) throws CacheException {
try {
ehcache.remove( key );
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
/**
* {@inheritDoc}
*/
@Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
// no-op
}
/**
* {@inheritDoc}
*/
public boolean update(Object key, Object value ) throws CacheException {
@Override
public boolean update(Object key, Object value) throws CacheException {
try {
ehcache.put( new Element( key, value ) );
return true;
}
catch ( net.sf.ehcache.CacheException e ) {
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}

View File

@ -0,0 +1,4 @@
/**
* Defines {@link org.hibernate.cache.spi.access.RegionAccessStrategy} support for the Ehcache integration
*/
package org.hibernate.cache.ehcache.internal.strategy;

View File

@ -0,0 +1,129 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.cache.ehcache.internal.util;
import java.net.URL;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.Configuration;
import net.sf.ehcache.config.ConfigurationFactory;
import net.sf.ehcache.config.NonstopConfiguration;
import net.sf.ehcache.config.TerracottaConfiguration;
import net.sf.ehcache.config.TerracottaConfiguration.ValueMode;
import net.sf.ehcache.config.TimeoutBehaviorConfiguration.TimeoutBehaviorType;
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.EhCacheMessageLogger;
/**
* Copy of Ehcache utils into Hibernate code base
*
* @author Chris Dennis
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
public final class HibernateEhcacheUtils {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
HibernateEhcacheUtils.class.getName()
);
private HibernateEhcacheUtils() {
}
/**
* Create a cache manager configuration from the supplied url, correcting it for Hibernate compatibility.
* <p/>
* Currently "correcting" for Hibernate compatibility means simply switching any identity based value modes
* to serialization.
*
* @param url The url to load the config from
*
* @return The Ehcache Configuration object
*/
public static Configuration loadAndCorrectConfiguration(URL url) {
final Configuration config = ConfigurationFactory.parseConfiguration( url );
if ( config.getDefaultCacheConfiguration().isTerracottaClustered() ) {
if ( ValueMode.IDENTITY
.equals( config.getDefaultCacheConfiguration().getTerracottaConfiguration().getValueMode() ) ) {
LOG.incompatibleCacheValueMode();
config.getDefaultCacheConfiguration()
.getTerracottaConfiguration()
.setValueMode( ValueMode.SERIALIZATION.name() );
}
setupHibernateTimeoutBehavior(
config.getDefaultCacheConfiguration()
.getTerracottaConfiguration()
.getNonstopConfiguration()
);
}
for ( CacheConfiguration cacheConfig : config.getCacheConfigurations().values() ) {
if ( cacheConfig.isTerracottaClustered() ) {
if ( ValueMode.IDENTITY.equals( cacheConfig.getTerracottaConfiguration().getValueMode() ) ) {
LOG.incompatibleCacheValueModePerCache( cacheConfig.getName() );
cacheConfig.getTerracottaConfiguration().setValueMode( ValueMode.SERIALIZATION.name() );
}
setupHibernateTimeoutBehavior( cacheConfig.getTerracottaConfiguration().getNonstopConfiguration() );
}
}
return config;
}
private static void setupHibernateTimeoutBehavior(NonstopConfiguration nonstopConfig) {
nonstopConfig.getTimeoutBehavior().setType( TimeoutBehaviorType.EXCEPTION.getTypeName() );
}
/**
* Validates that the supplied Ehcache instance is valid for use as a Hibernate cache.
*
* @param cache The cache instance
*
* @throws CacheException If any explicit settings on the cache are not validate
*/
public static void validateEhcache(Ehcache cache) throws CacheException {
final CacheConfiguration cacheConfig = cache.getCacheConfiguration();
if ( cacheConfig.isTerracottaClustered() ) {
final TerracottaConfiguration tcConfig = cacheConfig.getTerracottaConfiguration();
switch ( tcConfig.getValueMode() ) {
case IDENTITY: {
throw new CacheException(
"The clustered Hibernate cache " + cache.getName() + " is using IDENTITY value mode.\n"
+ "Identity value mode cannot be used with Hibernate cache regions."
);
}
case SERIALIZATION:
default: {
// this is the recommended valueMode
break;
}
}
}
}
}

View File

@ -1,116 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.cache.ehcache.internal.util;
import java.net.URL;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.Configuration;
import net.sf.ehcache.config.ConfigurationFactory;
import net.sf.ehcache.config.NonstopConfiguration;
import net.sf.ehcache.config.TerracottaConfiguration;
import net.sf.ehcache.config.TerracottaConfiguration.ValueMode;
import net.sf.ehcache.config.TimeoutBehaviorConfiguration.TimeoutBehaviorType;
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.EhCacheMessageLogger;
/**
* @author Chris Dennis
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
public final class HibernateUtil {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
HibernateUtil.class.getName()
);
private HibernateUtil() {
}
/**
* Create a cache manager configuration from the supplied url, correcting it for Hibernate compatibility.
* <p/>
* Currently correcting for Hibernate compatibility means simply switching any identity based value modes to serialization.
*/
public static Configuration loadAndCorrectConfiguration(URL url) {
Configuration config = ConfigurationFactory.parseConfiguration( url );
if ( config.getDefaultCacheConfiguration().isTerracottaClustered() ) {
if ( ValueMode.IDENTITY
.equals( config.getDefaultCacheConfiguration().getTerracottaConfiguration().getValueMode() ) ) {
LOG.incompatibleCacheValueMode();
config.getDefaultCacheConfiguration()
.getTerracottaConfiguration()
.setValueMode( ValueMode.SERIALIZATION.name() );
}
setupHibernateTimeoutBehavior(
config.getDefaultCacheConfiguration()
.getTerracottaConfiguration()
.getNonstopConfiguration()
);
}
for ( CacheConfiguration cacheConfig : config.getCacheConfigurations().values() ) {
if ( cacheConfig.isTerracottaClustered() ) {
if ( ValueMode.IDENTITY.equals( cacheConfig.getTerracottaConfiguration().getValueMode() ) ) {
LOG.incompatibleCacheValueModePerCache( cacheConfig.getName() );
cacheConfig.getTerracottaConfiguration().setValueMode( ValueMode.SERIALIZATION.name() );
}
setupHibernateTimeoutBehavior( cacheConfig.getTerracottaConfiguration().getNonstopConfiguration() );
}
}
return config;
}
private static void setupHibernateTimeoutBehavior(NonstopConfiguration nonstopConfig) {
nonstopConfig.getTimeoutBehavior().setType( TimeoutBehaviorType.EXCEPTION.getTypeName() );
}
/**
* Validates that the supplied Ehcache instance is valid for use as a Hibernate cache.
*/
public static void validateEhcache(Ehcache cache) throws CacheException {
CacheConfiguration cacheConfig = cache.getCacheConfiguration();
if ( cacheConfig.isTerracottaClustered() ) {
TerracottaConfiguration tcConfig = cacheConfig.getTerracottaConfiguration();
switch ( tcConfig.getValueMode() ) {
case IDENTITY:
throw new CacheException(
"The clustered Hibernate cache " + cache.getName() + " is using IDENTITY value mode.\n"
+ "Identity value mode cannot be used with Hibernate cache regions."
);
case SERIALIZATION:
default:
// this is the recommended valueMode
break;
}
}
}
}

View File

@ -0,0 +1,4 @@
/**
* Defines utilities used by the Ehcache integration
*/
package org.hibernate.cache.ehcache.internal.util;

View File

@ -24,9 +24,6 @@
package org.hibernate.cache.ehcache.management.impl;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
@ -36,64 +33,61 @@ import javax.management.NotificationEmitter;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.StandardMBean;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
/**
* Base MBean impl
*
* @author gkeim
*/
public abstract class BaseEmitterBean extends StandardMBean implements NotificationEmitter {
/**
* emitter
*/
protected final Emitter emitter = new Emitter();
/**
* sequenceNumber
*/
protected final AtomicLong sequenceNumber = new AtomicLong();
public abstract class AbstractEmitterBean extends StandardMBean implements NotificationEmitter {
private final Emitter emitter = new Emitter();
private final AtomicLong sequenceNumber = new AtomicLong();
private final List<NotificationListener> notificationListeners = new CopyOnWriteArrayList<NotificationListener>();
/**
* BaseEmitterBean
* Constructs a AbstractEmitterBean
*
* @param <T>
* @param mbeanInterface
* @param mbeanInterface The MBean contract
* @param <T> Not used as far as I can see
*
* @throws javax.management.NotCompliantMBeanException
* @throws javax.management.NotCompliantMBeanException thrown from JMX super ctor
*/
protected <T> BaseEmitterBean(Class<T> mbeanInterface) throws NotCompliantMBeanException {
protected <T> AbstractEmitterBean(Class<T> mbeanInterface) throws NotCompliantMBeanException {
super( mbeanInterface );
}
/**
* sendNotification
* Sends notification of an event
*
* @param eventType
* @param eventType The type of event
*/
public void sendNotification(String eventType) {
sendNotification( eventType, null, null );
}
/**
* sendNotification
* Sends notification of an event
*
* @param eventType
* @param data
* @param eventType The type of event
* @param data The event data
*/
public void sendNotification(String eventType, Object data) {
sendNotification( eventType, data, null );
}
/**
* sendNotification
* Sends notification of an event
*
* @param eventType
* @param data
* @param msg
* @param eventType The type of event
* @param data The event data
* @param msg A message
*/
public void sendNotification(String eventType, Object data, String msg) {
Notification notif = new Notification(
final Notification notification = new Notification(
eventType,
this,
sequenceNumber.incrementAndGet(),
@ -101,9 +95,9 @@ public abstract class BaseEmitterBean extends StandardMBean implements Notificat
msg
);
if ( data != null ) {
notif.setUserData( data );
notification.setUserData( data );
}
emitter.sendNotification( notif );
emitter.sendNotification( notification );
}
/**
@ -119,61 +113,42 @@ public abstract class BaseEmitterBean extends StandardMBean implements Notificat
*/
protected abstract void doDispose();
/**
* @author gkeim
*/
private class Emitter extends NotificationBroadcasterSupport {
/**
* @see javax.management.NotificationBroadcasterSupport#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
return BaseEmitterBean.this.getNotificationInfo();
return AbstractEmitterBean.this.getNotificationInfo();
}
}
/**
* @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener,
* javax.management.NotificationFilter, java.lang.Object)
*/
@Override
public void addNotificationListener(NotificationListener notif, NotificationFilter filter, Object callBack) {
emitter.addNotificationListener( notif, filter, callBack );
notificationListeners.add( notif );
}
/**
* remove all added notification listeners
*/
private void removeAllNotificationListeners() {
for ( NotificationListener listener : notificationListeners ) {
try {
emitter.removeNotificationListener( listener );
}
catch ( ListenerNotFoundException e ) {
catch (ListenerNotFoundException e) {
// ignore
}
}
notificationListeners.clear();
}
/**
* @see javax.management.NotificationBroadcaster#getNotificationInfo()
*/
@Override
public abstract MBeanNotificationInfo[] getNotificationInfo();
/**
* @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener)
*/
@Override
public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
emitter.removeNotificationListener( listener );
notificationListeners.remove( listener );
}
/**
* @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener,
* javax.management.NotificationFilter, java.lang.Object)
*/
@Override
public void removeNotificationListener(NotificationListener notif, NotificationFilter filter, Object callBack)
throws ListenerNotFoundException {
emitter.removeNotificationListener( notif, filter, callBack );

View File

@ -36,17 +36,17 @@ public class BeanUtils {
/**
* Return the named getter method on the bean or null if not found.
*
* @param bean
* @param propertyName
* @param bean The bean
* @param propertyName The property to get the getter for
*
* @return the named getter method
*/
private static Method getMethod(Object bean, String propertyName) {
StringBuilder sb = new StringBuilder( "get" ).append( Character.toUpperCase( propertyName.charAt( 0 ) ) );
final StringBuilder sb = new StringBuilder( "get" ).append( Character.toUpperCase( propertyName.charAt( 0 ) ) );
if ( propertyName.length() > 1 ) {
sb.append( propertyName.substring( 1 ) );
}
String getterName = sb.toString();
final String getterName = sb.toString();
for ( Method m : bean.getClass().getMethods() ) {
if ( getterName.equals( m.getName() ) && m.getParameterTypes().length == 0 ) {
return m;
@ -55,14 +55,6 @@ public class BeanUtils {
return null;
}
/**
* Return the named field on the bean or null if not found.
*
* @param bean
* @param propertyName
*
* @return the named field
*/
private static Field getField(Object bean, String propertyName) {
for ( Field f : bean.getClass().getDeclaredFields() ) {
if ( propertyName.equals( f.getName() ) ) {
@ -87,8 +79,8 @@ public class BeanUtils {
/**
* Retrieve a named bean property value.
*
* @param bean bean
* @param propertyName
* @param bean The bean instance
* @param propertyName The name of the property whose value to extract
*
* @return the property value
*/
@ -96,24 +88,24 @@ public class BeanUtils {
validateArgs( bean, propertyName );
// try getters first
Method getter = getMethod( bean, propertyName );
final Method getter = getMethod( bean, propertyName );
if ( getter != null ) {
try {
return getter.invoke( bean );
}
catch ( Exception e ) {
catch (Exception e) {
/**/
}
}
// then try fields
Field field = getField( bean, propertyName );
final Field field = getField( bean, propertyName );
if ( field != null ) {
try {
field.setAccessible( true );
return field.get( bean );
}
catch ( Exception e ) {
catch (Exception e) {
/**/
}
}
@ -124,22 +116,25 @@ public class BeanUtils {
/**
* Retrieve a Long bean property value.
*
* @param bean bean
* @param propertyName
* @param bean The bean instance
* @param propertyName The name of the property whose value to extract
*
* @return long value
*
* @throws NoSuchFieldException
* @throws NoSuchFieldException If the value is null (wow)
*/
public static long getLongBeanProperty(final Object bean, final String propertyName) throws NoSuchFieldException {
validateArgs( bean, propertyName );
Object o = getBeanProperty( bean, propertyName );
final Object o = getBeanProperty( bean, propertyName );
if ( o == null ) {
throw new NoSuchFieldException( propertyName );
}
else if ( !( o instanceof Number ) ) {
else if ( !(o instanceof Number) ) {
throw new IllegalArgumentException( propertyName + " not an Number" );
}
return ( (Number) o ).longValue();
return ((Number) o).longValue();
}
private BeanUtils() {
}
}

View File

@ -23,10 +23,6 @@
*/
package org.hibernate.cache.ehcache.management.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
@ -36,10 +32,15 @@ import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.stat.SecondLevelCacheStatistics;
/**
* Bean for exposing region stats
*
* @author gkeim
*/
public class CacheRegionStats implements Serializable {
@ -61,7 +62,7 @@ public class CacheRegionStats implements Serializable {
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Cache-region";
private static final String TABULAR_TYPE_DESCRIPTION = "All Cache Region Statistics";
private static final String[] INDEX_NAMES = new String[] { "region", };
private static final String[] INDEX_NAMES = new String[] {"region",};
private static final TabularType TABULAR_TYPE;
static {
@ -72,7 +73,7 @@ public class CacheRegionStats implements Serializable {
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
catch ( OpenDataException e ) {
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
@ -123,7 +124,9 @@ public class CacheRegionStats implements Serializable {
protected long elementCountTotal;
/**
* @param region
* Construct a CacheRegionStats
*
* @param region The region name
*/
public CacheRegionStats(String region) {
this.region = region;
@ -131,8 +134,10 @@ public class CacheRegionStats implements Serializable {
}
/**
* @param region
* @param src
* Construct a CacheRegionStats
*
* @param region The region name
* @param src The SecondLevelCacheStatistics reference
*/
public CacheRegionStats(String region, SecondLevelCacheStatistics src) {
this( region );
@ -146,15 +151,18 @@ public class CacheRegionStats implements Serializable {
this.elementCountOnDisk = BeanUtils.getLongBeanProperty( src, "elementCountOnDisk" );
this.elementCountTotal = BeanUtils.getLongBeanProperty( src, "elementCountOnDisk" );
}
catch ( Exception e ) {
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
}
/**
* @param cData
* Construct a CacheRegionStats
*
* @param cData No idea
*/
@SuppressWarnings("UnusedAssignment")
public CacheRegionStats(final CompositeData cData) {
int i = 0;
region = (String) cData.get( ITEM_NAMES[i++] );
@ -168,30 +176,15 @@ public class CacheRegionStats implements Serializable {
elementCountTotal = (Long) cData.get( ITEM_NAMES[i++] );
}
private static int safeParseInt(String s) {
try {
return Integer.parseInt( s );
}
catch ( Exception e ) {
return -1;
}
}
/**
* @return hit ratio
*/
protected double determineHitRatio() {
final long readCount = getHitCount() + getMissCount();
double result = 0;
long readCount = getHitCount() + getMissCount();
if ( readCount > 0 ) {
result = getHitCount() / ( (double) readCount );
result = getHitCount() / ((double) readCount);
}
return result;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "region=" + getRegion() + "shortName=" + getShortName() + ", hitCount=" + getHitCount() + ", missCount="
@ -200,70 +193,45 @@ public class CacheRegionStats implements Serializable {
+ getElementCountTotal();
}
/**
* @return region name
*/
public String getRegion() {
return region;
}
/**
* @return short name
*/
public String getShortName() {
return shortName;
}
/**
* @return hit count
*/
public long getHitCount() {
return hitCount;
}
/**
* @return miss count
*/
public long getMissCount() {
return missCount;
}
/**
* @return put count
*/
public long getPutCount() {
return putCount;
}
/**
* @return hit ratio
*/
public double getHitRatio() {
return hitRatio;
}
/**
* @return in-memory element count
*/
public long getElementCountInMemory() {
return elementCountInMemory;
}
/**
* @return on-disk element count
*/
public long getElementCountOnDisk() {
return elementCountOnDisk;
}
/**
* @return total element count
*/
public long getElementCountTotal() {
return elementCountTotal;
}
/**
* Convert our state into a JMX CompositeData
*
* @return composite data
*/
public CompositeData toCompositeData() {
@ -276,12 +244,14 @@ public class CacheRegionStats implements Serializable {
}
);
}
catch ( OpenDataException e ) {
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
/**
* Convert our state into a JMX TabularData
*
* @return tabular data
*/
public static TabularData newTabularDataInstance() {
@ -289,14 +259,17 @@ public class CacheRegionStats implements Serializable {
}
/**
* @param tabularData
* Re-build the CacheRegionStats from JMX tabular data
*
* @param tabularData The JMX tabular data
*
* @return array of region statistics
*/
@SuppressWarnings("UnusedDeclaration")
public static CacheRegionStats[] fromTabularData(final TabularData tabularData) {
final List<CacheRegionStats> countList = new ArrayList( tabularData.size() );
for ( final Iterator pos = tabularData.values().iterator(); pos.hasNext(); ) {
countList.add( new CacheRegionStats( (CompositeData) pos.next() ) );
final List<CacheRegionStats> countList = new ArrayList<CacheRegionStats>( tabularData.size() );
for ( Object o : tabularData.values() ) {
countList.add( new CacheRegionStats( (CompositeData) o ) );
}
return countList.toArray( new CacheRegionStats[countList.size()] );
}

View File

@ -23,13 +23,14 @@
*/
package org.hibernate.cache.ehcache.management.impl;
import java.awt.*;
import java.awt.Color;
/**
* CacheRegionUtils
*
* @author gkeim
*/
@SuppressWarnings("UnusedDeclaration")
public abstract class CacheRegionUtils {
/**
* HIT_COLOR
@ -49,51 +50,53 @@ public abstract class CacheRegionUtils {
/**
* HIT_FILL_COLOR
*/
public final static Color HIT_FILL_COLOR = CacheRegionUtils.HIT_COLOR.brighter().brighter().brighter();
public static final Color HIT_FILL_COLOR = CacheRegionUtils.HIT_COLOR.brighter().brighter().brighter();
/**
* MISS_FILL_COLOR
*/
public final static Color MISS_FILL_COLOR = CacheRegionUtils.MISS_COLOR.brighter().brighter().brighter();
public static final Color MISS_FILL_COLOR = CacheRegionUtils.MISS_COLOR.brighter().brighter().brighter();
/**
* PUT_FILL_COLOR
*/
public final static Color PUT_FILL_COLOR = CacheRegionUtils.PUT_COLOR.brighter().brighter().brighter();
public static final Color PUT_FILL_COLOR = CacheRegionUtils.PUT_COLOR.brighter().brighter().brighter();
/**
* HIT_DRAW_COLOR
*/
public final static Color HIT_DRAW_COLOR = CacheRegionUtils.HIT_COLOR.darker();
public static final Color HIT_DRAW_COLOR = CacheRegionUtils.HIT_COLOR.darker();
/**
* MISS_DRAW_COLOR
*/
public final static Color MISS_DRAW_COLOR = CacheRegionUtils.MISS_COLOR.darker();
public static final Color MISS_DRAW_COLOR = CacheRegionUtils.MISS_COLOR.darker();
/**
* PUT_DRAW_COLOR
*/
public final static Color PUT_DRAW_COLOR = CacheRegionUtils.PUT_COLOR.darker();
public static final Color PUT_DRAW_COLOR = CacheRegionUtils.PUT_COLOR.darker();
/**
* determineShortName
* Determine a short name from the full name
*
* @param fullName
* @param fullName The full name
*
* @return The short name
*/
public static String determineShortName(String fullName) {
String result = fullName;
if ( fullName != null ) {
String[] comps = fullName.split( "\\." );
final String[] comps = fullName.split( "\\." );
if ( comps.length == 1 ) {
return fullName;
}
boolean truncate = true;
for ( int i = 0; i < comps.length; i++ ) {
String comp = comps[i];
char c = comp.charAt( 0 );
final char c = comp.charAt( 0 );
if ( truncate && Character.isUpperCase( c ) ) {
truncate = false;
}
@ -108,16 +111,18 @@ public abstract class CacheRegionUtils {
}
/**
* join
* Same as Hibernate internal {@link org.hibernate.internal.util.StringHelper#join} methods
*
* @param elements
* @param c
* @param elements The things to join
* @param c The separator between elements
*
* @return The joined string
*/
private static String join(String[] elements, char c) {
if ( elements == null ) {
return null;
}
StringBuilder sb = new StringBuilder();
final StringBuilder sb = new StringBuilder();
for ( String s : elements ) {
sb.append( s ).append( c );
}

View File

@ -23,10 +23,6 @@
*/
package org.hibernate.cache.ehcache.management.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
@ -36,6 +32,9 @@ import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.stat.CollectionStatistics;
@ -62,7 +61,7 @@ public class CollectionStats implements Serializable {
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Collection";
private static final String TABULAR_TYPE_DESCRIPTION = "All Collection Statistics";
private static final String[] INDEX_NAMES = new String[] { "roleName", };
private static final String[] INDEX_NAMES = new String[] {"roleName",};
private static final TabularType TABULAR_TYPE;
static {
@ -73,7 +72,7 @@ public class CollectionStats implements Serializable {
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
catch ( OpenDataException e ) {
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
@ -115,19 +114,23 @@ public class CollectionStats implements Serializable {
/**
* @param roleName
* Constructs a CollectionsStats
*
* @param role The collection role
*/
public CollectionStats(String roleName) {
this.roleName = roleName;
this.shortName = CacheRegionUtils.determineShortName( roleName );
public CollectionStats(String role) {
this.roleName = role;
this.shortName = CacheRegionUtils.determineShortName( role );
}
/**
* @param name
* @param src
* Constructs a CollectionsStats
*
* @param role The collection role
* @param src The CollectionStatistics instance
*/
public CollectionStats(String name, CollectionStatistics src) {
this( name );
public CollectionStats(String role, CollectionStatistics src) {
this( role );
try {
this.loadCount = BeanUtils.getLongBeanProperty( src, "loadCount" );
@ -136,15 +139,18 @@ public class CollectionStats implements Serializable {
this.removeCount = BeanUtils.getLongBeanProperty( src, "removeCount" );
this.recreateCount = BeanUtils.getLongBeanProperty( src, "recreateCount" );
}
catch ( Exception e ) {
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
}
/**
* @param cData
* Constructs a CollectionsStats from a JMX CompositeData
*
* @param cData The JMX CompositeData
*/
@SuppressWarnings("UnusedAssignment")
public CollectionStats(final CompositeData cData) {
int i = 0;
roleName = (String) cData.get( ITEM_NAMES[i++] );
@ -156,17 +162,10 @@ public class CollectionStats implements Serializable {
recreateCount = (Long) cData.get( ITEM_NAMES[i++] );
}
private static int safeParseInt(String s) {
try {
return Integer.parseInt( s );
}
catch ( Exception e ) {
return -1;
}
}
/**
* @param stats
* Update the internal stats
*
* @param stats The incoming stats
*/
public void add(CollectionStats stats) {
loadCount += stats.getLoadCount();
@ -176,9 +175,6 @@ public class CollectionStats implements Serializable {
recreateCount += stats.getRecreateCount();
}
/**
* toString
*/
@Override
public String toString() {
return "roleName=" + roleName + "shortName=" + shortName + ", loadCount=" + loadCount + ", fetchCount="
@ -186,86 +182,75 @@ public class CollectionStats implements Serializable {
+ recreateCount;
}
/**
* getRoleName
*/
@SuppressWarnings("UnusedDeclaration")
public String getRoleName() {
return roleName;
}
/**
* getShortName
*/
@SuppressWarnings("UnusedDeclaration")
public String getShortName() {
return shortName;
}
/**
* getLoadCount
*/
public long getLoadCount() {
return loadCount;
}
/**
* getFetchCount
*/
public long getFetchCount() {
return fetchCount;
}
/**
* getUpdateCount
*/
public long getUpdateCount() {
return updateCount;
}
/**
* getRemoveCount
*/
public long getRemoveCount() {
return removeCount;
}
/**
* getRecreateCount
*/
public long getRecreateCount() {
return recreateCount;
}
/**
* toCompositeData
* Builds a JMX CompositeData view of our state
*
* @return The JMX CompositeData
*/
public CompositeData toCompositeData() {
try {
return new CompositeDataSupport(
COMPOSITE_TYPE, ITEM_NAMES, new Object[] {
roleName, shortName, loadCount,
fetchCount, updateCount, removeCount, recreateCount,
}
COMPOSITE_TYPE,
ITEM_NAMES,
new Object[] { roleName, shortName, loadCount, fetchCount, updateCount, removeCount, recreateCount }
);
}
catch ( OpenDataException e ) {
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
/**
* newTabularDataInstance
* Builds a JMX TabularData
*
* @return JMX TabularData
*/
public static TabularData newTabularDataInstance() {
return new TabularDataSupport( TABULAR_TYPE );
}
/**
* fromTabularData
* Re-builds CollectionStats from JMX TabularData
*
* @param tabularData The JMX TabularData
*
* @return The CollectionsStats
*/
@SuppressWarnings("UnusedDeclaration")
public static CollectionStats[] fromTabularData(final TabularData tabularData) {
final List<CollectionStats> countList = new ArrayList( tabularData.size() );
for ( final Iterator pos = tabularData.values().iterator(); pos.hasNext(); ) {
countList.add( new CollectionStats( (CompositeData) pos.next() ) );
final List<CollectionStats> countList = new ArrayList<CollectionStats>( tabularData.size() );
for ( Object o : tabularData.values() ) {
countList.add( new CollectionStats( (CompositeData) o ) );
}
return countList.toArray( new CollectionStats[countList.size()] );
}

View File

@ -23,12 +23,12 @@
*/
package org.hibernate.cache.ehcache.management.impl;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
import javax.management.openmbean.TabularData;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.hibernate.management.api.EhcacheHibernateMBean;
@ -44,7 +44,7 @@ import org.hibernate.SessionFactory;
*
* @author <a href="mailto:asanoujam@terracottatech.com">Abhishek Sanoujam</a>
*/
public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernateMBean {
public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibernateMBean {
private static final MBeanNotificationInfo NOTIFICATION_INFO;
private final AtomicBoolean statsEnabled = new AtomicBoolean( true );
@ -52,7 +52,7 @@ public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernat
private volatile HibernateStats hibernateStats = NullHibernateStats.INSTANCE;
static {
final String[] notifTypes = new String[] { };
final String[] notifTypes = new String[] {};
final String name = Notification.class.getName();
final String description = "Ehcache Hibernate Statistics Event";
NOTIFICATION_INFO = new MBeanNotificationInfo( notifTypes, name, description );
@ -77,7 +77,7 @@ public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernat
try {
hibernateStats = new HibernateStatsImpl( sessionFactory );
}
catch ( Exception e ) {
catch (Exception e) {
throw new RuntimeException( e );
}
}
@ -588,10 +588,10 @@ public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernat
}
/**
* @see BaseEmitterBean#getNotificationInfo()
* @see AbstractEmitterBean#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
return new MBeanNotificationInfo[] { NOTIFICATION_INFO };
return new MBeanNotificationInfo[] {NOTIFICATION_INFO};
}
}

View File

@ -23,16 +23,17 @@
*/
package org.hibernate.cache.ehcache.management.impl;
import java.lang.management.ManagementFactory;
import java.util.Properties;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
import java.util.Properties;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Status;
import net.sf.ehcache.event.CacheManagerEventListener;
import org.jboss.logging.Logger;
import org.hibernate.SessionFactory;
@ -48,132 +49,132 @@ import org.hibernate.cfg.Environment;
* @author <a href="mailto:asanoujam@terracottatech.com">Abhishek Sanoujam</a>
*/
public class EhcacheHibernateMBeanRegistrationImpl
implements EhcacheHibernateMBeanRegistration, CacheManagerEventListener {
implements EhcacheHibernateMBeanRegistration, CacheManagerEventListener {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
EhcacheHibernateMBeanRegistrationImpl.class.getName()
);
private static final int MAX_MBEAN_REGISTRATION_RETRIES = 50;
private String cacheManagerClusterUUID;
private String registeredCacheManagerName;
private Status status = Status.STATUS_UNINITIALISED;
private volatile EhcacheHibernate ehcacheHibernate;
private volatile ObjectName cacheManagerObjectName;
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
EhcacheHibernateMBeanRegistrationImpl.class.getName()
);
private static final int MAX_MBEAN_REGISTRATION_RETRIES = 50;
private String cacheManagerClusterUUID;
private String registeredCacheManagerName;
private Status status = Status.STATUS_UNINITIALISED;
private volatile EhcacheHibernate ehcacheHibernate;
private volatile ObjectName cacheManagerObjectName;
/**
* {@inheritDoc}
*/
public synchronized void registerMBeanForCacheManager(final CacheManager manager, final Properties properties)
throws Exception {
String sessionFactoryName = properties.getProperty( Environment.SESSION_FACTORY_NAME );
String name = null;
if ( sessionFactoryName == null ) {
name = manager.getName();
}
else {
name = "".equals( sessionFactoryName.trim() ) ? manager.getName() : sessionFactoryName;
}
registerBean( name, manager );
}
/**
* {@inheritDoc}
*/
public synchronized void registerMBeanForCacheManager(final CacheManager manager, final Properties properties)
throws Exception {
String sessionFactoryName = properties.getProperty( Environment.SESSION_FACTORY_NAME );
String name = null;
if ( sessionFactoryName == null ) {
name = manager.getName();
}
else {
name = "".equals( sessionFactoryName.trim() ) ? manager.getName() : sessionFactoryName;
}
registerBean( name, manager );
}
private void registerBean(String name, CacheManager manager) throws Exception {
ehcacheHibernate = new EhcacheHibernate( manager );
int tries = 0;
boolean success = false;
Exception exception = null;
cacheManagerClusterUUID = manager.getClusterUUID();
do {
this.registeredCacheManagerName = name;
if ( tries != 0 ) {
registeredCacheManagerName += "_" + tries;
}
try {
// register the CacheManager MBean
MBeanServer mBeanServer = getMBeanServer();
cacheManagerObjectName = EhcacheHibernateMbeanNames.getCacheManagerObjectName(
cacheManagerClusterUUID,
registeredCacheManagerName
);
mBeanServer.registerMBean( ehcacheHibernate, cacheManagerObjectName );
success = true;
break;
}
catch ( InstanceAlreadyExistsException e ) {
success = false;
exception = e;
}
tries++;
} while ( tries < MAX_MBEAN_REGISTRATION_RETRIES );
if ( !success ) {
throw new Exception(
"Cannot register mbean for CacheManager with name" + manager.getName() + " after "
+ MAX_MBEAN_REGISTRATION_RETRIES + " retries. Last tried name=" + registeredCacheManagerName,
exception
);
}
status = Status.STATUS_ALIVE;
}
private void registerBean(String name, CacheManager manager) throws Exception {
ehcacheHibernate = new EhcacheHibernate( manager );
int tries = 0;
boolean success = false;
Exception exception = null;
cacheManagerClusterUUID = manager.getClusterUUID();
do {
this.registeredCacheManagerName = name;
if ( tries != 0 ) {
registeredCacheManagerName += "_" + tries;
}
try {
// register the CacheManager MBean
MBeanServer mBeanServer = getMBeanServer();
cacheManagerObjectName = EhcacheHibernateMbeanNames.getCacheManagerObjectName(
cacheManagerClusterUUID,
registeredCacheManagerName
);
mBeanServer.registerMBean( ehcacheHibernate, cacheManagerObjectName );
success = true;
break;
}
catch (InstanceAlreadyExistsException e) {
success = false;
exception = e;
}
tries++;
} while ( tries < MAX_MBEAN_REGISTRATION_RETRIES );
if ( !success ) {
throw new Exception(
"Cannot register mbean for CacheManager with name" + manager.getName() + " after "
+ MAX_MBEAN_REGISTRATION_RETRIES + " retries. Last tried name=" + registeredCacheManagerName,
exception
);
}
status = Status.STATUS_ALIVE;
}
private MBeanServer getMBeanServer() {
return ManagementFactory.getPlatformMBeanServer();
}
private MBeanServer getMBeanServer() {
return ManagementFactory.getPlatformMBeanServer();
}
/**
* {@inheritDoc}
*/
public void enableHibernateStatisticsSupport(SessionFactory sessionFactory) {
ehcacheHibernate.enableHibernateStatistics( sessionFactory );
}
/**
* {@inheritDoc}
*/
public void enableHibernateStatisticsSupport(SessionFactory sessionFactory) {
ehcacheHibernate.enableHibernateStatistics( sessionFactory );
}
/**
* {@inheritDoc}
*/
public synchronized void dispose() throws CacheException {
if ( status == Status.STATUS_SHUTDOWN ) {
return;
}
/**
* {@inheritDoc}
*/
public synchronized void dispose() throws CacheException {
if ( status == Status.STATUS_SHUTDOWN ) {
return;
}
try {
getMBeanServer().unregisterMBean( cacheManagerObjectName );
}
catch ( Exception e ) {
LOG.warn(
"Error unregistering object instance " + cacheManagerObjectName + " . Error was " + e.getMessage(),
e
);
}
ehcacheHibernate = null;
cacheManagerObjectName = null;
status = Status.STATUS_SHUTDOWN;
}
try {
getMBeanServer().unregisterMBean( cacheManagerObjectName );
}
catch (Exception e) {
LOG.warn(
"Error unregistering object instance " + cacheManagerObjectName + " . Error was " + e.getMessage(),
e
);
}
ehcacheHibernate = null;
cacheManagerObjectName = null;
status = Status.STATUS_SHUTDOWN;
}
/**
* {@inheritDoc}
*/
public synchronized Status getStatus() {
return status;
}
/**
* {@inheritDoc}
*/
public synchronized Status getStatus() {
return status;
}
/**
* No-op in this case
*/
public void init() throws CacheException {
// no-op
}
/**
* No-op in this case
*/
public void init() throws CacheException {
// no-op
}
/**
* No-op in this case
*/
public void notifyCacheAdded(String cacheName) {
// no-op
}
/**
* No-op in this case
*/
public void notifyCacheAdded(String cacheName) {
// no-op
}
/**
* No-op in this case
*/
public void notifyCacheRemoved(String cacheName) {
// no-op
}
/**
* No-op in this case
*/
public void notifyCacheRemoved(String cacheName) {
// no-op
}
}

View File

@ -23,12 +23,12 @@
*/
package org.hibernate.cache.ehcache.management.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
@ -42,7 +42,7 @@ import net.sf.ehcache.management.sampled.SampledCacheManager;
*
* @author <a href="mailto:asanoujam@terracottatech.com">Abhishek Sanoujam</a>
*/
public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStats {
private static final long MILLIS_PER_SECOND = 1000;
private static final MBeanNotificationInfo NOTIFICATION_INFO;
@ -156,7 +156,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
*/
public double getCacheHitRate() {
long now = System.currentTimeMillis();
double deltaSecs = (double) ( now - statsSince ) / MILLIS_PER_SECOND;
double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND;
return getCacheHitCount() / deltaSecs;
}
@ -193,7 +193,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
*/
public double getCacheMissRate() {
long now = System.currentTimeMillis();
double deltaSecs = (double) ( now - statsSince ) / MILLIS_PER_SECOND;
double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND;
return getCacheMissCount() / deltaSecs;
}
@ -230,7 +230,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
*/
public double getCachePutRate() {
long now = System.currentTimeMillis();
double deltaSecs = (double) ( now - statsSince ) / MILLIS_PER_SECOND;
double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND;
return getCachePutCount() / deltaSecs;
}
@ -339,8 +339,8 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
rv.put(
name, new int[] {
(int) cache.getSampledCacheStatistics().getCacheHitMostRecentSample(),
(int) ( cache.getSampledCacheStatistics().getCacheMissNotFoundMostRecentSample()
+ cache.getSampledCacheStatistics().getCacheMissExpiredMostRecentSample() ),
(int) (cache.getSampledCacheStatistics().getCacheMissNotFoundMostRecentSample()
+ cache.getSampledCacheStatistics().getCacheMissExpiredMostRecentSample()),
(int) cache.getSampledCacheStatistics().getCacheElementPutMostRecentSample(),
}
);
@ -388,7 +388,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
}
}
}
return rv.toArray( new String[] { } );
return rv.toArray( new String[] {} );
}
/**
@ -680,10 +680,10 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
}
/**
* @see BaseEmitterBean#getNotificationInfo()
* @see AbstractEmitterBean#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
return new MBeanNotificationInfo[] { NOTIFICATION_INFO };
return new MBeanNotificationInfo[] {NOTIFICATION_INFO};
}
}

View File

@ -23,10 +23,6 @@
*/
package org.hibernate.cache.ehcache.management.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
@ -36,6 +32,10 @@ import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.stat.EntityStatistics;
@ -63,7 +63,7 @@ public class EntityStats implements Serializable {
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Entity";
private static final String TABULAR_TYPE_DESCRIPTION = "All Entity Statistics";
private static final String[] INDEX_NAMES = new String[] { "name", };
private static final String[] INDEX_NAMES = new String[] {"name",};
private static final TabularType TABULAR_TYPE;
static {
@ -74,7 +74,7 @@ public class EntityStats implements Serializable {
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
catch ( OpenDataException e ) {
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
@ -142,7 +142,7 @@ public class EntityStats implements Serializable {
this.fetchCount = BeanUtils.getLongBeanProperty( src, "fetchCount" );
this.optimisticFailureCount = BeanUtils.getLongBeanProperty( src, "optimisticFailureCount" );
}
catch ( Exception e ) {
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
@ -167,7 +167,7 @@ public class EntityStats implements Serializable {
try {
return Integer.parseInt( s );
}
catch ( Exception e ) {
catch (Exception e) {
return -1;
}
}
@ -262,7 +262,7 @@ public class EntityStats implements Serializable {
}
);
}
catch ( OpenDataException e ) {
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}

View File

@ -23,13 +23,13 @@
*/
package org.hibernate.cache.ehcache.management.impl;
import java.util.ArrayList;
import java.util.List;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import java.util.ArrayList;
import java.util.List;
import net.sf.ehcache.hibernate.management.api.HibernateStats;
@ -43,14 +43,14 @@ import org.hibernate.stat.Statistics;
*
* @author <a href="mailto:asanoujam@terracottatech.com">Abhishek Sanoujam</a>
*/
public class HibernateStatsImpl extends BaseEmitterBean implements HibernateStats {
public class HibernateStatsImpl extends AbstractEmitterBean implements HibernateStats {
private static final double MILLIS_PER_SECOND = 1000;
private static final MBeanNotificationInfo NOTIFICATION_INFO;
private final SessionFactory sessionFactory;
static {
final String[] notifTypes = new String[] { };
final String[] notifTypes = new String[] {};
final String name = Notification.class.getName();
final String description = "Hibernate Statistics Event";
NOTIFICATION_INFO = new MBeanNotificationInfo( notifTypes, name, description );
@ -172,7 +172,7 @@ public class HibernateStatsImpl extends BaseEmitterBean implements HibernateStat
public double getQueryExecutionRate() {
long startTime = getStatistics().getStartTime();
long now = System.currentTimeMillis();
double deltaSecs = ( now - startTime ) / MILLIS_PER_SECOND;
double deltaSecs = (now - startTime) / MILLIS_PER_SECOND;
return getQueryExecutionCount() / deltaSecs;
}
@ -321,10 +321,10 @@ public class HibernateStatsImpl extends BaseEmitterBean implements HibernateStat
}
/**
* @see BaseEmitterBean#getNotificationInfo()
* @see AbstractEmitterBean#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
return new MBeanNotificationInfo[] { NOTIFICATION_INFO };
return new MBeanNotificationInfo[] {NOTIFICATION_INFO};
}
}

View File

@ -31,6 +31,7 @@ import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import net.sf.ehcache.CacheManager;
import org.jboss.logging.Logger;
import org.hibernate.SessionFactory;
@ -48,141 +49,142 @@ import org.hibernate.internal.SessionFactoryRegistry;
* @author <a href="mailto:alexsnaps@terracottatech.com">Alex Snaps</a>
*/
public class ProviderMBeanRegistrationHelper {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
ProviderMBeanRegistrationHelper.class.getName()
);
private static final int MILLIS_PER_SECOND = 1000;
private static final int SLEEP_MILLIS = 500;
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
ProviderMBeanRegistrationHelper.class.getName()
);
private static final int MILLIS_PER_SECOND = 1000;
private static final int SLEEP_MILLIS = 500;
private volatile EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration;
private volatile EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration;
/**
* Registers mbean for the input cache manager and the session factory name
*
* @param manager the backing cachemanager
* @param properties session factory config properties
*/
public void registerMBean(final CacheManager manager, final Properties properties) {
if ( Boolean.getBoolean( "tc.active" ) ) {
ehcacheHibernateMBeanRegistration = new EhcacheHibernateMBeanRegistrationImpl();
manager.getTimer().scheduleAtFixedRate(
new RegisterMBeansTask( ehcacheHibernateMBeanRegistration, manager, properties ), SLEEP_MILLIS,
SLEEP_MILLIS
);
}
}
/**
* Registers mbean for the input cache manager and the session factory name
*
* @param manager the backing cachemanager
* @param properties session factory config properties
*/
public void registerMBean(final CacheManager manager, final Properties properties) {
if ( Boolean.getBoolean( "tc.active" ) ) {
ehcacheHibernateMBeanRegistration = new EhcacheHibernateMBeanRegistrationImpl();
manager.getTimer().scheduleAtFixedRate(
new RegisterMBeansTask( ehcacheHibernateMBeanRegistration, manager, properties ), SLEEP_MILLIS,
SLEEP_MILLIS
);
}
}
/**
* Unregisters previously registered mbean.
*/
public void unregisterMBean() {
if ( ehcacheHibernateMBeanRegistration != null ) {
ehcacheHibernateMBeanRegistration.dispose();
ehcacheHibernateMBeanRegistration = null;
}
}
/**
* Unregisters previously registered mbean.
*/
public void unregisterMBean() {
if ( ehcacheHibernateMBeanRegistration != null ) {
ehcacheHibernateMBeanRegistration.dispose();
ehcacheHibernateMBeanRegistration = null;
}
}
/**
* Task for running mbean registration that can be scheduled in a timer
*/
private static class RegisterMBeansTask extends TimerTask {
private static final int NUM_SECONDS = 30;
private long startTime;
private final AtomicBoolean mbeanRegistered = new AtomicBoolean( false );
private final EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration;
private final CacheManager manager;
private final Properties properties;
/**
* Task for running mbean registration that can be scheduled in a timer
*/
private static class RegisterMBeansTask extends TimerTask {
private static final int NUM_SECONDS = 30;
private long startTime;
private final AtomicBoolean mbeanRegistered = new AtomicBoolean( false );
private final EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration;
private final CacheManager manager;
private final Properties properties;
public RegisterMBeansTask(EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration,
CacheManager manager, Properties properties) {
this.ehcacheHibernateMBeanRegistration = ehcacheHibernateMBeanRegistration;
this.manager = manager;
this.properties = properties;
}
public RegisterMBeansTask(
EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration,
CacheManager manager, Properties properties) {
this.ehcacheHibernateMBeanRegistration = ehcacheHibernateMBeanRegistration;
this.manager = manager;
this.properties = properties;
}
@Override
public void run() {
LOG.debug( "Running mbean initializer task for ehcache hibernate..." );
startTime = System.currentTimeMillis();
if ( mbeanRegistered.compareAndSet( false, true ) ) {
try {
ehcacheHibernateMBeanRegistration.registerMBeanForCacheManager( manager, properties );
LOG.debug( "Successfully registered bean" );
}
catch ( Exception e ) {
throw new CacheException( e );
}
}
SessionFactory sessionFactory = locateSessionFactory();
if ( sessionFactory == null ) {
LOG.debug(
"SessionFactory is probably still being initialized..."
+ " waiting for it to complete before enabling hibernate statistics monitoring via JMX"
);
if ( System.currentTimeMillis() > startTime + ( NUM_SECONDS * MILLIS_PER_SECOND ) ) {
LOG.info( "Hibernate statistics monitoring through JMX is DISABLED." );
LOG.info(
"Failed to look up SessionFactory after " + NUM_SECONDS + " seconds using session-factory properties '"
+ properties + "'"
);
this.cancel();
}
return;
}
else {
ehcacheHibernateMBeanRegistration.enableHibernateStatisticsSupport( sessionFactory );
LOG.info( "Hibernate statistics monitoring through JMX is ENABLED. " );
this.cancel();
}
}
@Override
public void run() {
LOG.debug( "Running mbean initializer task for ehcache hibernate..." );
startTime = System.currentTimeMillis();
if ( mbeanRegistered.compareAndSet( false, true ) ) {
try {
ehcacheHibernateMBeanRegistration.registerMBeanForCacheManager( manager, properties );
LOG.debug( "Successfully registered bean" );
}
catch (Exception e) {
throw new CacheException( e );
}
}
SessionFactory sessionFactory = locateSessionFactory();
if ( sessionFactory == null ) {
LOG.debug(
"SessionFactory is probably still being initialized..."
+ " waiting for it to complete before enabling hibernate statistics monitoring via JMX"
);
if ( System.currentTimeMillis() > startTime + (NUM_SECONDS * MILLIS_PER_SECOND) ) {
LOG.info( "Hibernate statistics monitoring through JMX is DISABLED." );
LOG.info(
"Failed to look up SessionFactory after " + NUM_SECONDS + " seconds using session-factory properties '"
+ properties + "'"
);
this.cancel();
}
return;
}
else {
ehcacheHibernateMBeanRegistration.enableHibernateStatisticsSupport( sessionFactory );
LOG.info( "Hibernate statistics monitoring through JMX is ENABLED. " );
this.cancel();
}
}
private SessionFactory locateSessionFactory() {
String jndiName = properties.getProperty( Environment.SESSION_FACTORY_NAME );
if ( jndiName != null ) {
return SessionFactoryRegistry.INSTANCE.getNamedSessionFactory( jndiName );
}
try {
Class factoryType = SessionFactoryRegistry.class;
Field instancesField = getField( factoryType, "sessionFactoryMap" );
if ( instancesField == null ) {
throw new RuntimeException( "Expected 'sessionFactoryMap' field on " + SessionFactoryRegistry.class.getName() );
}
instancesField.setAccessible( true );
Map map = (Map) instancesField.get( SessionFactoryRegistry.INSTANCE );
if ( map == null ) {
return null;
}
Iterator values = map.values().iterator();
while ( values.hasNext() ) {
SessionFactory sessionFactory = (SessionFactory) values.next();
Class sessionFactoryType = sessionFactory.getClass();
Field propertiesField = getField( sessionFactoryType, "properties" );
if ( propertiesField != null ) {
propertiesField.setAccessible( true );
Properties props = (Properties) propertiesField.get( sessionFactory );
if ( props != null && props.equals( properties ) ) {
return sessionFactory;
}
}
}
}
catch ( RuntimeException re ) {
LOG.error( "Error locating Hibernate Session Factory", re );
}
catch ( IllegalAccessException iae ) {
LOG.error( "Error locating Hibernate Session Factory", iae );
}
return null;
}
}
private SessionFactory locateSessionFactory() {
String jndiName = properties.getProperty( Environment.SESSION_FACTORY_NAME );
if ( jndiName != null ) {
return SessionFactoryRegistry.INSTANCE.getNamedSessionFactory( jndiName );
}
try {
Class factoryType = SessionFactoryRegistry.class;
Field instancesField = getField( factoryType, "sessionFactoryMap" );
if ( instancesField == null ) {
throw new RuntimeException( "Expected 'sessionFactoryMap' field on " + SessionFactoryRegistry.class.getName() );
}
instancesField.setAccessible( true );
Map map = (Map) instancesField.get( SessionFactoryRegistry.INSTANCE );
if ( map == null ) {
return null;
}
Iterator values = map.values().iterator();
while ( values.hasNext() ) {
SessionFactory sessionFactory = (SessionFactory) values.next();
Class sessionFactoryType = sessionFactory.getClass();
Field propertiesField = getField( sessionFactoryType, "properties" );
if ( propertiesField != null ) {
propertiesField.setAccessible( true );
Properties props = (Properties) propertiesField.get( sessionFactory );
if ( props != null && props.equals( properties ) ) {
return sessionFactory;
}
}
}
}
catch (RuntimeException re) {
LOG.error( "Error locating Hibernate Session Factory", re );
}
catch (IllegalAccessException iae) {
LOG.error( "Error locating Hibernate Session Factory", iae );
}
return null;
}
}
private static Field getField(Class c, String fieldName) {
for ( Field field : c.getDeclaredFields() ) {
if ( field.getName().equals( fieldName ) ) {
return field;
}
}
throw new NoSuchFieldError( "Type '" + c + "' has no field '" + fieldName + "'" );
}
private static Field getField(Class c, String fieldName) {
for ( Field field : c.getDeclaredFields() ) {
if ( field.getName().equals( fieldName ) ) {
return field;
}
}
throw new NoSuchFieldError( "Type '" + c + "' has no field '" + fieldName + "'" );
}
}

View File

@ -23,10 +23,6 @@
*/
package org.hibernate.cache.ehcache.management.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
@ -36,6 +32,10 @@ import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.stat.QueryStatistics;
@ -75,7 +75,7 @@ public class QueryStats implements Serializable {
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Query";
private static final String TABULAR_TYPE_DESCRIPTION = "All Query Statistics";
private static final String[] INDEX_NAMES = new String[] { "query", };
private static final String[] INDEX_NAMES = new String[] {"query",};
private static final TabularType TABULAR_TYPE;
static {
@ -86,7 +86,7 @@ public class QueryStats implements Serializable {
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
catch ( OpenDataException e ) {
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
@ -161,7 +161,7 @@ public class QueryStats implements Serializable {
this.executionMinTime =
BeanUtils.getLongBeanProperty( src, "executionMinTime" );
}
catch ( Exception e ) {
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
@ -187,7 +187,7 @@ public class QueryStats implements Serializable {
try {
return Integer.parseInt( s );
}
catch ( Exception e ) {
catch (Exception e) {
return -1;
}
}
@ -297,7 +297,7 @@ public class QueryStats implements Serializable {
}
);
}
catch ( OpenDataException e ) {
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}

View File

@ -0,0 +1,4 @@
/**
* Defines JMX support for the Ehcache integration
*/
package org.hibernate.cache.ehcache.management.impl;

View File

@ -0,0 +1,4 @@
/**
* Defines the integration with Ehcache as a second-level cache service.
*/
package org.hibernate.cache.ehcache;