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;
/**
@ -101,32 +102,25 @@ abstract class AbstractEhcacheRegionFactory implements RegionFactory {
new NonstopAccessStrategyFactory( new EhcacheAccessStrategyFactoryImpl() );
/**
* Whether to optimize for minimals puts or minimal gets.
* {@inheritDoc}
* <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
*/
@Override
public boolean isMinimalPutsEnabledByDefault() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public long nextTimestamp() {
return net.sf.ehcache.util.Timestamper.next();
}
/**
* {@inheritDoc}
*/
@Override
public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
return new EhcacheEntityRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties );
@ -135,13 +129,20 @@ abstract class AbstractEhcacheRegionFactory implements RegionFactory {
@Override
public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
return new EhcacheNaturalIdRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties );
return new EhcacheNaturalIdRegion(
accessStrategyFactory,
getCache( regionName ),
settings,
metadata,
properties
);
}
/**
* {@inheritDoc}
*/
public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata)
@Override
public CollectionRegion buildCollectionRegion(
String regionName,
Properties properties,
CacheDataDescription metadata)
throws CacheException {
return new EhcacheCollectionRegion(
accessStrategyFactory,
@ -152,23 +153,20 @@ abstract class AbstractEhcacheRegionFactory implements RegionFactory {
);
}
/**
* {@inheritDoc}
*/
@Override
public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException {
return new EhcacheQueryResultsRegion( accessStrategyFactory, getCache( regionName ), properties );
}
@InjectService
@SuppressWarnings("UnusedDeclaration")
public void setClassLoaderService(ClassLoaderService classLoaderService) {
this.classLoaderService = classLoaderService;
}
private ClassLoaderService classLoaderService;
/**
* {@inheritDoc}
*/
@Override
public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException {
return new EhcacheTimestampsRegion( accessStrategyFactory, getCache( regionName ), properties );
}
@ -182,7 +180,7 @@ abstract class AbstractEhcacheRegionFactory implements RegionFactory {
cache = manager.getEhcache( name );
LOG.debug( "started EHCache region: " + name );
}
HibernateUtil.validateEhcache( cache );
HibernateEhcacheUtils.validateEhcache( cache );
return cache;
}
catch (net.sf.ehcache.CacheException e) {
@ -200,7 +198,7 @@ abstract class AbstractEhcacheRegionFactory implements RegionFactory {
url = classLoaderService.locateResource( configurationResourceName );
}
if ( url == null ) {
ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();
final ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();
if ( standardClassloader != null ) {
url = standardClassloader.getResource( configurationResourceName );
}

View File

@ -40,42 +40,96 @@ import static org.jboss.logging.Logger.Level.WARN;
@MessageLogger(projectCode = "HHH")
public interface EhCacheMessageLogger extends CoreMessageLogger {
/**
* 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 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 )
@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();
/**
* 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);
/**
* 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);
/**
* 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 )
@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 (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 )
@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}.
*
* @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);
/**
* 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 )
@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;
/**
@ -53,19 +54,24 @@ public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory {
);
/**
* Creates a non-singleton EhCacheRegionFactory
*/
@SuppressWarnings("UnusedDeclaration")
public EhCacheRegionFactory() {
}
/**
* Creates a non-singleton EhCacheRegionFactory
*
* @param prop Not used
*/
@SuppressWarnings("UnusedDeclaration")
public EhCacheRegionFactory(Properties prop) {
super();
}
/**
* {@inheritDoc}
*/
@Override
public void start(Settings settings, Properties properties) throws CacheException {
this.settings = settings;
if ( manager != null ) {
@ -79,7 +85,7 @@ public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory {
configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME );
}
if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
Configuration configuration = ConfigurationFactory.parseConfiguration();
final Configuration configuration = ConfigurationFactory.parseConfiguration();
manager = new CacheManager( configuration );
}
else {
@ -90,7 +96,7 @@ public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory {
catch (MalformedURLException e) {
url = loadResource( configurationResourceName );
}
Configuration configuration = HibernateUtil.loadAndCorrectConfiguration( url );
final Configuration configuration = HibernateEhcacheUtils.loadAndCorrectConfiguration( url );
manager = new CacheManager( configuration );
}
mbeanRegistrationHelper.registerMBean( manager, properties );
@ -112,9 +118,7 @@ public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory {
}
}
/**
* {@inheritDoc}
*/
@Override
public void stop() {
try {
if ( manager != null ) {

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,23 +46,31 @@ 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 AtomicInteger REFERENCE_COUNT = new AtomicInteger();
/**
* Returns a representation of the singleton EhCacheRegionFactory
* Constructs a SingletonEhCacheRegionFactory
*/
@SuppressWarnings("UnusedDeclaration")
public SingletonEhCacheRegionFactory() {
}
/**
* Constructs a SingletonEhCacheRegionFactory
*
* @param prop Not used
*/
@SuppressWarnings("UnusedDeclaration")
public SingletonEhCacheRegionFactory(Properties prop) {
super();
}
/**
* {@inheritDoc}
*/
@Override
public void start(Settings settings, Properties properties) throws CacheException {
this.settings = settings;
try {
@ -88,7 +97,7 @@ public class SingletonEhCacheRegionFactory extends AbstractEhcacheRegionFactory
}
url = loadResource( configurationResourceName );
}
Configuration configuration = HibernateUtil.loadAndCorrectConfiguration( url );
final Configuration configuration = HibernateEhcacheUtils.loadAndCorrectConfiguration( url );
manager = CacheManager.create( configuration );
REFERENCE_COUNT.incrementAndGet();
}
@ -99,9 +108,7 @@ public class SingletonEhCacheRegionFactory extends AbstractEhcacheRegionFactory
}
}
/**
* {@inheritDoc}
*/
@Override
public void stop() {
try {
if ( manager != null ) {
@ -115,5 +122,4 @@ public class SingletonEhCacheRegionFactory extends AbstractEhcacheRegionFactory
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;
@ -74,7 +75,7 @@ public final class HibernateNonstopCacheExceptionHandler {
* {@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
* @param nonStopCacheException The exception to handle
*/
public void handleNonstopCacheException(NonStopCacheException nonStopCacheException) {
if ( Boolean.getBoolean( HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY ) ) {

View File

@ -46,16 +46,16 @@ public class NonstopAccessStrategyFactory implements EhcacheAccessStrategyFactor
/**
* Constructor accepting the actual factory
*
* @param actualFactory
* @param actualFactory The wrapped RegionAccessStrategy factory
*/
public NonstopAccessStrategyFactory(EhcacheAccessStrategyFactory actualFactory) {
this.actualFactory = actualFactory;
}
/**
* {@inheritDoc}
*/
public EntityRegionAccessStrategy createEntityRegionAccessStrategy(EhcacheEntityRegion entityRegion, AccessType accessType) {
@Override
public EntityRegionAccessStrategy createEntityRegionAccessStrategy(
EhcacheEntityRegion entityRegion,
AccessType accessType) {
return new NonstopAwareEntityRegionAccessStrategy(
actualFactory.createEntityRegionAccessStrategy( entityRegion, accessType ),
HibernateNonstopCacheExceptionHandler.getInstance()
@ -63,7 +63,8 @@ public class NonstopAccessStrategyFactory implements EhcacheAccessStrategyFactor
}
@Override
public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion naturalIdRegion,
public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(
EhcacheNaturalIdRegion naturalIdRegion,
AccessType accessType) {
return new NonstopAwareNaturalIdRegionAccessStrategy(
actualFactory.createNaturalIdRegionAccessStrategy(
@ -73,10 +74,9 @@ public class NonstopAccessStrategyFactory implements EhcacheAccessStrategyFactor
);
}
/**
* {@inheritDoc}
*/
public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(EhcacheCollectionRegion collectionRegion,
@Override
public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(
EhcacheCollectionRegion collectionRegion,
AccessType accessType) {
return new NonstopAwareCollectionRegionAccessStrategy(
actualFactory.createCollectionRegionAccessStrategy(

View File

@ -38,36 +38,28 @@ 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,
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 );
@ -77,11 +69,7 @@ public class NonstopAwareCollectionRegionAccessStrategy implements CollectionReg
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll()
*/
@Override
public void evictAll() throws CacheException {
try {
actualStrategy.evictAll();
@ -91,11 +79,7 @@ public class NonstopAwareCollectionRegionAccessStrategy implements CollectionReg
}
}
/**
* {@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 );
@ -106,11 +90,7 @@ public class NonstopAwareCollectionRegionAccessStrategy implements CollectionReg
}
}
/**
* {@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 );
@ -121,11 +101,7 @@ public class NonstopAwareCollectionRegionAccessStrategy implements CollectionReg
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion()
*/
@Override
public SoftLock lockRegion() throws CacheException {
try {
return actualStrategy.lockRegion();
@ -136,12 +112,7 @@ public class NonstopAwareCollectionRegionAccessStrategy implements CollectionReg
}
}
/**
* {@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 {
@ -153,11 +124,7 @@ public class NonstopAwareCollectionRegionAccessStrategy implements CollectionReg
}
}
/**
* {@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 );
@ -168,11 +135,7 @@ public class NonstopAwareCollectionRegionAccessStrategy implements CollectionReg
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#remove(java.lang.Object)
*/
@Override
public void remove(Object key) throws CacheException {
try {
actualStrategy.remove( key );
@ -182,11 +145,7 @@ public class NonstopAwareCollectionRegionAccessStrategy implements CollectionReg
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll()
*/
@Override
public void removeAll() throws CacheException {
try {
actualStrategy.removeAll();
@ -196,11 +155,7 @@ public class NonstopAwareCollectionRegionAccessStrategy implements CollectionReg
}
}
/**
* {@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 );
@ -210,11 +165,7 @@ public class NonstopAwareCollectionRegionAccessStrategy implements CollectionReg
}
}
/**
* {@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 );

View File

@ -38,36 +38,28 @@ 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,
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 );
@ -78,12 +70,7 @@ public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAcces
}
}
/**
* {@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 {
@ -95,11 +82,7 @@ public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAcces
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evict(java.lang.Object)
*/
@Override
public void evict(Object key) throws CacheException {
try {
actualStrategy.evict( key );
@ -109,11 +92,7 @@ public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAcces
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll()
*/
@Override
public void evictAll() throws CacheException {
try {
actualStrategy.evictAll();
@ -123,11 +102,7 @@ public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAcces
}
}
/**
* {@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 );
@ -138,11 +113,7 @@ public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAcces
}
}
/**
* {@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 );
@ -153,11 +124,7 @@ public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAcces
}
}
/**
* {@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 );
@ -168,11 +135,7 @@ public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAcces
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion()
*/
@Override
public SoftLock lockRegion() throws CacheException {
try {
return actualStrategy.lockRegion();
@ -183,12 +146,7 @@ public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAcces
}
}
/**
* {@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 {
@ -200,11 +158,7 @@ public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAcces
}
}
/**
* {@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 );
@ -215,11 +169,7 @@ public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAcces
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#remove(java.lang.Object)
*/
@Override
public void remove(Object key) throws CacheException {
try {
actualStrategy.remove( key );
@ -229,11 +179,7 @@ public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAcces
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll()
*/
@Override
public void removeAll() throws CacheException {
try {
actualStrategy.removeAll();
@ -243,11 +189,7 @@ public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAcces
}
}
/**
* {@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 );
@ -257,11 +199,7 @@ public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAcces
}
}
/**
* {@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 );
@ -271,12 +209,7 @@ public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAcces
}
}
/**
* {@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 {

View File

@ -38,17 +38,17 @@ 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,
public NonstopAwareNaturalIdRegionAccessStrategy(
NaturalIdRegionAccessStrategy actualStrategy,
HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
this.actualStrategy = actualStrategy;
this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler;
@ -98,20 +98,12 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
}
}
/**
* {@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 );
@ -121,11 +113,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll()
*/
@Override
public void evictAll() throws CacheException {
try {
actualStrategy.evictAll();
@ -135,11 +123,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
}
}
/**
* {@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 );
@ -150,11 +134,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
}
}
/**
* {@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 );
@ -165,11 +145,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion()
*/
@Override
public SoftLock lockRegion() throws CacheException {
try {
return actualStrategy.lockRegion();
@ -180,12 +156,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
}
}
/**
* {@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 {
@ -197,11 +168,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
}
}
/**
* {@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 );
@ -212,11 +179,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#remove(java.lang.Object)
*/
@Override
public void remove(Object key) throws CacheException {
try {
actualStrategy.remove( key );
@ -226,11 +189,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
}
}
/**
* {@inheritDoc}
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll()
*/
@Override
public void removeAll() throws CacheException {
try {
actualStrategy.removeAll();
@ -240,11 +199,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
}
}
/**
* {@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 );
@ -254,11 +209,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
}
}
/**
* {@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 );

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
* @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) {
public EhcacheCollectionRegion(
EhcacheAccessStrategyFactory accessStrategyFactory,
Ehcache underlyingCache,
Settings settings,
CacheDataDescription metadata,
Properties properties) {
super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
}
/**
* {@inheritDoc}
*/
@Override
public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
return accessStrategyFactory.createCollectionRegionAccessStrategy( this, accessType );
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,7 +53,6 @@ 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()
@ -60,16 +60,8 @@ public abstract class EhcacheDataRegion implements Region {
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 Ehcache cache;
private final EhcacheAccessStrategyFactory accessStrategyFactory;
private final int cacheLockTimeout;
@ -79,7 +71,7 @@ public abstract class EhcacheDataRegion implements Region {
EhcacheDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Properties properties) {
this.accessStrategyFactory = accessStrategyFactory;
this.cache = cache;
String timeout = properties.getProperty(
final String timeout = properties.getProperty(
CACHE_LOCK_TIMEOUT_PROPERTY,
Integer.toString( DEFAULT_CACHE_LOCK_TIMEOUT )
);
@ -87,18 +79,38 @@ public abstract class EhcacheDataRegion implements Region {
}
/**
* {@inheritDoc}
* Ehcache instance backing this Hibernate data region.
*/
public String getName() {
return cache.getName();
protected Ehcache getCache() {
return cache;
}
/**
* {@inheritDoc}
* The {@link org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory} used for creating
* various access strategies
*/
protected EhcacheAccessStrategyFactory getAccessStrategyFactory() {
return accessStrategyFactory;
}
/**
* Return the Ehcache instance backing this Hibernate data region.
*
* @return The underlying ehcache cache
*/
public Ehcache getEhcache() {
return getCache();
}
@Override
public String getName() {
return getCache().getName();
}
@Override
public void destroy() throws CacheException {
try {
cache.getCacheManager().removeCache( cache.getName() );
getCache().getCacheManager().removeCache( getCache().getName() );
}
catch (IllegalStateException e) {
//When Spring and Hibernate are both involved this will happen in normal shutdown operation.
@ -116,12 +128,10 @@ public abstract class EhcacheDataRegion implements Region {
}
}
/**
* {@inheritDoc}
*/
@Override
public long getSizeInMemory() {
try {
return cache.calculateInMemorySize();
return getCache().calculateInMemorySize();
}
catch (Throwable t) {
if ( t instanceof NonStopCacheException ) {
@ -132,12 +142,10 @@ public abstract class EhcacheDataRegion implements Region {
}
}
/**
* {@inheritDoc}
*/
@Override
public long getElementCountInMemory() {
try {
return cache.getMemoryStoreSize();
return getCache().getMemoryStoreSize();
}
catch (net.sf.ehcache.CacheException ce) {
if ( ce instanceof NonStopCacheException ) {
@ -151,12 +159,10 @@ public abstract class EhcacheDataRegion implements Region {
}
}
/**
* {@inheritDoc}
*/
@Override
public long getElementCountOnDisk() {
try {
return cache.getDiskStoreSize();
return getCache().getDiskStoreSize();
}
catch (net.sf.ehcache.CacheException ce) {
if ( ce instanceof NonStopCacheException ) {
@ -170,14 +176,12 @@ public abstract class EhcacheDataRegion implements Region {
}
}
/**
* {@inheritDoc}
*/
@Override
public Map toMap() {
try {
Map<Object, Object> result = new HashMap<Object, Object>();
for ( Object key : cache.getKeys() ) {
result.put( key, cache.get( key ).getObjectValue() );
final Map<Object, Object> result = new HashMap<Object, Object>();
for ( Object key : getCache().getKeys() ) {
result.put( key, getCache().get( key ).getObjectValue() );
}
return result;
}
@ -193,33 +197,19 @@ public abstract class EhcacheDataRegion implements Region {
}
}
/**
* {@inheritDoc}
*/
@Override
public long nextTimestamp() {
return Timestamper.next();
}
/**
* {@inheritDoc}
*/
@Override
public int getTimeout() {
return cacheLockTimeout;
}
/**
* Return the Ehcache instance backing this Hibernate data region.
*/
public Ehcache getEhcache() {
return cache;
@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 EhcacheEntityRegion around the given underlying cache.
* Constructs an EhcacheCollectionRegion around the given underlying cache.
*
* @param accessStrategyFactory
* @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) {
public EhcacheEntityRegion(
EhcacheAccessStrategyFactory accessStrategyFactory,
Ehcache underlyingCache,
Settings settings,
CacheDataDescription metadata,
Properties properties) {
super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
}
/**
* {@inheritDoc}
*/
@Override
public EntityRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
return accessStrategyFactory.createEntityRegionAccessStrategy( this, accessType );
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,22 +49,26 @@ 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()
);
/**
* Creates an EhcacheGeneralDataRegion using the given Ehcache instance as a backing.
* 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 cache, Properties properties) {
super( accessStrategyFactory, cache, properties );
public EhcacheGeneralDataRegion(
EhcacheAccessStrategyFactory accessStrategyFactory,
Ehcache underlyingCache,
Properties properties) {
super( accessStrategyFactory, underlyingCache, properties );
}
/**
* {@inheritDoc}
*/
@Override
public Object get(Object key) throws CacheException {
try {
LOG.debugf( "key: %s", key );
@ -71,7 +76,7 @@ abstract class EhcacheGeneralDataRegion extends EhcacheDataRegion implements Gen
return null;
}
else {
Element element = cache.get( key );
final Element element = getCache().get( key );
if ( element == null ) {
LOG.debugf( "Element for key %s is null", key );
return null;
@ -93,14 +98,12 @@ abstract class EhcacheGeneralDataRegion extends EhcacheDataRegion implements Gen
}
}
/**
* {@inheritDoc}
*/
@Override
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 );
final Element element = new Element( key, value );
getCache().put( element );
}
catch (IllegalArgumentException e) {
throw new CacheException( e );
@ -119,12 +122,10 @@ abstract class EhcacheGeneralDataRegion extends EhcacheDataRegion implements Gen
}
}
/**
* {@inheritDoc}
*/
@Override
public void evict(Object key) throws CacheException {
try {
cache.remove( key );
getCache().remove( key );
}
catch (ClassCastException e) {
throw new CacheException( e );
@ -143,12 +144,10 @@ abstract class EhcacheGeneralDataRegion extends EhcacheDataRegion implements Gen
}
}
/**
* {@inheritDoc}
*/
@Override
public void evictAll() throws CacheException {
try {
cache.removeAll();
getCache().removeAll();
}
catch (IllegalStateException e) {
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
* @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) {
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,13 +37,17 @@ 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) {
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,
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;
}
@ -134,11 +131,16 @@ 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) {
throw new CacheException( e );
@ -159,10 +161,14 @@ 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) {
throw new CacheException( e );
@ -183,10 +189,12 @@ 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) {
throw new CacheException( e );
@ -204,6 +212,10 @@ 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 {
@ -222,6 +234,10 @@ 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 {
@ -240,6 +256,10 @@ 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 {
@ -258,6 +278,10 @@ 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 {
@ -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,6 +147,7 @@ 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,13 +44,15 @@ import org.hibernate.cfg.Settings;
* @author Chris Dennis
* @author Alex Snaps
*/
abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransactionalDataRegion>
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();
@ -74,9 +76,9 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
public final Object get(Object key, long txTimestamp) throws CacheException {
readLockIfNeeded( key );
try {
Lockable item = (Lockable) region.get( key );
final Lockable item = (Lockable) region().get( key );
boolean readable = item != null && item.isReadable( txTimestamp );
final boolean readable = item != null && item.isReadable( txTimestamp );
if ( readable ) {
return item.getValue();
}
@ -97,14 +99,19 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
* @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)
public final boolean putFromLoad(
Object key,
Object value,
long txTimestamp,
Object version,
boolean minimalPutOverride)
throws CacheException {
region.writeLock( key );
region().writeLock( key );
try {
Lockable item = (Lockable) region.get( key );
boolean writeable = item == null || item.isWriteable( txTimestamp, version, versionComparator );
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() ) );
region().put( key, new Item( value, version, region().nextTimestamp() ) );
return true;
}
else {
@ -112,7 +119,7 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
}
}
finally {
region.writeUnlock( key );
region().writeUnlock( key );
}
}
@ -123,20 +130,20 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
* @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 );
region().writeLock( key );
try {
Lockable item = (Lockable) region.get( key );
long timeout = region.nextTimestamp() + region.getTimeout();
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 );
region().put( key, lock );
return lock;
}
finally {
region.writeUnlock( key );
region().writeUnlock( key );
}
}
@ -147,9 +154,9 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
* @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 );
region().writeLock( key );
try {
Lockable item = (Lockable) region.get( key );
final Lockable item = (Lockable) region().get( key );
if ( (item != null) && item.isUnlockable( lock ) ) {
decrementLock( key, (Lock) item );
@ -159,7 +166,7 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
}
}
finally {
region.writeUnlock( key );
region().writeUnlock( key );
}
}
@ -171,29 +178,29 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
* Unlock and re-put the given key, lock combination.
*/
protected void decrementLock(Object key, Lock lock) {
lock.unlock( region.nextTimestamp() );
region.put( key, lock );
lock.unlock( region().nextTimestamp() );
region().put( key, lock );
}
/**
* 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() );
LOG.softLockedCacheExpired( region().getName(), key, lock == null ? "(null)" : lock.toString() );
long ts = region.nextTimestamp() + region.getTimeout();
final long ts = region().nextTimestamp() + region().getTimeout();
// create new lock that times out immediately
Lock newLock = new Lock( ts, uuid, nextLockId.getAndIncrement(), null );
final Lock newLock = new Lock( ts, uuid, nextLockId.getAndIncrement(), null );
newLock.unlock( ts );
region.put( key, newLock );
region().put( key, newLock );
}
/**
* 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 );
if ( region().locksAreIndependentOfCache() ) {
region().readLock( key );
}
}
@ -201,8 +208,8 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
* 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 );
if ( region().locksAreIndependentOfCache() ) {
region().readUnlock( key );
}
}
@ -242,8 +249,7 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
/**
* Wrapper type representing unlocked items.
*/
protected final static class Item implements Serializable, Lockable {
protected static final class Item implements Serializable, Lockable {
private static final long serialVersionUID = 1L;
private final Object value;
private final Object version;
@ -258,37 +264,28 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
this.timestamp = timestamp;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isReadable(long txTimestamp) {
return txTimestamp > timestamp;
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) {
return version != null && versionComparator.compare( version, newVersion ) < 0;
}
/**
* {@inheritDoc}
*/
@Override
public Object getValue() {
return value;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isUnlockable(SoftLock lock) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public Lock lock(long timeout, UUID uuid, long lockId) {
return new Lock( timeout, uuid, lockId, version );
}
@ -297,8 +294,7 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
/**
* Wrapper type representing locked items.
*/
protected final static class Lock implements Serializable, Lockable, SoftLock {
protected static final class Lock implements Serializable, Lockable, SoftLock {
private static final long serialVersionUID = 2L;
private final UUID sourceUuid;
@ -320,16 +316,13 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
this.sourceUuid = sourceUuid;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isReadable(long txTimestamp) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings({"SimplifiableIfStatement", "unchecked"})
public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) {
if ( txTimestamp > timeout ) {
// if timedout then allow write
@ -339,30 +332,23 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
// if still locked then disallow write
return false;
}
return version == null ? txTimestamp > unlockTimestamp : versionComparator.compare(
version,
newVersion
) < 0;
return version == null
? txTimestamp > unlockTimestamp
: versionComparator.compare( version, newVersion ) < 0;
}
/**
* {@inheritDoc}
*/
@Override
public Object getValue() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isUnlockable(SoftLock lock) {
return equals( lock );
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("SimplifiableIfStatement")
public boolean equals(Object o) {
if ( o == this ) {
return true;
@ -375,12 +361,9 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int hash = ( sourceUuid != null ? sourceUuid.hashCode() : 0 );
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));
@ -395,9 +378,7 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
return concurrent;
}
/**
* {@inheritDoc}
*/
@Override
public Lock lock(long timeout, UUID uuid, long lockId) {
concurrent = true;
multiplicity++;
@ -414,13 +395,9 @@ abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransacti
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder( "Lock Source-UUID:" + sourceUuid + " Lock-ID:" + lockId );
return sb.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,
public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(
EhcacheCollectionRegion collectionRegion,
AccessType accessType);
/**
* Create {@link NaturalIdRegionAccessStrategy} for the input {@link org.hibernate.cache.ehcache.internal.regions.EhcacheNaturalIdRegion} and {@link AccessType}
* Create {@link NaturalIdRegionAccessStrategy} for the input {@link EhcacheNaturalIdRegion} and {@link AccessType}
*
* @param naturalIdRegion
* @param 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,
public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(
EhcacheNaturalIdRegion naturalIdRegion,
AccessType accessType);
}

View File

@ -47,10 +47,10 @@ public class EhcacheAccessStrategyFactoryImpl implements EhcacheAccessStrategyFa
EhcacheAccessStrategyFactoryImpl.class.getName()
);
/**
* {@inheritDoc}
*/
public EntityRegionAccessStrategy createEntityRegionAccessStrategy(EhcacheEntityRegion entityRegion, AccessType accessType) {
@Override
public EntityRegionAccessStrategy createEntityRegionAccessStrategy(
EhcacheEntityRegion entityRegion,
AccessType accessType) {
switch ( accessType ) {
case READ_ONLY:
if ( entityRegion.getCacheDataDescription().isMutable() ) {
@ -79,10 +79,9 @@ public class EhcacheAccessStrategyFactoryImpl implements EhcacheAccessStrategyFa
}
/**
* {@inheritDoc}
*/
public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(EhcacheCollectionRegion collectionRegion,
@Override
public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(
EhcacheCollectionRegion collectionRegion,
AccessType accessType) {
switch ( accessType ) {
case READ_ONLY:
@ -114,7 +113,8 @@ public class EhcacheAccessStrategyFactoryImpl implements EhcacheAccessStrategyFa
}
@Override
public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion naturalIdRegion,
public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(
EhcacheNaturalIdRegion naturalIdRegion,
AccessType accessType) {
switch ( accessType ) {
case READ_ONLY:

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.
*/
@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;
}
/**
* {@inheritDoc}
*/
@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;
}

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
*/
@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 );
region().put( key, value );
return true;
}
/**
* {@inheritDoc}
* <p/>
* Throws UnsupportedOperationException since this cache is read-only
*
* @throws UnsupportedOperationException always
*/
@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,21 +42,25 @@ 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.
*/
@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.
*/
@Override
public boolean afterInsert(Object key, Object value) 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, 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,18 +53,18 @@ 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) {
@ -72,25 +72,23 @@ public class TransactionalEhcacheCollectionRegionAccessStrategy
}
}
/**
* {@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;
@ -104,9 +102,6 @@ public class TransactionalEhcacheCollectionRegionAccessStrategy
}
}
/**
* {@inheritDoc}
*/
@Override
public void remove(Object key) throws CacheException {
try {
@ -117,9 +112,7 @@ public class TransactionalEhcacheCollectionRegionAccessStrategy
}
}
/**
* {@inheritDoc}
*/
@Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
// no-op
}

View File

@ -52,31 +52,28 @@ 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) {
@ -84,16 +81,12 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca
}
}
/**
* {@inheritDoc}
*/
@Override
public EntityRegion getRegion() {
return region;
return region();
}
/**
* {@inheritDoc}
*/
@Override
public boolean insert(Object key, Object value, Object version)
throws CacheException {
//OptimisticCache? versioning?
@ -106,18 +99,18 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca
}
}
/**
* {@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;
@ -131,9 +124,6 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca
}
}
/**
* {@inheritDoc}
*/
@Override
public void remove(Object key) throws CacheException {
try {
@ -144,17 +134,16 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca
}
}
/**
* {@inheritDoc}
*/
@Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
// no-op
}
/**
* {@inheritDoc}
*/
public boolean update(Object key, Object value, Object currentVersion,
@Override
public boolean update(
Object key,
Object value,
Object currentVersion,
Object previousVersion) throws CacheException {
try {
ehcache.put( new Element( key, value ) );

View File

@ -53,32 +53,28 @@ 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}
*/
@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) {
@ -86,16 +82,12 @@ public class TransactionalEhcacheNaturalIdRegionAccessStrategy
}
}
/**
* {@inheritDoc}
*/
@Override
public NaturalIdRegion getRegion() {
return region;
return region();
}
/**
* {@inheritDoc}
*/
@Override
public boolean insert(Object key, Object value) throws CacheException {
//OptimisticCache? versioning?
try {
@ -107,18 +99,18 @@ public class TransactionalEhcacheNaturalIdRegionAccessStrategy
}
}
/**
* {@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;
@ -132,9 +124,6 @@ public class TransactionalEhcacheNaturalIdRegionAccessStrategy
}
}
/**
* {@inheritDoc}
*/
@Override
public void remove(Object key) throws CacheException {
try {
@ -145,16 +134,12 @@ public class TransactionalEhcacheNaturalIdRegionAccessStrategy
}
}
/**
* {@inheritDoc}
*/
@Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
// no-op
}
/**
* {@inheritDoc}
*/
@Override
public boolean update(Object key, Object value) throws CacheException {
try {
ehcache.put( new Element( key, value ) );

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,31 +113,19 @@ 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 {
@ -156,24 +138,17 @@ public abstract class BaseEmitterBean extends StandardMBean implements Notificat
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,7 +88,7 @@ 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 );
@ -107,7 +99,7 @@ public class BeanUtils {
}
// then try fields
Field field = getField( bean, propertyName );
final Field field = getField( bean, propertyName );
if ( field != null ) {
try {
field.setAccessible( true );
@ -124,16 +116,16 @@ 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 );
}
@ -142,4 +134,7 @@ public class BeanUtils {
}
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 {
@ -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 );
@ -153,8 +158,11 @@ public class CacheRegionStats implements Serializable {
}
/**
* @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);
}
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() {
@ -282,6 +250,8 @@ public class CacheRegionStats implements Serializable {
}
/**
* 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;
@ -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" );
@ -143,8 +146,11 @@ public class CollectionStats implements Serializable {
}
/**
* @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,65 +182,47 @@ 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) {
@ -253,19 +231,26 @@ public class CollectionStats implements Serializable {
}
/**
* 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 );
@ -588,7 +588,7 @@ public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernat
}
/**
* @see BaseEmitterBean#getNotificationInfo()
* @see AbstractEmitterBean#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {

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;

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;
@ -680,7 +680,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
}
/**
* @see BaseEmitterBean#getNotificationInfo()
* @see AbstractEmitterBean#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {

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;

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,7 +43,7 @@ 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;
@ -321,7 +321,7 @@ public class HibernateStatsImpl extends BaseEmitterBean implements HibernateStat
}
/**
* @see BaseEmitterBean#getNotificationInfo()
* @see AbstractEmitterBean#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {

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;
@ -94,7 +95,8 @@ public class ProviderMBeanRegistrationHelper {
private final CacheManager manager;
private final Properties properties;
public RegisterMBeansTask(EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration,
public RegisterMBeansTask(
EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration,
CacheManager manager, Properties properties) {
this.ehcacheHibernateMBeanRegistration = ehcacheHibernateMBeanRegistration;
this.manager = manager;

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;

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;