HHH-11356 - Adjust the 2nd-Cache SPIs to better reflect supported uses

HHH-12323 - Update Statistics API and SPI based on changes to 2nd level caching changes
HHH-12416 - set up relocation for hibernate-ehcache
This commit is contained in:
Steve Ebersole 2018-03-21 14:57:57 -05:00
parent eea22fad17
commit dae31640a8
111 changed files with 96 additions and 10615 deletions

View File

@ -13,6 +13,7 @@ ext {
'documentation',
'hibernate-entitymanager',
'hibernate-infinispan',
'hibernate-ehcache',
'hibernate-java8',
'hibernate-orm-modules',
'release'
@ -43,15 +44,17 @@ dependencies {
testCompile( 'org.apache.commons:commons-lang3:3.4' )
testCompile( project(':hibernate-ehcache') )
testCompile( project(':hibernate-envers') )
testCompile( project(':hibernate-spatial') )
testCompile( project(path: ':hibernate-core', configuration: 'tests') )
testCompile( project(':hibernate-testing') )
testCompile "org.osgi:org.osgi.core:4.3.1"
testCompile( libraries.mockito )
testCompile( libraries.mockito_inline )
testRuntime( libraries.h2 )
testRuntime( libraries.hsqldb )
testRuntime( libraries.postgresql )
@ -59,7 +62,8 @@ dependencies {
testRuntime( libraries.mariadb )
testRuntime( libraries.mssql )
testCompile "org.osgi:org.osgi.core:4.3.1"
testCompile( project( ':hibernate-jcache' ) )
testRuntime( libraries.ehcache3 )
}
@ -264,6 +268,14 @@ task renderIntegrationGuide(type: AsciidoctorTask, group: 'Documentation') {
}
}
// Testing
// resources inherently exclude sources
sourceSets.test.resources {
setSrcDirs( ['src/test/java','src/test/resources'] )
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// grouping tasks
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

View File

@ -15,14 +15,11 @@ import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.hibernate.Session;
import org.hibernate.cache.ehcache.EhCacheRegionFactory;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.junit.Test;
import org.jboss.logging.Logger;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
@ -42,7 +39,7 @@ public class FirstLevelCacheTest extends BaseEntityManagerFunctionalTestCase {
@SuppressWarnings( "unchecked" )
protected void addConfigOptions(Map options) {
options.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, Boolean.TRUE.toString() );
options.put( AvailableSettings.CACHE_REGION_FACTORY, EhCacheRegionFactory.class.getName() );
options.put( AvailableSettings.CACHE_REGION_FACTORY, "jcache" );
}
@Test

View File

@ -9,6 +9,7 @@ package org.hibernate.userguide.caching;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.cache.configuration.MutableConfiguration;
import javax.persistence.Cacheable;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
@ -20,7 +21,7 @@ import javax.persistence.OneToMany;
import javax.persistence.Version;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.cache.ehcache.EhCacheRegionFactory;
import org.hibernate.cache.jcache.JCacheHelper;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
@ -36,7 +37,25 @@ import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
*/
public class NonStrictReadWriteCacheTest extends BaseEntityManagerFunctionalTestCase {
@Override
@Override
public void buildEntityManagerFactory() {
JCacheHelper.locateStandardCacheManager().createCache(
"hibernate.test.org.hibernate.userguide.caching.NonStrictReadWriteCacheTest$Person",
new MutableConfiguration<>()
);
JCacheHelper.locateStandardCacheManager().createCache(
"hibernate.test.org.hibernate.userguide.caching.NonStrictReadWriteCacheTest$Phone",
new MutableConfiguration<>()
);
JCacheHelper.locateStandardCacheManager().createCache(
"hibernate.test.org.hibernate.userguide.caching.NonStrictReadWriteCacheTest$Person.phones",
new MutableConfiguration<>()
);
super.buildEntityManagerFactory();
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
Person.class,
@ -48,7 +67,7 @@ public class NonStrictReadWriteCacheTest extends BaseEntityManagerFunctionalTest
@SuppressWarnings( "unchecked" )
protected void addConfigOptions(Map options) {
options.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, Boolean.TRUE.toString() );
options.put( AvailableSettings.CACHE_REGION_FACTORY, EhCacheRegionFactory.class.getName() );
options.put( AvailableSettings.CACHE_REGION_FACTORY, "jcache" );
}
@Test

View File

@ -22,7 +22,6 @@ import org.hibernate.CacheMode;
import org.hibernate.Session;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.NaturalId;
import org.hibernate.cache.ehcache.EhCacheRegionFactory;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.jpa.QueryHints;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
@ -54,7 +53,7 @@ public class SecondLevelCacheTest extends BaseEntityManagerFunctionalTestCase {
@SuppressWarnings( "unchecked" )
protected void addConfigOptions(Map options) {
options.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, Boolean.TRUE.toString() );
options.put( AvailableSettings.CACHE_REGION_FACTORY, EhCacheRegionFactory.class.getName() );
options.put( AvailableSettings.CACHE_REGION_FACTORY, "jcache" );
options.put( AvailableSettings.USE_QUERY_CACHE, Boolean.TRUE.toString() );
options.put( AvailableSettings.GENERATE_STATISTICS, Boolean.TRUE.toString() );
//options.put( AvailableSettings.CACHE_REGION_PREFIX, "" );

View File

@ -33,7 +33,7 @@ public class BasicTypeElementCollectionTest extends BaseEntityManagerFunctionalT
}
@Override
public void buildEntityManagerFactory() throws Exception {
public void buildEntityManagerFactory() {
super.buildEntityManagerFactory();
doInJPA( this::entityManagerFactory, entityManager -> {
Person person = new Person();

View File

@ -7,13 +7,15 @@
package org.hibernate.userguide.mapping.identifier;
import java.util.Map;
import javax.cache.configuration.MutableConfiguration;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.Id;
import org.hibernate.Session;
import org.hibernate.annotations.NaturalId;
import org.hibernate.annotations.NaturalIdCache;
import org.hibernate.cache.ehcache.EhCacheRegionFactory;
import org.hibernate.cache.jcache.JCacheHelper;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
@ -27,6 +29,16 @@ import static org.junit.Assert.assertEquals;
*/
public class CacheableNaturalIdTest extends BaseEntityManagerFunctionalTestCase {
@Override
public void buildEntityManagerFactory() {
JCacheHelper.locateStandardCacheManager().createCache( "org.hibernate.cache.spi.TimestampsRegion", new MutableConfiguration<>() );
JCacheHelper.locateStandardCacheManager().createCache( "org.hibernate.cache.spi.QueryResultsRegion", new MutableConfiguration<>() );
JCacheHelper.locateStandardCacheManager().createCache( "org.hibernate.userguide.mapping.identifier.CacheableNaturalIdTest$Book##NaturalId", new MutableConfiguration<>() );
// JCacheHelper.locateStandardCacheManager().createCache( "", new MutableConfiguration<>() );
super.buildEntityManagerFactory();
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
@ -38,7 +50,7 @@ public class CacheableNaturalIdTest extends BaseEntityManagerFunctionalTestCase
@SuppressWarnings( "unchecked" )
protected void addConfigOptions(Map options) {
options.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, Boolean.TRUE.toString() );
options.put( AvailableSettings.CACHE_REGION_FACTORY, EhCacheRegionFactory.class.getName() );
options.put( AvailableSettings.CACHE_REGION_FACTORY, "jcache" );
options.put( AvailableSettings.USE_QUERY_CACHE, Boolean.TRUE.toString() );
options.put( AvailableSettings.GENERATE_STATISTICS, Boolean.TRUE.toString() );
options.put( AvailableSettings.CACHE_REGION_PREFIX, "" );

View File

@ -8,6 +8,7 @@ package org.hibernate.userguide.persister;
import org.hibernate.MappingException;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.spi.access.CollectionDataAccess;
import org.hibernate.mapping.Collection;
import org.hibernate.persister.collection.OneToManyPersister;
import org.hibernate.persister.spi.PersisterCreationContext;
@ -22,7 +23,7 @@ public class CollectionPersister
public CollectionPersister(
Collection collectionBinding,
CollectionRegionAccessStrategy cacheAccessStrategy,
CollectionDataAccess cacheAccessStrategy,
PersisterCreationContext creationContext)
throws MappingException, CacheException {
super( collectionBinding, cacheAccessStrategy, creationContext );

View File

@ -7,6 +7,8 @@
package org.hibernate.userguide.persister;
import org.hibernate.HibernateException;
import org.hibernate.cache.spi.access.EntityDataAccess;
import org.hibernate.cache.spi.access.NaturalIdDataAccess;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.persister.entity.SingleTableEntityPersister;
import org.hibernate.persister.spi.PersisterCreationContext;
@ -21,8 +23,8 @@ public class EntityPersister
public EntityPersister(
PersistentClass persistentClass,
EntityRegionAccessStrategy cache,
NaturalIdRegionAccessStrategy naturalIdRegionAccessStrategy,
EntityDataAccess cache,
NaturalIdDataAccess naturalIdRegionAccessStrategy,
PersisterCreationContext creationContext)
throws HibernateException {
super( persistentClass, cache, naturalIdRegionAccessStrategy, creationContext );

View File

@ -21,6 +21,7 @@ import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.internal.FilterConfiguration;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.CollectionType;
@ -460,7 +461,7 @@ public abstract class Collection implements Fetchable, Value, Filterable {
}
public void setCacheRegionName(String cacheRegionName) {
this.cacheRegionName = cacheRegionName;
this.cacheRegionName = StringHelper.nullIfEmpty( cacheRegionName );
}

View File

@ -17,6 +17,7 @@ import org.hibernate.engine.spi.Mapping;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.SingletonIterator;
/**
@ -312,7 +313,7 @@ public class RootClass extends PersistentClass implements TableOwner {
}
public void setCacheRegionName(String cacheRegionName) {
this.cacheRegionName = cacheRegionName;
this.cacheRegionName = StringHelper.nullIfEmpty( cacheRegionName );
}
public boolean isLazyPropertiesCacheable() {

View File

@ -69,7 +69,7 @@ public abstract class BaseEntityManagerFunctionalTestCase extends BaseUnitTestCa
@Before
@SuppressWarnings( {"UnusedDeclaration"})
public void buildEntityManagerFactory() throws Exception {
public void buildEntityManagerFactory() {
log.trace( "Building EntityManagerFactory" );
entityManagerFactory = Bootstrap.getEntityManagerFactoryBuilder(

View File

@ -46,7 +46,7 @@ public abstract class AbstractCriteriaLiteralHandlingModeTest extends BaseEntity
}
@Override
public void buildEntityManagerFactory() throws Exception {
public void buildEntityManagerFactory() {
connectionProvider = new PreparedStatementSpyConnectionProvider();
super.buildEntityManagerFactory();
}

View File

@ -58,7 +58,7 @@ public class CriteriaLiteralsTest extends BaseEntityManagerFunctionalTestCase {
}
@Override
public void buildEntityManagerFactory() throws Exception {
public void buildEntityManagerFactory() {
connectionProvider = new PreparedStatementSpyConnectionProvider();
super.buildEntityManagerFactory();
}

View File

@ -49,7 +49,7 @@ public class EntityGraphWithFetchAnnotationTest
}
@Override
public void buildEntityManagerFactory() throws Exception {
public void buildEntityManagerFactory() {
connectionProvider = new PreparedStatementSpyConnectionProvider();
super.buildEntityManagerFactory();
}

View File

@ -58,7 +58,7 @@ public class NamedQueryCommentTest extends BaseEntityManagerFunctionalTestCase {
}
@Override
public void buildEntityManagerFactory() throws Exception {
public void buildEntityManagerFactory() {
connectionProvider = new PreparedStatementSpyConnectionProvider();
super.buildEntityManagerFactory();
}

View File

@ -35,7 +35,7 @@ public class EmbeddableWithOneToMany_HHH_11302_xml_Test extends
};
}
public void buildEntityManagerFactory() throws Exception {
public void buildEntityManagerFactory() {
try {
super.buildEntityManagerFactory();
fail( "Should throw AnnotationException!" );

View File

@ -35,7 +35,7 @@ public class LoaderWithInvalidQueryTest extends BaseEntityManagerFunctionalTestC
}
@Override
public void buildEntityManagerFactory() throws Exception {
public void buildEntityManagerFactory() {
try {
super.buildEntityManagerFactory();
}

View File

@ -40,7 +40,7 @@ public class SchemaMigratorHaltOnErrorTest extends BaseEntityManagerFunctionalTe
}
@Override
public void buildEntityManagerFactory() throws Exception {
public void buildEntityManagerFactory() {
try {
super.buildEntityManagerFactory();
fail("Should halt on error!");

View File

@ -37,7 +37,7 @@ public class SchemaUpdateProceedOnErrorTest extends BaseEntityManagerFunctionalT
}
@Override
public void buildEntityManagerFactory() throws Exception {
public void buildEntityManagerFactory() {
try {
super.buildEntityManagerFactory();
}

View File

@ -5,17 +5,31 @@
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
apply from: rootProject.file( 'gradle/published-java-module.gradle' )
apply from: rootProject.file( 'gradle/base-information.gradle' )
apply from: rootProject.file( 'gradle/publishing-repos.gradle' )
apply from: rootProject.file( 'gradle/publishing-pom.gradle' )
apply plugin: 'maven-publish'
apply plugin: 'maven-publish-auth'
description = 'Integration for Ehcache into Hibernate as a second-level caching service'
description = "(deprecated - use `org.hibernate:hibernate-jcache:${project.version}` + `org.ehcache:ehcache:3.0.0` instead)"
dependencies {
compile project( ':hibernate-core' )
compile( libraries.ehcache )
testCompile project( ':hibernate-testing' )
ext {
relocatedGroupId = 'org.hibernate'
relocatedArtifactId = 'hibernate-jcache'
relocatedVersion = project.version
}
test {
forkEvery 1
publishing {
publications {
publishedArtifacts {
pom.withXml {
def relocation = asNode().appendNode( 'distributionManagement' ).appendNode( 'relocation' )
relocation.appendNode( 'groupId', project.relocatedGroupId)
relocation.appendNode( 'artifactId', project.relocatedArtifactId )
relocation.appendNode( 'version', project.relocatedVersion )
}
}
}
}
task release( dependsOn: bintrayUpload )

View File

@ -1,219 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.nonstop.NonstopAccessStrategyFactory;
import org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion;
import org.hibernate.cache.ehcache.internal.regions.EhcacheEntityRegion;
import org.hibernate.cache.ehcache.internal.regions.EhcacheNaturalIdRegion;
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.management.impl.ProviderMBeanRegistrationHelper;
import org.hibernate.cache.spi.QueryResultsRegion;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.TimestampsRegion;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.service.spi.InjectService;
import org.jboss.logging.Logger;
/**
* Abstract implementation of an Ehcache specific RegionFactory.
*
* @author Chris Dennis
* @author Greg Luck
* @author Emmanuel Bernard
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
abstract class AbstractEhcacheRegionFactory implements RegionFactory {
/**
* The Hibernate system property specifying the location of the ehcache configuration file name.
* <p/>
* If not set, ehcache.xml will be looked for in the root of the classpath.
* <p/>
* If set to say ehcache-1.xml, ehcache-1.xml will be looked for in the root of the classpath.
*/
public static final String NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME = "net.sf.ehcache.configurationResourceName";
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
AbstractEhcacheRegionFactory.class.getName()
);
/**
* MBean registration helper class instance for Ehcache Hibernate MBeans.
*/
protected final ProviderMBeanRegistrationHelper mbeanRegistrationHelper = new ProviderMBeanRegistrationHelper();
/**
* Ehcache CacheManager that supplied Ehcache instances for this Hibernate RegionFactory.
*/
protected volatile CacheManager manager;
/**
* Settings object for the Hibernate persistence unit.
*/
protected SessionFactoryOptions settings;
/**
* {@link EhcacheAccessStrategyFactory} for creating various access strategies
*/
protected final EhcacheAccessStrategyFactory accessStrategyFactory =
new NonstopAccessStrategyFactory( new EhcacheAccessStrategyFactoryImpl() );
/**
* {@inheritDoc}
* <p/>
* In Ehcache we default to minimal puts since this should have minimal to no
* affect on unclustered users, and has great benefit for clustered users.
*
* @return true, optimize for minimal puts
*/
@Override
public boolean isMinimalPutsEnabledByDefault() {
return true;
}
@Override
public long nextTimestamp() {
return net.sf.ehcache.util.Timestamper.next();
}
@Override
public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
return new EhcacheEntityRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties );
}
@Override
public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
return new EhcacheNaturalIdRegion(
accessStrategyFactory,
getCache( regionName ),
settings,
metadata,
properties
);
}
@Override
public CollectionRegion buildCollectionRegion(
String regionName,
Properties properties,
CacheDataDescription metadata)
throws CacheException {
return new EhcacheCollectionRegion(
accessStrategyFactory,
getCache( regionName ),
settings,
metadata,
properties
);
}
@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;
@Override
public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException {
return new EhcacheTimestampsRegion( accessStrategyFactory, getCache( regionName ), properties );
}
private Ehcache getCache(String name) throws CacheException {
try {
Ehcache cache = manager.getEhcache( name );
if ( cache == null ) {
LOG.unableToFindEhCacheConfiguration( name );
manager.addCache( name );
cache = manager.getEhcache( name );
LOG.debug( "started EHCache region: " + name );
}
return cache;
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
/**
* Load a resource from the classpath.
*/
protected URL loadResource(String configurationResourceName) {
URL url = null;
if ( classLoaderService != null ) {
url = classLoaderService.locateResource( configurationResourceName );
}
if ( url == null ) {
final ClassLoader standardClassloader = Thread.currentThread().getContextClassLoader();
if ( standardClassloader != null ) {
url = standardClassloader.getResource( configurationResourceName );
}
if ( url == null ) {
url = AbstractEhcacheRegionFactory.class.getResource( configurationResourceName );
}
if ( url == null ) {
try {
url = new URL( configurationResourceName );
}
catch ( MalformedURLException e ) {
// ignore
}
}
}
if ( LOG.isDebugEnabled() ) {
LOG.debugf(
"Creating EhCacheRegionFactory from a specified resource: %s. Resolved to URL: %s",
configurationResourceName,
url
);
}
if ( url == null ) {
LOG.unableToLoadConfiguration( configurationResourceName );
}
return url;
}
/**
* Default access-type used when the configured using JPA 2.0 config. JPA 2.0 allows <code>@Cacheable(true)</code> to be attached to an
* entity without any access type or usage qualification.
* <p/>
* We are conservative here in specifying {@link AccessType#READ_WRITE} so as to follow the mantra of "do no harm".
* <p/>
* This is a Hibernate 3.5 method.
*/
public AccessType getDefaultAccessType() {
return AccessType.READ_WRITE;
}
}

View File

@ -1,119 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache;
import org.hibernate.internal.CoreMessageLogger;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import static org.jboss.logging.Logger.Level.WARN;
/**
* The jboss-logging {@link MessageLogger} for the hibernate-ehcache module. It reserves message ids ranging from
* 20001 to 25000 inclusively.
* <p/>
* New messages must be added after the last message defined to ensure message codes are unique.
*/
@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 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
)
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
)
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
)
void softLockedCacheExpired(String regionName, Object key, String lock);
}

View File

@ -1,109 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache;
import java.net.URL;
import java.util.Properties;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.Configuration;
import net.sf.ehcache.config.ConfigurationFactory;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.util.HibernateEhcacheUtils;
import org.jboss.logging.Logger;
/**
* A non-singleton EhCacheRegionFactory implementation.
*
* @author Chris Dennis
* @author Greg Luck
* @author Emmanuel Bernard
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
EhCacheRegionFactory.class.getName()
);
/**
* 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();
}
@Override
public void start(SessionFactoryOptions settings, Properties properties) throws CacheException {
this.settings = settings;
if ( manager != null ) {
LOG.attemptToRestartAlreadyStartedEhCacheProvider();
return;
}
try {
String configurationResourceName = null;
if ( properties != null ) {
configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME );
}
if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
final Configuration configuration = ConfigurationFactory.parseConfiguration();
manager = new CacheManager( configuration );
}
else {
final URL url = loadResource( configurationResourceName );
final Configuration configuration = HibernateEhcacheUtils.loadAndCorrectConfiguration( url );
manager = new CacheManager( configuration );
}
mbeanRegistrationHelper.registerMBean( manager, properties );
}
catch (net.sf.ehcache.CacheException e) {
if ( e.getMessage().startsWith(
"Cannot parseConfiguration CacheManager. Attempt to create a new instance of " +
"CacheManager using the diskStorePath"
) ) {
throw new CacheException(
"Attempt to restart an already started EhCacheRegionFactory. " +
"Use sessionFactory.close() between repeated calls to buildSessionFactory. " +
"Consider using SingletonEhCacheRegionFactory. Error from ehcache was: " + e.getMessage()
);
}
else {
throw new CacheException( e );
}
}
}
@Override
public void stop() {
try {
if ( manager != null ) {
mbeanRegistrationHelper.unregisterMBean();
manager.shutdown();
manager = null;
}
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
}

View File

@ -1,108 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.Configuration;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.util.HibernateEhcacheUtils;
import org.jboss.logging.Logger;
/**
* A singleton EhCacheRegionFactory implementation.
*
* @author Chris Dennis
* @author Greg Luck
* @author Emmanuel Bernard
* @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();
/**
* Constructs a SingletonEhCacheRegionFactory
*/
@SuppressWarnings("UnusedDeclaration")
public SingletonEhCacheRegionFactory() {
}
/**
* Constructs a SingletonEhCacheRegionFactory
*
* @param prop Not used
*/
@SuppressWarnings("UnusedDeclaration")
public SingletonEhCacheRegionFactory(Properties prop) {
super();
}
@Override
public void start(SessionFactoryOptions settings, Properties properties) throws CacheException {
this.settings = settings;
try {
String configurationResourceName = null;
if ( properties != null ) {
configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME );
}
if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
manager = CacheManager.create();
REFERENCE_COUNT.incrementAndGet();
}
else {
URL url;
try {
url = new URL( configurationResourceName );
}
catch (MalformedURLException e) {
if ( !configurationResourceName.startsWith( "/" ) ) {
configurationResourceName = "/" + configurationResourceName;
LOG.debugf(
"prepending / to %s. It should be placed in the root of the classpath rather than in a package.",
configurationResourceName
);
}
url = loadResource( configurationResourceName );
}
final Configuration configuration = HibernateEhcacheUtils.loadAndCorrectConfiguration( url );
manager = CacheManager.create( configuration );
REFERENCE_COUNT.incrementAndGet();
}
mbeanRegistrationHelper.registerMBean( manager, properties );
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
@Override
public void stop() {
try {
if ( manager != null ) {
if ( REFERENCE_COUNT.decrementAndGet() == 0 ) {
manager.shutdown();
}
manager = null;
}
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
}

View File

@ -1,55 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
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.cache.spi.RegionFactory;
/**
* Makes the 2 contained region factory implementations available to the Hibernate
* {@link org.hibernate.boot.registry.selector.spi.StrategySelector} service.
*
* @author Steve Ebersole
*/
public class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider {
@Override
@SuppressWarnings("unchecked")
public Iterable<StrategyRegistration> getStrategyRegistrations() {
final List<StrategyRegistration> strategyRegistrations = new ArrayList<StrategyRegistration>();
strategyRegistrations.add(
new SimpleStrategyRegistrationImpl(
RegionFactory.class,
EhCacheRegionFactory.class,
"ehcache",
EhCacheRegionFactory.class.getName(),
EhCacheRegionFactory.class.getSimpleName(),
// legacy impl class name
"org.hibernate.cache.EhCacheRegionFactory"
)
);
strategyRegistrations.add(
new SimpleStrategyRegistrationImpl(
RegionFactory.class,
SingletonEhCacheRegionFactory.class,
"ehcache-singleton",
SingletonEhCacheRegionFactory.class.getName(),
SingletonEhCacheRegionFactory.class.getSimpleName(),
// legacy impl class name
"org.hibernate.cache.SingletonEhCacheRegionFactory"
)
);
return strategyRegistrations;
}
}

View File

@ -1,79 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.nonstop;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
import org.hibernate.cache.ehcache.EhCacheMessageLogger;
import org.jboss.logging.Logger;
/**
* Class that takes care of {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException} that happens in hibernate module
*
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
public final class HibernateNonstopCacheExceptionHandler {
/**
* Property name which set as "true" will throw exceptions on timeout with hibernate
*/
public static final String HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY = "ehcache.hibernate.propagateNonStopCacheException";
/**
* Property name for logging the stack trace of the nonstop cache exception too. False by default
*/
public static final String HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY = "ehcache.hibernate.logNonStopCacheExceptionStackTrace";
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
HibernateNonstopCacheExceptionHandler.class.getName()
);
private static final HibernateNonstopCacheExceptionHandler INSTANCE = new HibernateNonstopCacheExceptionHandler();
/**
* private constructor
*/
private HibernateNonstopCacheExceptionHandler() {
// private
}
/**
* Returns the singleton instance
*
* @return the singleton instance
*/
public static HibernateNonstopCacheExceptionHandler getInstance() {
return INSTANCE;
}
/**
* Handle {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}.
* If {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY} system property is set to true,
* rethrows the {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}, otherwise logs the exception. While logging, if
* {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY} is set to true, logs the exception stack
* trace too, otherwise logs the exception message only
*
* @param nonStopCacheException The exception to handle
*/
public void handleNonstopCacheException(NonStopCacheException nonStopCacheException) {
if ( Boolean.getBoolean( HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY ) ) {
throw nonStopCacheException;
}
else {
if ( Boolean.getBoolean( HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY ) ) {
LOG.debug(
"Ignoring NonstopCacheException - " + nonStopCacheException.getMessage(),
nonStopCacheException
);
}
else {
LOG.debug( "Ignoring NonstopCacheException - " + nonStopCacheException.getMessage() );
}
}
}
}

View File

@ -1,69 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.nonstop;
import org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion;
import org.hibernate.cache.ehcache.internal.regions.EhcacheEntityRegion;
import org.hibernate.cache.ehcache.internal.regions.EhcacheNaturalIdRegion;
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory;
import org.hibernate.cache.spi.access.AccessType;
/**
* Implementation of {@link org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory} that takes care of Nonstop cache exceptions using
* {@link HibernateNonstopCacheExceptionHandler}
*
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
public class NonstopAccessStrategyFactory implements EhcacheAccessStrategyFactory {
private final EhcacheAccessStrategyFactory actualFactory;
/**
* Constructor accepting the actual factory
*
* @param actualFactory The wrapped RegionAccessStrategy factory
*/
public NonstopAccessStrategyFactory(EhcacheAccessStrategyFactory actualFactory) {
this.actualFactory = actualFactory;
}
@Override
public EntityRegionAccessStrategy createEntityRegionAccessStrategy(
EhcacheEntityRegion entityRegion,
AccessType accessType) {
return new NonstopAwareEntityRegionAccessStrategy(
actualFactory.createEntityRegionAccessStrategy( entityRegion, accessType ),
HibernateNonstopCacheExceptionHandler.getInstance()
);
}
@Override
public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(
EhcacheNaturalIdRegion naturalIdRegion,
AccessType accessType) {
return new NonstopAwareNaturalIdRegionAccessStrategy(
actualFactory.createNaturalIdRegionAccessStrategy(
naturalIdRegion,
accessType
), HibernateNonstopCacheExceptionHandler.getInstance()
);
}
@Override
public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(
EhcacheCollectionRegion collectionRegion,
AccessType accessType) {
return new NonstopAwareCollectionRegionAccessStrategy(
actualFactory.createCollectionRegionAccessStrategy(
collectionRegion,
accessType
), HibernateNonstopCacheExceptionHandler.getInstance()
);
}
}

View File

@ -1,171 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.nonstop;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.collection.CollectionPersister;
/**
* Implementation of {@link CollectionRegionAccessStrategy} that handles {@link NonStopCacheException} using
* {@link HibernateNonstopCacheExceptionHandler}
*
* @author Abhishek Sanoujam
* @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 The wrapped strategy
* @param hibernateNonstopExceptionHandler The exception handler
*/
public NonstopAwareCollectionRegionAccessStrategy(
CollectionRegionAccessStrategy actualStrategy,
HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
this.actualStrategy = actualStrategy;
this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler;
}
@Override
public CollectionRegion getRegion() {
return actualStrategy.getRegion();
}
@Override
public void evict(Object key) throws CacheException {
try {
actualStrategy.evict( key );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public void evictAll() throws CacheException {
try {
actualStrategy.evictAll();
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public Object get(SharedSessionContractImplementor session, Object key, long txTimestamp) throws CacheException {
try {
return actualStrategy.get( session, key, txTimestamp );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
@Override
public SoftLock lockItem(SharedSessionContractImplementor session, Object key, Object version) throws CacheException {
try {
return actualStrategy.lockItem( session, key, version );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
@Override
public SoftLock lockRegion() throws CacheException {
try {
return actualStrategy.lockRegion();
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
@Override
public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
try {
return actualStrategy.putFromLoad( session, key, value, txTimestamp, version, minimalPutOverride );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
@Override
public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version) throws CacheException {
try {
return actualStrategy.putFromLoad( session, key, value, txTimestamp, version );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
@Override
public void remove(SharedSessionContractImplementor session, Object key) throws CacheException {
try {
actualStrategy.remove( session, key);
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public void removeAll() throws CacheException {
try {
actualStrategy.removeAll();
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException {
try {
actualStrategy.unlockItem( session, key, lock );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public void unlockRegion(SoftLock lock) throws CacheException {
try {
actualStrategy.unlockRegion( lock );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public Object generateCacheKey(Object id, CollectionPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) {
return DefaultCacheKeysFactory.staticCreateCollectionKey( id, persister, factory, tenantIdentifier );
}
@Override
public Object getCacheKeyId(Object cacheKey) {
return DefaultCacheKeysFactory.staticGetCollectionId(cacheKey);
}
}

View File

@ -1,217 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.nonstop;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
* Implementation of {@link EntityRegionAccessStrategy} that handles {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException} using
* {@link HibernateNonstopCacheExceptionHandler}
*
* @author Abhishek Sanoujam
* @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 The wrapped EntityRegionAccessStrategy
* @param hibernateNonstopExceptionHandler The exception handler
*/
public NonstopAwareEntityRegionAccessStrategy(
EntityRegionAccessStrategy actualStrategy,
HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
this.actualStrategy = actualStrategy;
this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler;
}
@Override
public EntityRegion getRegion() {
return actualStrategy.getRegion();
}
@Override
public boolean afterInsert(SharedSessionContractImplementor session, Object key, Object value, Object version) throws CacheException {
try {
return actualStrategy.afterInsert( session, key, value, version );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
@Override
public boolean afterUpdate(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock)
throws CacheException {
try {
return actualStrategy.afterUpdate( session, key, value, currentVersion, previousVersion, lock );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
@Override
public void evict(Object key) throws CacheException {
try {
actualStrategy.evict( key );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public void evictAll() throws CacheException {
try {
actualStrategy.evictAll();
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public Object get(SharedSessionContractImplementor session, Object key, long txTimestamp) throws CacheException {
try {
return actualStrategy.get( session, key, txTimestamp );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
@Override
public boolean insert(SharedSessionContractImplementor session, Object key, Object value, Object version) throws CacheException {
try {
return actualStrategy.insert( session, key, value, version);
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
@Override
public SoftLock lockItem(SharedSessionContractImplementor session, Object key, Object version) throws CacheException {
try {
return actualStrategy.lockItem( session, key, version );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
@Override
public SoftLock lockRegion() throws CacheException {
try {
return actualStrategy.lockRegion();
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
@Override
public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
try {
return actualStrategy.putFromLoad( session, key, value, txTimestamp, version, minimalPutOverride );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
@Override
public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version) throws CacheException {
try {
return actualStrategy.putFromLoad( session, key, value, txTimestamp, version );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
@Override
public void remove(SharedSessionContractImplementor session, Object key) throws CacheException {
try {
actualStrategy.remove( session, key);
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public void removeAll() throws CacheException {
try {
actualStrategy.removeAll();
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException {
try {
actualStrategy.unlockItem( session, key, lock );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public void unlockRegion(SoftLock lock) throws CacheException {
try {
actualStrategy.unlockRegion( lock );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public boolean update(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion)
throws CacheException {
try {
return actualStrategy.update( session, key, value, currentVersion, previousVersion );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
@Override
public Object generateCacheKey(Object id, EntityPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) {
return DefaultCacheKeysFactory.staticCreateEntityKey( id, persister, factory, tenantIdentifier );
}
@Override
public Object getCacheKeyId(Object cacheKey) {
return DefaultCacheKeysFactory.staticGetEntityId(cacheKey);
}
}

View File

@ -1,214 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.nonstop;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
* Implementation of {@link NaturalIdRegionAccessStrategy} that handles {@link NonStopCacheException} using
* {@link HibernateNonstopCacheExceptionHandler}
*
* @author Abhishek Sanoujam
* @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 The wrapped NaturalIdRegionAccessStrategy
* @param hibernateNonstopExceptionHandler The exception handler
*/
public NonstopAwareNaturalIdRegionAccessStrategy(
NaturalIdRegionAccessStrategy actualStrategy,
HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
this.actualStrategy = actualStrategy;
this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler;
}
@Override
public boolean insert(SharedSessionContractImplementor session, Object key, Object value) throws CacheException {
try {
return actualStrategy.insert( session, key, value );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
@Override
public boolean afterInsert(SharedSessionContractImplementor session, Object key, Object value) throws CacheException {
try {
return actualStrategy.afterInsert( session, key, value );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
@Override
public boolean update(SharedSessionContractImplementor session, Object key, Object value) throws CacheException {
try {
return actualStrategy.update( session, key, value );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
@Override
public boolean afterUpdate(SharedSessionContractImplementor session, Object key, Object value, SoftLock lock) throws CacheException {
try {
return actualStrategy.afterUpdate( session, key, value, lock);
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
@Override
public NaturalIdRegion getRegion() {
return actualStrategy.getRegion();
}
@Override
public void evict(Object key) throws CacheException {
try {
actualStrategy.evict( key );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public void evictAll() throws CacheException {
try {
actualStrategy.evictAll();
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public Object get(SharedSessionContractImplementor session, Object key, long txTimestamp) throws CacheException {
try {
return actualStrategy.get( session, key, txTimestamp );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
@Override
public SoftLock lockItem(SharedSessionContractImplementor session, Object key, Object version) throws CacheException {
try {
return actualStrategy.lockItem( session, key, version );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
@Override
public SoftLock lockRegion() throws CacheException {
try {
return actualStrategy.lockRegion();
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
@Override
public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
try {
return actualStrategy.putFromLoad( session, key, value, txTimestamp, version, minimalPutOverride );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
@Override
public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version) throws CacheException {
try {
return actualStrategy.putFromLoad( session, key, value, txTimestamp, version );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
@Override
public void remove(SharedSessionContractImplementor session, Object key) throws CacheException {
try {
actualStrategy.remove( session, key );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public void removeAll() throws CacheException {
try {
actualStrategy.removeAll();
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException {
try {
actualStrategy.unlockItem( session, key, lock );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public void unlockRegion(SoftLock lock) throws CacheException {
try {
actualStrategy.unlockRegion( lock );
}
catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
@Override
public Object generateCacheKey(Object[] naturalIdValues, EntityPersister persister, SharedSessionContractImplementor session) {
return DefaultCacheKeysFactory.staticCreateNaturalIdKey( naturalIdValues, persister, session );
}
@Override
public Object[] getNaturalIdValues(Object cacheKey) {
return DefaultCacheKeysFactory.staticGetNaturalIdValues(cacheKey);
}
}

View File

@ -1,12 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
/**
* 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

@ -1,52 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.regions;
import java.util.Properties;
import net.sf.ehcache.Ehcache;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory;
import org.hibernate.cache.spi.access.AccessType;
/**
* A collection region specific wrapper around an Ehcache instance.
* <p/>
* This implementation returns Ehcache specific access strategy instances for all the non-transactional access types. Transactional access
* is not supported.
*
* @author Chris Dennis
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
public class EhcacheCollectionRegion extends EhcacheTransactionalDataRegion implements CollectionRegion {
/**
* Constructs an EhcacheCollectionRegion around the given underlying cache.
*
* @param accessStrategyFactory The factory for building needed CollectionRegionAccessStrategy instance
* @param underlyingCache The ehcache cache instance
* @param settings The Hibernate settings
* @param metadata Metadata about the data to be cached in this region
* @param properties Any additional[ properties
*/
public EhcacheCollectionRegion(
EhcacheAccessStrategyFactory accessStrategyFactory,
Ehcache underlyingCache,
SessionFactoryOptions settings,
CacheDataDescription metadata,
Properties properties) {
super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
}
@Override
public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
return getAccessStrategyFactory().createCollectionRegionAccessStrategy( this, accessType );
}
}

View File

@ -1,198 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.regions;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
import net.sf.ehcache.util.Timestamper;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.EhCacheMessageLogger;
import org.hibernate.cache.ehcache.internal.nonstop.HibernateNonstopCacheExceptionHandler;
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory;
import org.hibernate.cache.spi.Region;
import org.jboss.logging.Logger;
/**
* An Ehcache specific data region implementation.
* <p/>
* This class is the ultimate superclass for all Ehcache Hibernate cache regions.
*
* @author Chris Dennis
* @author Greg Luck
* @author Emmanuel Bernard
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
public abstract class EhcacheDataRegion implements Region {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
EhcacheDataRegion.class.getName()
);
private static final String CACHE_LOCK_TIMEOUT_PROPERTY = "net.sf.ehcache.hibernate.cache_lock_timeout";
private static final int DEFAULT_CACHE_LOCK_TIMEOUT = 60000;
private final Ehcache cache;
private final EhcacheAccessStrategyFactory accessStrategyFactory;
private final int cacheLockTimeout;
/**
* Create a Hibernate data region backed by the given Ehcache instance.
*/
EhcacheDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Properties properties) {
this.accessStrategyFactory = accessStrategyFactory;
this.cache = cache;
final String timeout = properties.getProperty(
CACHE_LOCK_TIMEOUT_PROPERTY,
Integer.toString( DEFAULT_CACHE_LOCK_TIMEOUT )
);
this.cacheLockTimeout = Timestamper.ONE_MS * Integer.decode( timeout );
}
/**
* Ehcache instance backing this Hibernate data region.
*/
protected Ehcache getCache() {
return cache;
}
/**
* 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 {
getCache().getCacheManager().removeCache( getCache().getName() );
}
catch (IllegalStateException e) {
//When Spring and Hibernate are both involved this will happen in normal shutdown operation.
//Do not throw an exception, simply log this one.
LOG.debug( "This can happen if multiple frameworks both try to shutdown ehcache", e );
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
@Override
public long getSizeInMemory() {
try {
return getCache().calculateInMemorySize();
}
catch (Throwable t) {
if ( t instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) t );
}
return -1;
}
}
@Override
public long getElementCountInMemory() {
try {
return getCache().getMemoryStoreSize();
}
catch (net.sf.ehcache.CacheException ce) {
if ( ce instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) ce );
return -1;
}
else {
throw new CacheException( ce );
}
}
}
@Override
public long getElementCountOnDisk() {
try {
return getCache().getDiskStoreSize();
}
catch (net.sf.ehcache.CacheException ce) {
if ( ce instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) ce );
return -1;
}
else {
throw new CacheException( ce );
}
}
}
@Override
public Map toMap() {
try {
final Map<Object, Object> result = new HashMap<Object, Object>();
for ( Object key : getCache().getKeys() ) {
result.put( key, getCache().get( key ).getObjectValue() );
}
return result;
}
catch (Exception e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
return Collections.emptyMap();
}
else {
throw new CacheException( e );
}
}
}
@Override
public long nextTimestamp() {
return Timestamper.next();
}
@Override
public int getTimeout() {
return cacheLockTimeout;
}
@Override
public boolean contains(Object key) {
return getCache().isKeyInCache( key );
}
}

View File

@ -1,51 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.regions;
import java.util.Properties;
import net.sf.ehcache.Ehcache;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory;
import org.hibernate.cache.spi.access.AccessType;
/**
* An entity region specific wrapper around an Ehcache instance.
* <p/>
* This implementation returns Ehcache specific access strategy instances for all the non-transactional access types. Transactional access
* is not supported.
*
* @author Chris Dennis
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
public class EhcacheEntityRegion extends EhcacheTransactionalDataRegion implements EntityRegion {
/**
* Constructs an EhcacheCollectionRegion around the given underlying cache.
*
* @param accessStrategyFactory The factory for building needed EntityRegionAccessStrategy instance
* @param underlyingCache The ehcache cache instance
* @param settings The Hibernate settings
* @param metadata Metadata about the data to be cached in this region
* @param properties Any additional[ properties
*/
public EhcacheEntityRegion(
EhcacheAccessStrategyFactory accessStrategyFactory,
Ehcache underlyingCache,
SessionFactoryOptions settings,
CacheDataDescription metadata,
Properties properties) {
super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
}
@Override
public EntityRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
return getAccessStrategyFactory().createEntityRegionAccessStrategy( this, accessType );
}
}

View File

@ -1,148 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.regions;
import java.util.Properties;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.EhCacheMessageLogger;
import org.hibernate.cache.ehcache.internal.nonstop.HibernateNonstopCacheExceptionHandler;
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.jboss.logging.Logger;
/**
* An Ehcache specific GeneralDataRegion.
* <p/>
* GeneralDataRegion instances are used for both the timestamps and query caches.
*
* @author Chris Dennis
* @author Greg Luck
* @author Emmanuel Bernard
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
abstract class EhcacheGeneralDataRegion extends EhcacheDataRegion implements GeneralDataRegion {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
EhcacheGeneralDataRegion.class.getName()
);
/**
* Constructs an EhcacheGeneralDataRegion around the given underlying cache.
*
* @param accessStrategyFactory The factory for building needed RegionAccessStrategy instance
* @param underlyingCache The ehcache cache instance
* @param properties Any additional[ properties
*/
public EhcacheGeneralDataRegion(
EhcacheAccessStrategyFactory accessStrategyFactory,
Ehcache underlyingCache,
Properties properties) {
super( accessStrategyFactory, underlyingCache, properties );
}
@Override
public Object get(SharedSessionContractImplementor session, Object key) throws CacheException {
try {
LOG.debugf( "key: %s", key );
if ( key == null ) {
return null;
}
else {
final Element element = getCache().get( key );
if ( element == null ) {
LOG.debugf( "Element for key %s is null", key );
return null;
}
else {
return element.getObjectValue();
}
}
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
return null;
}
else {
throw new CacheException( e );
}
}
}
@Override
public void put(SharedSessionContractImplementor session, Object key, Object value) throws CacheException {
LOG.debugf( "key: %s value: %s", key, value );
try {
final Element element = new Element( key, value );
getCache().put( element );
}
catch (IllegalArgumentException e) {
throw new CacheException( e );
}
catch (IllegalStateException e) {
throw new CacheException( e );
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
@Override
public void evict(Object key) throws CacheException {
try {
getCache().remove( key );
}
catch (ClassCastException e) {
throw new CacheException( e );
}
catch (IllegalStateException e) {
throw new CacheException( e );
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
@Override
public void evictAll() throws CacheException {
try {
getCache().removeAll();
}
catch (IllegalStateException e) {
throw new CacheException( e );
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
}

View File

@ -1,52 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.regions;
import java.util.Properties;
import net.sf.ehcache.Ehcache;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory;
import org.hibernate.cache.spi.access.AccessType;
/**
* A collection region specific wrapper around an Ehcache instance.
* <p/>
* This implementation returns Ehcache specific access strategy instances for all the non-transactional access types. Transactional access
* is not supported.
*
* @author Chris Dennis
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
public class EhcacheNaturalIdRegion extends EhcacheTransactionalDataRegion implements NaturalIdRegion {
/**
* Constructs an EhcacheNaturalIdRegion around the given underlying cache.
*
* @param accessStrategyFactory The factory for building needed NaturalIdRegionAccessStrategy instance
* @param underlyingCache The ehcache cache instance
* @param settings The Hibernate settings
* @param metadata Metadata about the data to be cached in this region
* @param properties Any additional[ properties
*/
public EhcacheNaturalIdRegion(
EhcacheAccessStrategyFactory accessStrategyFactory,
Ehcache underlyingCache,
SessionFactoryOptions settings,
CacheDataDescription metadata,
Properties properties) {
super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
}
@Override
public NaturalIdRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
return getAccessStrategyFactory().createNaturalIdRegionAccessStrategy( this, accessType );
}
}

View File

@ -1,37 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.regions;
import java.util.Properties;
import net.sf.ehcache.Ehcache;
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory;
import org.hibernate.cache.spi.QueryResultsRegion;
/**
* A query results region specific wrapper around an Ehcache instance.
*
* @author Chris Dennis
* @author Alex Snaps
*/
public class EhcacheQueryResultsRegion extends EhcacheGeneralDataRegion implements QueryResultsRegion {
/**
* Constructs an EhcacheQueryResultsRegion around the given underlying cache.
*
* @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) {
super( accessStrategyFactory, underlyingCache, properties );
}
}

View File

@ -1,37 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.regions;
import java.util.Properties;
import net.sf.ehcache.Ehcache;
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory;
import org.hibernate.cache.spi.TimestampsRegion;
/**
* A timestamps region specific wrapper around an Ehcache instance.
*
* @author Chris Dennis
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
public class EhcacheTimestampsRegion extends EhcacheGeneralDataRegion implements TimestampsRegion {
/**
* Constructs an EhcacheTimestampsRegion around the given underlying cache.
*
* @param accessStrategyFactory The factory for building needed CollectionRegionAccessStrategy instance
* @param underlyingCache The ehcache cache instance
* @param properties Any additional[ properties
*/
public EhcacheTimestampsRegion(
EhcacheAccessStrategyFactory accessStrategyFactory,
Ehcache underlyingCache,
Properties properties) {
super( accessStrategyFactory, underlyingCache, properties );
}
}

View File

@ -1,293 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.regions;
import java.util.Properties;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.concurrent.CacheLockProvider;
import net.sf.ehcache.concurrent.LockType;
import net.sf.ehcache.concurrent.StripedReadWriteLockSync;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.nonstop.HibernateNonstopCacheExceptionHandler;
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory;
/**
* An Ehcache specific TransactionalDataRegion.
* <p/>
* This is the common superclass entity and collection regions.
*
* @author Chris Dennis
* @author Greg Luck
* @author Emmanuel Bernard
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements TransactionalDataRegion {
private static final int LOCAL_LOCK_PROVIDER_CONCURRENCY = 128;
private final SessionFactoryOptions settings;
/**
* Metadata associated with the objects stored in the region.
*/
protected final CacheDataDescription metadata;
private final CacheLockProvider lockProvider;
/**
* Construct a transactional Hibernate cache region around the given Ehcache instance.
*/
EhcacheTransactionalDataRegion(
EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, SessionFactoryOptions settings,
CacheDataDescription metadata, Properties properties) {
super( accessStrategyFactory, cache, properties );
this.settings = settings;
this.metadata = metadata;
final Object context = cache.getInternalContext();
if ( context instanceof CacheLockProvider ) {
this.lockProvider = (CacheLockProvider) context;
}
else {
this.lockProvider = new StripedReadWriteLockSync( LOCAL_LOCK_PROVIDER_CONCURRENCY );
}
}
/**
* Access the Hibernate settings associated with the persistence unit.
*
* @return settings
*/
public SessionFactoryOptions getSettings() {
return settings;
}
@Override
public boolean isTransactionAware() {
return false;
}
@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 {
final Element element = getCache().get( key );
if ( element == null ) {
return null;
}
else {
return element.getObjectValue();
}
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
return null;
}
else {
throw new CacheException( e );
}
}
}
/**
* 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 {
final Element element = new Element( key, value );
getCache().put( element );
}
catch (IllegalArgumentException e) {
throw new CacheException( e );
}
catch (IllegalStateException e) {
throw new CacheException( e );
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
/**
* 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 {
getCache().remove( key );
}
catch (ClassCastException e) {
throw new CacheException( e );
}
catch (IllegalStateException e) {
throw new CacheException( e );
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
/**
* Remove all mapping from this cache region.
*
* @throws CacheException Indicates a problem accessing the cache
*/
public final void clear() throws CacheException {
try {
getCache().removeAll();
}
catch (IllegalStateException e) {
throw new CacheException( e );
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
/**
* 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) throws CacheException {
try {
lockProvider.getSyncForKey( key ).lock( LockType.WRITE );
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
/**
* 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) throws CacheException {
try {
lockProvider.getSyncForKey( key ).unlock( LockType.WRITE );
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
/**
* 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) throws CacheException {
try {
lockProvider.getSyncForKey( key ).lock( LockType.READ );
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
/**
* 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) throws CacheException {
try {
lockProvider.getSyncForKey( key ).unlock( LockType.READ );
}
catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
}
else {
throw new CacheException( e );
}
}
}
/**
* Returns <code>true</code> if the locks used by the locking methods of this region are the independent of the cache.
* <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

@ -1,11 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
/**
* Defines {@link org.hibernate.cache.spi.RegionFactory} support for the Ehcache integration
*/
package org.hibernate.cache.ehcache.internal.regions;

View File

@ -1,137 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.regions.EhcacheTransactionalDataRegion;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
/**
* Ultimate superclass for all Ehcache specific Hibernate AccessStrategy implementations.
*
* @param <T> type of the enclosed region
*
* @author Chris Dennis
* @author Alex Snaps
*/
abstract class AbstractEhcacheAccessStrategy<T extends EhcacheTransactionalDataRegion> {
private final T region;
private final SessionFactoryOptions 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, SessionFactoryOptions settings) {
this.region = region;
this.settings = settings;
}
/**
* The wrapped Hibernate cache region.
*/
protected T region() {
return region;
}
/**
* The settings for this persistence unit.
*/
protected SessionFactoryOptions settings() {
return settings;
}
/**
* This method is a placeholder for method signatures supplied by interfaces pulled in further down the class
* hierarchy.
*
* @see RegionAccessStrategy#putFromLoad(SharedSessionContractImplementor, Object, Object, long, Object)
* @see RegionAccessStrategy#putFromLoad(SharedSessionContractImplementor, Object, Object, long, Object)
*/
public final boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version) throws CacheException {
return putFromLoad( session, key, value, txTimestamp, version, settings.isMinimalPutsEnabled() );
}
/**
* This method is a placeholder for method signatures supplied by interfaces pulled in further down the class
* hierarchy.
*
* @see RegionAccessStrategy#putFromLoad(SharedSessionContractImplementor, Object, Object, long, Object, boolean)
* @see RegionAccessStrategy#putFromLoad(SharedSessionContractImplementor, Object, Object, long, Object, boolean)
*/
public abstract boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException;
/**
* Region locks are not supported.
*
* @return <code>null</code>
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion()
* @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#lockRegion()
*/
@SuppressWarnings("UnusedDeclaration")
public final SoftLock lockRegion() {
return null;
}
/**
* Region locks are not supported - perform a cache clear as a precaution.
*
* @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();
}
/**
* A no-op since this is an asynchronous cache access strategy.
*
* @see RegionAccessStrategy#remove(SharedSessionContractImplementor, Object)
* @see RegionAccessStrategy#remove(SharedSessionContractImplementor, Object)
*/
public void remove(SharedSessionContractImplementor session, Object key) throws CacheException {
}
/**
* Called to evict data from the entire region
*
* @throws CacheException Propogated from underlying {@link org.hibernate.cache.spi.Region}
* @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();
}
/**
* Remove the given mapping without regard to transactional safety
*
* @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evict(java.lang.Object)
* @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#evict(java.lang.Object)
*/
public final void evict(Object key) throws CacheException {
region.remove( key );
}
/**
* Remove all mappings without regard to transactional safety
*
* @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

@ -1,395 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import java.io.Serializable;
import java.util.Comparator;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.EhCacheMessageLogger;
import org.hibernate.cache.ehcache.internal.regions.EhcacheTransactionalDataRegion;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.jboss.logging.Logger;
/**
* Superclass for all Ehcache specific read/write AccessStrategy implementations.
*
* @param <T> the type of the enclosed cache region
*
* @author Chris Dennis
* @author Alex Snaps
*/
abstract class AbstractReadWriteEhcacheAccessStrategy<T extends EhcacheTransactionalDataRegion>
extends AbstractEhcacheAccessStrategy<T> {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
AbstractReadWriteEhcacheAccessStrategy.class.getName()
);
private final UUID uuid = UUID.randomUUID();
private final AtomicLong nextLockId = new AtomicLong();
private final Comparator versionComparator;
/**
* Creates a read/write cache access strategy around the given cache region.
*/
public AbstractReadWriteEhcacheAccessStrategy(T region, SessionFactoryOptions settings) {
super( region, settings );
this.versionComparator = region.getCacheDataDescription().getVersionComparator();
}
/**
* Returns <code>null</code> if the item is not readable. Locked items are not readable, nor are items created
* after the start of this transaction.
*
* @see RegionAccessStrategy#get(SharedSessionContractImplementor, Object, long)
* @see RegionAccessStrategy#get(SharedSessionContractImplementor, Object, long)
*/
public final Object get(SharedSessionContractImplementor session, Object key, long txTimestamp) throws CacheException {
readLockIfNeeded( key );
try {
final Lockable item = (Lockable) region().get( key );
final boolean readable = item != null && item.isReadable( txTimestamp );
if ( readable ) {
return item.getValue();
}
else {
return null;
}
}
finally {
readUnlockIfNeeded( key );
}
}
/**
* Returns <code>false</code> and fails to put the value if there is an existing un-writeable item mapped to this
* key.
*
* @see RegionAccessStrategy#putFromLoad(SharedSessionContractImplementor, Object, Object, long, Object, boolean)
* @see RegionAccessStrategy#putFromLoad(SharedSessionContractImplementor, Object, Object, long, Object, boolean)
*/
@Override
public final boolean putFromLoad(
SharedSessionContractImplementor session,
Object key,
Object value,
long txTimestamp,
Object version,
boolean minimalPutOverride)
throws CacheException {
region().writeLock( key );
try {
final Lockable item = (Lockable) region().get( key );
final boolean writeable = item == null || item.isWriteable( txTimestamp, version, versionComparator );
if ( writeable ) {
region().put( key, new Item( value, version, region().nextTimestamp() ) );
return true;
}
else {
return false;
}
}
finally {
region().writeUnlock( key );
}
}
/**
* Soft-lock a cache item.
*
* @see RegionAccessStrategy#lockItem(SharedSessionContractImplementor, Object, Object)
* @see RegionAccessStrategy#lockItem(SharedSessionContractImplementor, Object, Object)
*/
public final SoftLock lockItem(SharedSessionContractImplementor session, Object key, Object version) throws CacheException {
region().writeLock( key );
try {
final Lockable item = (Lockable) region().get( key );
final long timeout = region().nextTimestamp() + region().getTimeout();
final Lock lock = (item == null) ? new Lock( timeout, uuid, nextLockId(), version ) : item.lock(
timeout,
uuid,
nextLockId()
);
region().put( key, lock );
return lock;
}
finally {
region().writeUnlock( key );
}
}
/**
* Soft-unlock a cache item.
*
* @see RegionAccessStrategy#unlockItem(SharedSessionContractImplementor, Object, SoftLock)
* @see RegionAccessStrategy#unlockItem(SharedSessionContractImplementor, Object, SoftLock)
*/
public final void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException {
region().writeLock( key );
try {
final Lockable item = (Lockable) region().get( key );
if ( (item != null) && item.isUnlockable( lock ) ) {
decrementLock( key, (Lock) item );
}
else {
handleLockExpiry( key, item );
}
}
finally {
region().writeUnlock( key );
}
}
private long nextLockId() {
return nextLockId.getAndIncrement();
}
/**
* Unlock and re-put the given key, lock combination.
*/
protected void decrementLock(Object key, Lock 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() );
final long ts = region().nextTimestamp() + region().getTimeout();
// create new lock that times out immediately
final Lock newLock = new Lock( ts, uuid, nextLockId.getAndIncrement(), null );
newLock.unlock( ts );
region().put( key, newLock );
}
/**
* Read 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 );
}
}
/**
* 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 );
}
}
/**
* Interface type implemented by all wrapper objects in the cache.
*/
protected static interface Lockable {
/**
* Returns <code>true</code> if the enclosed value can be read by a transaction started at the given time.
*/
public boolean isReadable(long txTimestamp);
/**
* Returns <code>true</code> if the enclosed value can be replaced with one of the given version by a
* transaction started at the given time.
*/
public boolean isWriteable(long txTimestamp, Object version, Comparator versionComparator);
/**
* Returns the enclosed value.
*/
public Object getValue();
/**
* Returns <code>true</code> if the given lock can be unlocked using the given SoftLock instance as a handle.
*/
public boolean isUnlockable(SoftLock lock);
/**
* Locks this entry, stamping it with the UUID and lockId given, with the lock timeout occuring at the specified
* time. The returned Lock object can be used to unlock the entry in the future.
*/
public Lock lock(long timeout, UUID uuid, long lockId);
}
/**
* Wrapper type representing unlocked items.
*/
protected static final class Item implements Serializable, Lockable {
private static final long serialVersionUID = 1L;
private final Object value;
private final Object version;
private final long timestamp;
/**
* Creates an unlocked item wrapping the given value with a version and creation timestamp.
*/
Item(Object value, Object version, long timestamp) {
this.value = value;
this.version = version;
this.timestamp = timestamp;
}
@Override
public boolean isReadable(long txTimestamp) {
return txTimestamp > timestamp;
}
@Override
@SuppressWarnings("unchecked")
public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) {
return version != null && versionComparator.compare( version, newVersion ) < 0;
}
@Override
public Object getValue() {
return value;
}
@Override
public boolean isUnlockable(SoftLock lock) {
return false;
}
@Override
public Lock lock(long timeout, UUID uuid, long lockId) {
return new Lock( timeout, uuid, lockId, version );
}
@Override
public String toString() {
return "Item{" +
"value=" + value +
", version=" + version +
", timestamp=" + timestamp +
'}';
}
}
/**
* Wrapper type representing locked items.
*/
protected static final class Lock implements Serializable, Lockable {
private static final long serialVersionUID = 2L;
private final UUID sourceUuid;
private final long lockId;
private final Object version;
private long timeout;
private boolean concurrent;
private int multiplicity = 1;
private long unlockTimestamp;
/**
* Creates a locked item with the given identifiers and object version.
*/
Lock(long timeout, UUID sourceUuid, long lockId, Object version) {
this.timeout = timeout;
this.lockId = lockId;
this.version = version;
this.sourceUuid = sourceUuid;
}
@Override
public boolean isReadable(long txTimestamp) {
return false;
}
@Override
@SuppressWarnings({"SimplifiableIfStatement", "unchecked"})
public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) {
if ( txTimestamp > timeout ) {
// if timedout then allow write
return true;
}
if ( multiplicity > 0 ) {
// if still locked then disallow write
return false;
}
return version == null
? txTimestamp > unlockTimestamp
: versionComparator.compare( version, newVersion ) < 0;
}
@Override
public Object getValue() {
return null;
}
@Override
public boolean isUnlockable(SoftLock lock) {
return equals( lock );
}
@Override
@SuppressWarnings("SimplifiableIfStatement")
public boolean equals(Object o) {
if ( o == this ) {
return true;
}
else if ( o instanceof Lock ) {
return (lockId == ((Lock) o).lockId) && sourceUuid.equals( ((Lock) o).sourceUuid );
}
else {
return false;
}
}
@Override
public int hashCode() {
final int hash = (sourceUuid != null ? sourceUuid.hashCode() : 0);
int temp = (int) lockId;
for ( int i = 1; i < Long.SIZE / Integer.SIZE; i++ ) {
temp ^= (lockId >>> (i * Integer.SIZE));
}
return hash + temp;
}
/**
* Returns true if this Lock has been concurrently locked by more than one transaction.
*/
public boolean wasLockedConcurrently() {
return concurrent;
}
@Override
public Lock lock(long timeout, UUID uuid, long lockId) {
concurrent = true;
multiplicity++;
this.timeout = timeout;
return this;
}
/**
* Unlocks this Lock, and timestamps the unlock event.
*/
public void unlock(long timestamp) {
if ( --multiplicity == 0 ) {
unlockTimestamp = timestamp;
}
}
@Override
public String toString() {
return "Lock Source-UUID:" + sourceUuid + " Lock-ID:" + lockId;
}
}
}

View File

@ -1,57 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion;
import org.hibernate.cache.ehcache.internal.regions.EhcacheEntityRegion;
import org.hibernate.cache.ehcache.internal.regions.EhcacheNaturalIdRegion;
import org.hibernate.cache.spi.access.AccessType;
/**
* 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 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);
/**
* Create {@link CollectionRegionAccessStrategy} for the input {@link EhcacheCollectionRegion} and {@link AccessType}
*
* @param collectionRegion The collection region being wrapped
* @param accessType The type of access to allow to the region
*
* @return the created {@link CollectionRegionAccessStrategy}
*/
public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(
EhcacheCollectionRegion collectionRegion,
AccessType accessType);
/**
* Create {@link NaturalIdRegionAccessStrategy} for the input {@link EhcacheNaturalIdRegion} and {@link AccessType}
*
* @param naturalIdRegion The natural-id region being wrapped
* @param accessType The type of access to allow to the region
*
* @return the created {@link NaturalIdRegionAccessStrategy}
*/
public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(
EhcacheNaturalIdRegion naturalIdRegion,
AccessType accessType);
}

View File

@ -1,129 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import org.hibernate.cache.ehcache.EhCacheMessageLogger;
import org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion;
import org.hibernate.cache.ehcache.internal.regions.EhcacheEntityRegion;
import org.hibernate.cache.ehcache.internal.regions.EhcacheNaturalIdRegion;
import org.hibernate.cache.spi.access.AccessType;
import org.jboss.logging.Logger;
/**
* Class implementing {@link EhcacheAccessStrategyFactory}
*
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
public class EhcacheAccessStrategyFactoryImpl implements EhcacheAccessStrategyFactory {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
EhcacheAccessStrategyFactoryImpl.class.getName()
);
@Override
public EntityRegionAccessStrategy createEntityRegionAccessStrategy(
EhcacheEntityRegion entityRegion,
AccessType accessType) {
switch ( accessType ) {
case READ_ONLY:
if ( entityRegion.getCacheDataDescription().isMutable() ) {
LOG.readOnlyCacheConfiguredForMutableEntity( entityRegion.getName() );
}
return new ReadOnlyEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() );
case READ_WRITE:
return new ReadWriteEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() );
case NONSTRICT_READ_WRITE:
return new NonStrictReadWriteEhcacheEntityRegionAccessStrategy(
entityRegion,
entityRegion.getSettings()
);
case TRANSACTIONAL:
return new TransactionalEhcacheEntityRegionAccessStrategy(
entityRegion,
entityRegion.getEhcache(),
entityRegion.getSettings()
);
default:
throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
}
}
@Override
public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(
EhcacheCollectionRegion collectionRegion,
AccessType accessType) {
switch ( accessType ) {
case READ_ONLY:
if ( collectionRegion.getCacheDataDescription().isMutable() ) {
LOG.readOnlyCacheConfiguredForMutableEntity( collectionRegion.getName() );
}
return new ReadOnlyEhcacheCollectionRegionAccessStrategy(
collectionRegion,
collectionRegion.getSettings()
);
case READ_WRITE:
return new ReadWriteEhcacheCollectionRegionAccessStrategy(
collectionRegion,
collectionRegion.getSettings()
);
case NONSTRICT_READ_WRITE:
return new NonStrictReadWriteEhcacheCollectionRegionAccessStrategy(
collectionRegion,
collectionRegion.getSettings()
);
case TRANSACTIONAL:
return new TransactionalEhcacheCollectionRegionAccessStrategy(
collectionRegion, collectionRegion.getEhcache(), collectionRegion
.getSettings()
);
default:
throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
}
}
@Override
public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(
EhcacheNaturalIdRegion naturalIdRegion,
AccessType accessType) {
switch ( accessType ) {
case READ_ONLY:
if ( naturalIdRegion.getCacheDataDescription().isMutable() ) {
LOG.readOnlyCacheConfiguredForMutableEntity( naturalIdRegion.getName() );
}
return new ReadOnlyEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion,
naturalIdRegion.getSettings()
);
case READ_WRITE:
return new ReadWriteEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion,
naturalIdRegion.getSettings()
);
case NONSTRICT_READ_WRITE:
return new NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion,
naturalIdRegion.getSettings()
);
case TRANSACTIONAL:
return new TransactionalEhcacheNaturalIdRegionAccessStrategy(
naturalIdRegion, naturalIdRegion.getEhcache(), naturalIdRegion
.getSettings()
);
default:
throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
}
}
}

View File

@ -1,93 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.collection.CollectionPersister;
/**
* Ehcache specific non-strict read/write collection region access strategy
*
* @author Chris Dennis
* @author Alex Snaps
*/
public class NonStrictReadWriteEhcacheCollectionRegionAccessStrategy
extends AbstractEhcacheAccessStrategy<EhcacheCollectionRegion>
implements CollectionRegionAccessStrategy {
/**
* 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, SessionFactoryOptions settings) {
super( region, settings );
}
@Override
public CollectionRegion getRegion() {
return region();
}
@Override
public Object get(SharedSessionContractImplementor session, Object key, long txTimestamp) throws CacheException {
return region().get( key );
}
@Override
public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
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(SharedSessionContractImplementor session, 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(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException {
region().remove( key );
}
@Override
public void remove(SharedSessionContractImplementor session, Object key) throws CacheException {
region().remove( key );
}
@Override
public Object generateCacheKey(Object id, CollectionPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) {
return DefaultCacheKeysFactory.staticCreateCollectionKey( id, persister, factory, tenantIdentifier );
}
@Override
public Object getCacheKeyId(Object cacheKey) {
return DefaultCacheKeysFactory.staticGetCollectionId( cacheKey );
}
}

View File

@ -1,132 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.regions.EhcacheEntityRegion;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
* Ehcache specific non-strict read/write entity region access strategy
*
* @author Chris Dennis
* @author Alex Snaps
*/
public class NonStrictReadWriteEhcacheEntityRegionAccessStrategy
extends AbstractEhcacheAccessStrategy<EhcacheEntityRegion>
implements EntityRegionAccessStrategy {
/**
* 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, SessionFactoryOptions settings) {
super( region, settings );
}
@Override
public EntityRegion getRegion() {
return super.region();
}
@Override
public Object get(SharedSessionContractImplementor session, Object key, long txTimestamp) throws CacheException {
return region().get( key );
}
@Override
public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
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(SharedSessionContractImplementor session, 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(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException {
region().remove( key );
}
/**
* {@inheritDoc}
* <p/>
* Returns <code>false</code> since this is an asynchronous cache access strategy.
*/
@Override
public boolean insert(SharedSessionContractImplementor session, 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(SharedSessionContractImplementor session, 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(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion)
throws CacheException {
remove( session, key );
return false;
}
@Override
public boolean afterUpdate(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock)
throws CacheException {
unlockItem( session, key, lock );
return false;
}
@Override
public void remove(SharedSessionContractImplementor session, Object key) throws CacheException {
region().remove( key );
}
@Override
public Object generateCacheKey(Object id, EntityPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) {
return DefaultCacheKeysFactory.staticCreateEntityKey( id, persister, factory, tenantIdentifier );
}
@Override
public Object getCacheKeyId(Object cacheKey) {
return DefaultCacheKeysFactory.staticGetEntityId( cacheKey );
}
}

View File

@ -1,129 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.regions.EhcacheNaturalIdRegion;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
* Ehcache specific non-strict read/write NaturalId region access strategy
*
* @author Chris Dennis
* @author Alex Snaps
*/
public class NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy
extends AbstractEhcacheAccessStrategy<EhcacheNaturalIdRegion>
implements NaturalIdRegionAccessStrategy {
/**
* 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, SessionFactoryOptions settings) {
super( region, settings );
}
@Override
public NaturalIdRegion getRegion() {
return region();
}
@Override
public Object get(SharedSessionContractImplementor session, Object key, long txTimestamp) throws CacheException {
return region().get( key );
}
@Override
public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
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(SharedSessionContractImplementor session, 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(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException {
region().remove( key );
}
/**
* {@inheritDoc}
* <p/>
* Returns <code>false</code> since this is an asynchronous cache access strategy.
*/
@Override
public boolean insert(SharedSessionContractImplementor session, 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(SharedSessionContractImplementor session, 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(SharedSessionContractImplementor session, Object key, Object value) throws CacheException {
remove( session, key );
return false;
}
@Override
public boolean afterUpdate(SharedSessionContractImplementor session, Object key, Object value, SoftLock lock) throws CacheException {
unlockItem( session, key, lock );
return false;
}
@Override
public void remove(SharedSessionContractImplementor session, Object key) throws CacheException {
region().remove( key );
}
@Override
public Object generateCacheKey(Object[] naturalIdValues, EntityPersister persister, SharedSessionContractImplementor session) {
return DefaultCacheKeysFactory.staticCreateNaturalIdKey(naturalIdValues, persister, session);
}
@Override
public Object[] getNaturalIdValues(Object cacheKey) {
return DefaultCacheKeysFactory.staticGetNaturalIdValues( cacheKey );
}
}

View File

@ -1,82 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.collection.CollectionPersister;
/**
* Ehcache specific read-only collection region access strategy
*
* @author Chris Dennis
* @author Alex Snaps
*/
public class ReadOnlyEhcacheCollectionRegionAccessStrategy
extends AbstractEhcacheAccessStrategy<EhcacheCollectionRegion>
implements CollectionRegionAccessStrategy {
/**
* 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, SessionFactoryOptions settings) {
super( region, settings );
}
@Override
public CollectionRegion getRegion() {
return region();
}
@Override
public Object get(SharedSessionContractImplementor session, Object key, long txTimestamp) throws CacheException {
return region().get( key );
}
@Override
public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
region().put( key, value );
return true;
}
}
@Override
public SoftLock lockItem(SharedSessionContractImplementor session, Object key, Object version) throws UnsupportedOperationException {
return null;
}
/**
* {@inheritDoc}
* <p/>
* A no-op since this cache is read-only
*/
@Override
public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException {
}
@Override
public Object generateCacheKey(Object id, CollectionPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) {
return DefaultCacheKeysFactory.staticCreateCollectionKey( id, persister, factory, tenantIdentifier );
}
@Override
public Object getCacheKeyId(Object cacheKey) {
return DefaultCacheKeysFactory.staticGetCollectionId(cacheKey);
}
}

View File

@ -1,124 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.regions.EhcacheEntityRegion;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
* Ehcache specific read-only entity region access strategy
*
* @author Chris Dennis
* @author Alex Snaps
*/
public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAccessStrategy<EhcacheEntityRegion>
implements EntityRegionAccessStrategy {
/**
* 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, SessionFactoryOptions settings) {
super( region, settings );
}
@Override
public EntityRegion getRegion() {
return region();
}
@Override
public Object get(SharedSessionContractImplementor session, Object key, long txTimestamp) throws CacheException {
return region().get( key );
}
@Override
public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
region().put( key, value );
return true;
}
}
@Override
public SoftLock lockItem(SharedSessionContractImplementor session, Object key, Object version) throws UnsupportedOperationException {
return null;
}
/**
* {@inheritDoc}
* <p/>
* A no-op since this cache is read-only
*/
@Override
public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException {
evict( key );
}
/**
* {@inheritDoc}
* <p/>
* This cache is asynchronous hence a no-op
*/
@Override
public boolean insert(SharedSessionContractImplementor session, Object key, Object value, Object version) throws CacheException {
return false;
}
@Override
public boolean afterInsert(SharedSessionContractImplementor session, Object key, Object value, Object version) throws CacheException {
region().put( key, value );
return true;
}
/**
* {@inheritDoc}
* <p/>
* Throws UnsupportedOperationException since this cache is read-only
*
* @throws UnsupportedOperationException always
*/
@Override
public boolean update(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion)
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(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock)
throws UnsupportedOperationException {
throw new UnsupportedOperationException( "Can't write to a readonly object" );
}
@Override
public Object generateCacheKey(Object id, EntityPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) {
return DefaultCacheKeysFactory.staticCreateEntityKey( id, persister, factory, tenantIdentifier );
}
@Override
public Object getCacheKeyId(Object cacheKey) {
return DefaultCacheKeysFactory.staticGetEntityId(cacheKey);
}
}

View File

@ -1,122 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.regions.EhcacheNaturalIdRegion;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
* Ehcache specific read-only NaturalId region access strategy
*
* @author Chris Dennis
* @author Alex Snaps
*/
public class ReadOnlyEhcacheNaturalIdRegionAccessStrategy
extends AbstractEhcacheAccessStrategy<EhcacheNaturalIdRegion>
implements NaturalIdRegionAccessStrategy {
/**
* 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, SessionFactoryOptions settings) {
super( region, settings );
}
@Override
public NaturalIdRegion getRegion() {
return region();
}
@Override
public Object get(SharedSessionContractImplementor session, Object key, long txTimestamp) throws CacheException {
return region().get( key );
}
@Override
public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
region().put( key, value );
return true;
}
}
@Override
public SoftLock lockItem(SharedSessionContractImplementor session, Object key, Object version) throws UnsupportedOperationException {
return null;
}
/**
* {@inheritDoc}
* <p/>
* A no-op since this cache is read-only
*/
@Override
public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException {
region().remove( key );
}
/**
* {@inheritDoc}
* <p/>
* This cache is asynchronous hence a no-op
*/
@Override
public boolean insert(SharedSessionContractImplementor session, Object key, Object value) throws CacheException {
return false;
}
@Override
public boolean afterInsert(SharedSessionContractImplementor session, Object key, Object value) throws CacheException {
region().put( key, value );
return true;
}
/**
* {@inheritDoc}
* <p/>
* Throws UnsupportedOperationException since this cache is read-only
*
* @throws UnsupportedOperationException always
*/
@Override
public boolean update(SharedSessionContractImplementor session, 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(SharedSessionContractImplementor session, Object key, Object value, SoftLock lock) throws UnsupportedOperationException {
throw new UnsupportedOperationException( "Can't write to a readonly object" );
}
@Override
public Object generateCacheKey(Object[] naturalIdValues, EntityPersister persister, SharedSessionContractImplementor session) {
return DefaultCacheKeysFactory.staticCreateNaturalIdKey(naturalIdValues, persister, session);
}
@Override
public Object[] getNaturalIdValues(Object cacheKey) {
return DefaultCacheKeysFactory.staticGetNaturalIdValues(cacheKey);
}
}

View File

@ -1,50 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.persister.collection.CollectionPersister;
/**
* Ehcache specific read/write collection region access strategy
*
* @author Chris Dennis
* @author Alex Snaps
*/
public class ReadWriteEhcacheCollectionRegionAccessStrategy
extends AbstractReadWriteEhcacheAccessStrategy<EhcacheCollectionRegion>
implements CollectionRegionAccessStrategy {
/**
* 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, SessionFactoryOptions settings) {
super( region, settings );
}
@Override
public CollectionRegion getRegion() {
return region();
}
@Override
public Object generateCacheKey(Object id, CollectionPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) {
return DefaultCacheKeysFactory.staticCreateCollectionKey( id, persister, factory, tenantIdentifier );
}
@Override
public Object getCacheKeyId(Object cacheKey) {
return DefaultCacheKeysFactory.staticGetCollectionId(cacheKey);
}
}

View File

@ -1,131 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.regions.EhcacheEntityRegion;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
* Ehcache specific read/write entity region access strategy
*
* @author Chris Dennis
* @author Alex Snaps
*/
public class ReadWriteEhcacheEntityRegionAccessStrategy
extends AbstractReadWriteEhcacheAccessStrategy<EhcacheEntityRegion>
implements EntityRegionAccessStrategy {
/**
* 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, SessionFactoryOptions settings) {
super( region, settings );
}
@Override
public EntityRegion getRegion() {
return region();
}
/**
* {@inheritDoc}
* <p/>
* A no-op since this is an asynchronous cache access strategy.
*/
@Override
public boolean insert(SharedSessionContractImplementor session, Object key, Object value, Object version) throws CacheException {
return false;
}
/**
* {@inheritDoc}
* <p/>
* Inserts will only succeed if there is no existing value mapped to this key.
*/
@Override
public boolean afterInsert(SharedSessionContractImplementor session, Object key, Object value, Object version) throws CacheException {
region().writeLock( key );
try {
final Lockable item = (Lockable) region().get( key );
if ( item == null ) {
region().put( key, new Item( value, version, region().nextTimestamp() ) );
return true;
}
else {
return false;
}
}
finally {
region().writeUnlock( key );
}
}
/**
* {@inheritDoc}
* <p/>
* A no-op since this is an asynchronous cache access strategy.
*/
@Override
public boolean update(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion)
throws CacheException {
return false;
}
/**
* {@inheritDoc}
* <p/>
* Updates will only succeed if this entry was locked by this transaction and exclusively this transaction for the
* 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(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock)
throws CacheException {
//what should we do with previousVersion here?
region().writeLock( key );
try {
final Lockable item = (Lockable) region().get( key );
if ( item != null && item.isUnlockable( lock ) ) {
final Lock lockItem = (Lock) item;
if ( lockItem.wasLockedConcurrently() ) {
decrementLock( key, lockItem );
return false;
}
else {
region().put( key, new Item( value, currentVersion, region().nextTimestamp() ) );
return true;
}
}
else {
handleLockExpiry( key, item );
return false;
}
}
finally {
region().writeUnlock( key );
}
}
@Override
public Object generateCacheKey(Object id, EntityPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) {
return DefaultCacheKeysFactory.staticCreateEntityKey(id, persister, factory, tenantIdentifier);
}
@Override
public Object getCacheKeyId(Object cacheKey) {
return DefaultCacheKeysFactory.staticGetEntityId(cacheKey);
}
}

View File

@ -1,128 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.regions.EhcacheNaturalIdRegion;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
* Ehcache specific read/write NaturalId region access strategy
*
* @author Chris Dennis
* @author Alex Snaps
*/
public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
extends AbstractReadWriteEhcacheAccessStrategy<EhcacheNaturalIdRegion>
implements NaturalIdRegionAccessStrategy {
/**
* 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, SessionFactoryOptions settings) {
super( region, settings );
}
@Override
public NaturalIdRegion getRegion() {
return region();
}
/**
* {@inheritDoc}
* <p/>
* A no-op since this is an asynchronous cache access strategy.
*/
@Override
public boolean insert(SharedSessionContractImplementor session, Object key, Object value) throws CacheException {
return false;
}
/**
* {@inheritDoc}
* <p/>
* Inserts will only succeed if there is no existing value mapped to this key.
*/
@Override
public boolean afterInsert(SharedSessionContractImplementor session, Object key, Object value) throws CacheException {
region().writeLock( key );
try {
final Lockable item = (Lockable) region().get( key );
if ( item == null ) {
region().put( key, new Item( value, null, region().nextTimestamp() ) );
return true;
}
else {
return false;
}
}
finally {
region().writeUnlock( key );
}
}
/**
* {@inheritDoc}
* <p/>
* A no-op since this is an asynchronous cache access strategy.
*/
@Override
public boolean update(SharedSessionContractImplementor session, Object key, Object value) throws CacheException {
return false;
}
/**
* {@inheritDoc}
* <p/>
* Updates will only succeed if this entry was locked by this transaction and exclusively this transaction for the
* 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(SharedSessionContractImplementor session, Object key, Object value, SoftLock lock) throws CacheException {
//what should we do with previousVersion here?
region().writeLock( key );
try {
final Lockable item = (Lockable) region().get( key );
if ( item != null && item.isUnlockable( lock ) ) {
final Lock lockItem = (Lock) item;
if ( lockItem.wasLockedConcurrently() ) {
decrementLock( key, lockItem );
return false;
}
else {
region().put( key, new Item( value, null, region().nextTimestamp() ) );
return true;
}
}
else {
handleLockExpiry( key, item );
return false;
}
}
finally {
region().writeUnlock( key );
}
}
@Override
public Object generateCacheKey(Object[] naturalIdValues, EntityPersister persister, SharedSessionContractImplementor session) {
return DefaultCacheKeysFactory.staticCreateNaturalIdKey(naturalIdValues, persister, session);
}
@Override
public Object[] getNaturalIdValues(Object cacheKey) {
return DefaultCacheKeysFactory.staticGetNaturalIdValues(cacheKey);
}
}

View File

@ -1,114 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.collection.CollectionPersister;
/**
* JTA CollectionRegionAccessStrategy.
*
* @author Chris Dennis
* @author Ludovic Orban
* @author Alex Snaps
*/
public class TransactionalEhcacheCollectionRegionAccessStrategy
extends AbstractEhcacheAccessStrategy<EhcacheCollectionRegion>
implements CollectionRegionAccessStrategy {
private final Ehcache ehcache;
/**
* Construct a new collection region access strategy.
*
* @param region the Hibernate region.
* @param ehcache the cache.
* @param settings the Hibernate settings.
*/
public TransactionalEhcacheCollectionRegionAccessStrategy(
EhcacheCollectionRegion region,
Ehcache ehcache,
SessionFactoryOptions settings) {
super( region, settings );
this.ehcache = ehcache;
}
@Override
public Object get(SharedSessionContractImplementor session, Object key, long txTimestamp) throws CacheException {
try {
final Element element = ehcache.get( key );
return element == null ? null : element.getObjectValue();
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
@Override
public CollectionRegion getRegion() {
return region();
}
@Override
public SoftLock lockItem(SharedSessionContractImplementor session, Object key, Object version) throws CacheException {
return null;
}
@Override
public boolean putFromLoad(
SharedSessionContractImplementor session,
Object key,
Object value,
long txTimestamp,
Object version,
boolean minimalPutOverride) throws CacheException {
try {
if ( minimalPutOverride && ehcache.get( key ) != null ) {
return false;
}
//OptimisticCache? versioning?
ehcache.put( new Element( key, value ) );
return true;
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
@Override
public void remove(SharedSessionContractImplementor session, Object key) throws CacheException {
try {
ehcache.remove( key );
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
@Override
public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException {
// no-op
}
@Override
public Object generateCacheKey(Object id, CollectionPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) {
return DefaultCacheKeysFactory.staticCreateCollectionKey( id, persister, factory, tenantIdentifier );
}
@Override
public Object getCacheKeyId(Object cacheKey) {
return DefaultCacheKeysFactory.staticGetCollectionId(cacheKey);
}
}

View File

@ -1,152 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.regions.EhcacheEntityRegion;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
* JTA EntityRegionAccessStrategy.
*
* @author Chris Dennis
* @author Ludovic Orban
* @author Alex Snaps
*/
public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAccessStrategy<EhcacheEntityRegion>
implements EntityRegionAccessStrategy {
private final Ehcache ehcache;
/**
* Construct a new entity region access strategy.
*
* @param region the Hibernate region.
* @param ehcache the cache.
* @param settings the Hibernate settings.
*/
public TransactionalEhcacheEntityRegionAccessStrategy(
EhcacheEntityRegion region,
Ehcache ehcache,
SessionFactoryOptions settings) {
super( region, settings );
this.ehcache = ehcache;
}
@Override
public boolean afterInsert(SharedSessionContractImplementor session, Object key, Object value, Object version) {
return false;
}
@Override
public boolean afterUpdate(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) {
return false;
}
@Override
public Object get(SharedSessionContractImplementor session, Object key, long txTimestamp) throws CacheException {
try {
final Element element = ehcache.get( key );
return element == null ? null : element.getObjectValue();
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
@Override
public EntityRegion getRegion() {
return region();
}
@Override
public boolean insert(SharedSessionContractImplementor session, Object key, Object value, Object version)
throws CacheException {
//OptimisticCache? versioning?
try {
ehcache.put( new Element( key, value ) );
return true;
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
@Override
public SoftLock lockItem(SharedSessionContractImplementor session, Object key, Object version) throws CacheException {
return null;
}
@Override
public boolean putFromLoad(
SharedSessionContractImplementor session,
Object key,
Object value,
long txTimestamp,
Object version,
boolean minimalPutOverride) throws CacheException {
try {
if ( minimalPutOverride && ehcache.get( key ) != null ) {
return false;
}
//OptimisticCache? versioning?
ehcache.put( new Element( key, value ) );
return true;
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
@Override
public void remove(SharedSessionContractImplementor session, Object key) throws CacheException {
try {
ehcache.remove( key );
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
@Override
public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException {
// no-op
}
@Override
public boolean update(
SharedSessionContractImplementor session,
Object key,
Object value,
Object currentVersion,
Object previousVersion) throws CacheException {
try {
ehcache.put( new Element( key, value ) );
return true;
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
@Override
public Object generateCacheKey(Object id, EntityPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) {
return DefaultCacheKeysFactory.staticCreateEntityKey(id, persister, factory, tenantIdentifier);
}
@Override
public Object getCacheKeyId(Object cacheKey) {
return DefaultCacheKeysFactory.staticGetEntityId(cacheKey);
}
}

View File

@ -1,146 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.regions.EhcacheNaturalIdRegion;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.cache.spi.NaturalIdRegion;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
* JTA NaturalIdRegionAccessStrategy.
*
* @author Chris Dennis
* @author Ludovic Orban
* @author Alex Snaps
*/
public class TransactionalEhcacheNaturalIdRegionAccessStrategy
extends AbstractEhcacheAccessStrategy<EhcacheNaturalIdRegion>
implements NaturalIdRegionAccessStrategy {
private final Ehcache ehcache;
/**
* Construct a new collection region access strategy.
*
* @param region the Hibernate region.
* @param ehcache the cache.
* @param settings the Hibernate settings.
*/
public TransactionalEhcacheNaturalIdRegionAccessStrategy(
EhcacheNaturalIdRegion region,
Ehcache ehcache,
SessionFactoryOptions settings) {
super( region, settings );
this.ehcache = ehcache;
}
@Override
public boolean afterInsert(SharedSessionContractImplementor session, Object key, Object value) {
return false;
}
@Override
public boolean afterUpdate(SharedSessionContractImplementor session, Object key, Object value, SoftLock lock) {
return false;
}
@Override
public Object get(SharedSessionContractImplementor session, Object key, long txTimestamp) throws CacheException {
try {
final Element element = ehcache.get( key );
return element == null ? null : element.getObjectValue();
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
@Override
public NaturalIdRegion getRegion() {
return region();
}
@Override
public boolean insert(SharedSessionContractImplementor session, Object key, Object value) throws CacheException {
//OptimisticCache? versioning?
try {
ehcache.put( new Element( key, value ) );
return true;
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
@Override
public SoftLock lockItem(SharedSessionContractImplementor session, Object key, Object version) throws CacheException {
return null;
}
@Override
public boolean putFromLoad(
SharedSessionContractImplementor session, Object key,
Object value,
long txTimestamp,
Object version,
boolean minimalPutOverride) throws CacheException {
try {
if ( minimalPutOverride && ehcache.get( key ) != null ) {
return false;
}
//OptimisticCache? versioning?
ehcache.put( new Element( key, value ) );
return true;
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
@Override
public void remove(SharedSessionContractImplementor session, Object key) throws CacheException {
try {
ehcache.remove( key );
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
@Override
public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException {
// no-op
}
@Override
public boolean update(SharedSessionContractImplementor session, Object key, Object value) throws CacheException {
try {
ehcache.put( new Element( key, value ) );
return true;
}
catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
@Override
public Object generateCacheKey(Object[] naturalIdValues, EntityPersister persister, SharedSessionContractImplementor session) {
return DefaultCacheKeysFactory.staticCreateNaturalIdKey(naturalIdValues, persister, session);
}
@Override
public Object[] getNaturalIdValues(Object cacheKey) {
return DefaultCacheKeysFactory.staticGetNaturalIdValues(cacheKey);
}
}

View File

@ -1,11 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
/**
* Defines {@link org.hibernate.cache.spi.access.RegionAccessStrategy} support for the Ehcache integration
*/
package org.hibernate.cache.ehcache.internal.strategy;

View File

@ -1,75 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.util;
import java.net.URL;
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.TimeoutBehaviorConfiguration.TimeoutBehaviorType;
import org.jboss.logging.Logger;
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 );
// EHC-875 / HHH-6576
if ( config == null ) {
return null;
}
if ( config.getDefaultCacheConfiguration() != null
&& config.getDefaultCacheConfiguration().isTerracottaClustered() ) {
setupHibernateTimeoutBehavior(
config.getDefaultCacheConfiguration()
.getTerracottaConfiguration()
.getNonstopConfiguration()
);
}
for ( CacheConfiguration cacheConfig : config.getCacheConfigurations().values() ) {
if ( cacheConfig.isTerracottaClustered() ) {
setupHibernateTimeoutBehavior( cacheConfig.getTerracottaConfiguration().getNonstopConfiguration() );
}
}
return config;
}
private static void setupHibernateTimeoutBehavior(NonstopConfiguration nonstopConfig) {
nonstopConfig.getTimeoutBehavior().setType( TimeoutBehaviorType.EXCEPTION.getTypeName() );
}
}

View File

@ -1,11 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
/**
* Defines utilities used by the Ehcache integration
*/
package org.hibernate.cache.ehcache.internal.util;

View File

@ -1,144 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
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;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationEmitter;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.StandardMBean;
/**
* Base MBean impl
*
* @author gkeim
*/
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>();
/**
* Constructs a AbstractEmitterBean
*
* @param mbeanInterface The MBean contract
* @param <T> Not used as far as I can see
*
* @throws javax.management.NotCompliantMBeanException thrown from JMX super ctor
*/
protected <T> AbstractEmitterBean(Class<T> mbeanInterface) throws NotCompliantMBeanException {
super( mbeanInterface );
}
/**
* Sends notification of an event
*
* @param eventType The type of event
*/
public void sendNotification(String eventType) {
sendNotification( eventType, null, null );
}
/**
* Sends notification of an event
*
* @param eventType The type of event
* @param data The event data
*/
public void sendNotification(String eventType, Object data) {
sendNotification( eventType, data, null );
}
/**
* Sends notification of an event
*
* @param eventType The type of event
* @param data The event data
* @param msg A message
*/
public void sendNotification(String eventType, Object data, String msg) {
final Notification notification = new Notification(
eventType,
this,
sequenceNumber.incrementAndGet(),
System.currentTimeMillis(),
msg
);
if ( data != null ) {
notification.setUserData( data );
}
emitter.sendNotification( notification );
}
/**
* Dispose of this SampledCacheManager and clean up held resources
*/
@SuppressWarnings("UnusedDeclaration")
public final void dispose() {
doDispose();
removeAllNotificationListeners();
}
/**
* Dispose callback of subclasses
*/
protected abstract void doDispose();
private class Emitter extends NotificationBroadcasterSupport {
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
return AbstractEmitterBean.this.getNotificationInfo();
}
}
@Override
public void addNotificationListener(NotificationListener notif, NotificationFilter filter, Object callBack) {
emitter.addNotificationListener( notif, filter, callBack );
notificationListeners.add( notif );
}
private void removeAllNotificationListeners() {
for ( NotificationListener listener : notificationListeners ) {
try {
emitter.removeNotificationListener( listener );
}
catch (ListenerNotFoundException e) {
// ignore
}
}
notificationListeners.clear();
}
/**
* {@inheritDoc}
*/
@Override
public abstract MBeanNotificationInfo[] getNotificationInfo();
@Override
public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
emitter.removeNotificationListener( listener );
notificationListeners.remove( listener );
}
@Override
public void removeNotificationListener(NotificationListener notif, NotificationFilter filter, Object callBack)
throws ListenerNotFoundException {
emitter.removeNotificationListener( notif, filter, callBack );
notificationListeners.remove( notif );
}
}

View File

@ -1,125 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.management.impl;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.hibernate.internal.util.ReflectHelper;
/**
* Reflective utilities for dealing with backward-incompatible change to statistics types in Hibernate 3.5.
*
* @author gkeim
*/
public class BeanUtils {
/**
* Return the named getter method on the bean or null if not found.
*
* @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) {
final StringBuilder sb = new StringBuilder( "get" ).append( Character.toUpperCase( propertyName.charAt( 0 ) ) );
if ( propertyName.length() > 1 ) {
sb.append( propertyName.substring( 1 ) );
}
final String getterName = sb.toString();
for ( Method m : bean.getClass().getMethods() ) {
if ( getterName.equals( m.getName() ) && m.getParameterCount() == 0 ) {
return m;
}
}
return null;
}
private static Field getField(Object bean, String propertyName) {
for ( Field f : bean.getClass().getDeclaredFields() ) {
if ( propertyName.equals( f.getName() ) ) {
return f;
}
}
return null;
}
private static void validateArgs(Object bean, String propertyName) {
if ( bean == null ) {
throw new IllegalArgumentException( "bean is null" );
}
if ( propertyName == null ) {
throw new IllegalArgumentException( "propertyName is null" );
}
if ( propertyName.trim().length() == 0 ) {
throw new IllegalArgumentException( "propertyName is empty" );
}
}
/**
* Retrieve a named bean property value.
*
* @param bean The bean instance
* @param propertyName The name of the property whose value to extract
*
* @return the property value
*/
public static Object getBeanProperty(Object bean, String propertyName) {
validateArgs( bean, propertyName );
// try getters first
final Method getter = getMethod( bean, propertyName );
if ( getter != null ) {
try {
return getter.invoke( bean );
}
catch (Exception e) {
/**/
}
}
// then try fields
final Field field = getField( bean, propertyName );
if ( field != null ) {
try {
ReflectHelper.ensureAccessibility( field );
return field.get( bean );
}
catch (Exception e) {
/**/
}
}
return null;
}
/**
* Retrieve a Long bean property value.
*
* @param bean The bean instance
* @param propertyName The name of the property whose value to extract
*
* @return long value
*
* @throws NoSuchFieldException If the value is null (wow)
*/
public static long getLongBeanProperty(final Object bean, final String propertyName) throws NoSuchFieldException {
validateArgs( bean, propertyName );
final Object o = getBeanProperty( bean, propertyName );
if ( o == null ) {
throw new NoSuchFieldException( propertyName );
}
else if ( !(o instanceof Number) ) {
throw new IllegalArgumentException( propertyName + " not a Number" );
}
return ((Number) o).longValue();
}
private BeanUtils() {
}
}

View File

@ -1,259 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.management.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
import org.hibernate.stat.CacheRegionStatistics;
/**
* Bean for exposing region stats
*
* @author gkeim
*/
public class CacheRegionStats implements Serializable {
private static final String COMPOSITE_TYPE_NAME = "CacheRegionStats";
private static final String COMPOSITE_TYPE_DESCRIPTION = "Statistics per Cache-region";
private static final String[] ITEM_NAMES = new String[] {
"region", "shortName", "hitCount",
"missCount", "putCount", "hitRatio", "elementCountInMemory", "elementCountOnDisk", "elementCountTotal",
};
private static final String[] ITEM_DESCRIPTIONS = new String[] {
"region", "shortName", "hitCount",
"missCount", "putCount", "hitRatio", "elementCountInMemory", "elementCountOnDisk", "elementCountTotal",
};
private static final OpenType[] ITEM_TYPES = new OpenType[] {
SimpleType.STRING,
SimpleType.STRING, SimpleType.LONG, SimpleType.LONG, SimpleType.LONG, SimpleType.DOUBLE, SimpleType.LONG,
SimpleType.LONG, SimpleType.LONG,
};
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Cache-region";
private static final String TABULAR_TYPE_DESCRIPTION = "All Cache Region Statistics";
private static final String[] INDEX_NAMES = new String[] {"region",};
private static final TabularType TABULAR_TYPE;
static {
try {
COMPOSITE_TYPE = new CompositeType(
COMPOSITE_TYPE_NAME, COMPOSITE_TYPE_DESCRIPTION, ITEM_NAMES,
ITEM_DESCRIPTIONS, ITEM_TYPES
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
/**
* region name
*/
protected final String region;
/**
* region short name
*/
protected final String shortName;
/**
* hit count
*/
protected long hitCount;
/**
* miss count
*/
protected long missCount;
/**
* put count
*/
protected long putCount;
/**
* hit ratio
*/
protected double hitRatio;
/**
* in-memory element count
*/
protected long elementCountInMemory;
/**
* on-disk element count
*/
protected long elementCountOnDisk;
/**
* total element count
*/
protected long elementCountTotal;
/**
* Construct a CacheRegionStats
*
* @param region The region name
*/
public CacheRegionStats(String region) {
this.region = region;
this.shortName = CacheRegionUtils.determineShortName( region );
}
/**
* Construct a CacheRegionStats
*
* @param region The region name
* @param src The SecondLevelCacheStatistics reference
*/
public CacheRegionStats(String region, CacheRegionStatistics src) {
this( region );
try {
this.hitCount = BeanUtils.getLongBeanProperty( src, "hitCount" );
this.missCount = BeanUtils.getLongBeanProperty( src, "missCount" );
this.putCount = BeanUtils.getLongBeanProperty( src, "putCount" );
this.hitRatio = determineHitRatio();
this.elementCountInMemory = BeanUtils.getLongBeanProperty( src, "elementCountInMemory" );
this.elementCountOnDisk = BeanUtils.getLongBeanProperty( src, "elementCountOnDisk" );
this.elementCountTotal = BeanUtils.getLongBeanProperty( src, "elementCountOnDisk" );
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
}
/**
* Construct a CacheRegionStats
*
* @param cData No idea
*/
@SuppressWarnings("UnusedAssignment")
public CacheRegionStats(final CompositeData cData) {
int i = 0;
region = (String) cData.get( ITEM_NAMES[i++] );
shortName = (String) cData.get( ITEM_NAMES[i++] );
hitCount = (Long) cData.get( ITEM_NAMES[i++] );
missCount = (Long) cData.get( ITEM_NAMES[i++] );
putCount = (Long) cData.get( ITEM_NAMES[i++] );
hitRatio = (Double) cData.get( ITEM_NAMES[i++] );
elementCountInMemory = (Long) cData.get( ITEM_NAMES[i++] );
elementCountOnDisk = (Long) cData.get( ITEM_NAMES[i++] );
elementCountTotal = (Long) cData.get( ITEM_NAMES[i++] );
}
protected double determineHitRatio() {
final long readCount = getHitCount() + getMissCount();
double result = 0;
if ( readCount > 0 ) {
result = getHitCount() / ((double) readCount);
}
return result;
}
@Override
public String toString() {
return "region=" + getRegion() + "shortName=" + getShortName() + ", hitCount=" + getHitCount() + ", missCount="
+ getMissCount() + ", putCount" + getPutCount() + ", hitRatio" + getHitRatio() + ", elementCountInMemory="
+ getElementCountInMemory() + ", elementCountOnDisk=" + getElementCountOnDisk() + ", elementCountTotal="
+ getElementCountTotal();
}
public String getRegion() {
return region;
}
public String getShortName() {
return shortName;
}
public long getHitCount() {
return hitCount;
}
public long getMissCount() {
return missCount;
}
public long getPutCount() {
return putCount;
}
public double getHitRatio() {
return hitRatio;
}
public long getElementCountInMemory() {
return elementCountInMemory;
}
public long getElementCountOnDisk() {
return elementCountOnDisk;
}
public long getElementCountTotal() {
return elementCountTotal;
}
/**
* Convert our state into a JMX CompositeData
*
* @return composite data
*/
public CompositeData toCompositeData() {
try {
return new CompositeDataSupport(
COMPOSITE_TYPE, ITEM_NAMES, new Object[] {
getRegion(), getShortName(),
getHitCount(), getMissCount(), getPutCount(), getHitRatio(), getElementCountInMemory(),
getElementCountOnDisk(), getElementCountTotal(),
}
);
}
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
/**
* Convert our state into a JMX TabularData
*
* @return tabular data
*/
public static TabularData newTabularDataInstance() {
return new TabularDataSupport( TABULAR_TYPE );
}
/**
* 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<CacheRegionStats>( tabularData.size() );
for ( Object o : tabularData.values() ) {
countList.add( new CacheRegionStats( (CompositeData) o ) );
}
return countList.toArray( new CacheRegionStats[countList.size()] );
}
}

View File

@ -1,66 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.management.impl;
/**
* CacheRegionUtils
*
* @author gkeim
*/
@SuppressWarnings("UnusedDeclaration")
public abstract class CacheRegionUtils {
/**
* Determine a short name from the full name
*
* @param fullName The full name
*
* @return The short name
*/
public static String determineShortName(String fullName) {
String result = fullName;
if ( fullName != null ) {
final String[] comps = fullName.split( "\\." );
if ( comps.length == 1 ) {
return fullName;
}
boolean truncate = true;
for ( int i = 0; i < comps.length; i++ ) {
final String comp = comps[i];
final char c = comp.charAt( 0 );
if ( truncate && Character.isUpperCase( c ) ) {
truncate = false;
}
if ( truncate ) {
comps[i] = Character.toString( c );
}
}
result = join( comps, '.' );
}
return result;
}
/**
* Same as Hibernate internal {@link org.hibernate.internal.util.StringHelper#join} methods
*
* @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;
}
final StringBuilder sb = new StringBuilder();
for ( String s : elements ) {
sb.append( s ).append( c );
}
return sb.length() > 0 ? sb.substring( 0, sb.length() - 1 ) : "";
}
}

View File

@ -1,241 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.management.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
import org.hibernate.stat.CollectionStatistics;
/**
* CollectionStats
*
* @author gkeim
*/
public class CollectionStats implements Serializable {
private static final String COMPOSITE_TYPE_NAME = "CollectionsStats";
private static final String COMPOSITE_TYPE_DESCRIPTION = "Statistics per Collections";
private static final String[] ITEM_NAMES = new String[] {
"roleName", "shortName", "loadCount",
"fetchCount", "updateCount", "removeCount", "recreateCount",
};
private static final String[] ITEM_DESCRIPTIONS = new String[] {
"roleName", "shortName", "loadCount",
"fetchCount", "updateCount", "removeCount", "recreateCount",
};
private static final OpenType[] ITEM_TYPES = new OpenType[] {
SimpleType.STRING,
SimpleType.STRING, SimpleType.LONG, SimpleType.LONG, SimpleType.LONG, SimpleType.LONG, SimpleType.LONG,
};
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Collection";
private static final String TABULAR_TYPE_DESCRIPTION = "All Collection Statistics";
private static final String[] INDEX_NAMES = new String[] {"roleName",};
private static final TabularType TABULAR_TYPE;
static {
try {
COMPOSITE_TYPE = new CompositeType(
COMPOSITE_TYPE_NAME, COMPOSITE_TYPE_DESCRIPTION, ITEM_NAMES,
ITEM_DESCRIPTIONS, ITEM_TYPES
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
/**
* roleName
*/
protected final String roleName;
/**
* shortName
*/
protected final String shortName;
/**
* loadCount
*/
protected long loadCount;
/**
* fetchCount
*/
protected long fetchCount;
/**
* updateCount
*/
protected long updateCount;
/**
* removeCount
*/
protected long removeCount;
/**
* recreateCount
*/
protected long recreateCount;
/**
* Constructs a CollectionsStats
*
* @param role The collection role
*/
public CollectionStats(String role) {
this.roleName = role;
this.shortName = CacheRegionUtils.determineShortName( role );
}
/**
* Constructs a CollectionsStats
*
* @param role The collection role
* @param src The CollectionStatistics instance
*/
public CollectionStats(String role, CollectionStatistics src) {
this( role );
try {
this.loadCount = BeanUtils.getLongBeanProperty( src, "loadCount" );
this.fetchCount = BeanUtils.getLongBeanProperty( src, "fetchCount" );
this.updateCount = BeanUtils.getLongBeanProperty( src, "updateCount" );
this.removeCount = BeanUtils.getLongBeanProperty( src, "removeCount" );
this.recreateCount = BeanUtils.getLongBeanProperty( src, "recreateCount" );
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
}
/**
* 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++] );
shortName = (String) cData.get( ITEM_NAMES[i++] );
loadCount = (Long) cData.get( ITEM_NAMES[i++] );
fetchCount = (Long) cData.get( ITEM_NAMES[i++] );
updateCount = (Long) cData.get( ITEM_NAMES[i++] );
removeCount = (Long) cData.get( ITEM_NAMES[i++] );
recreateCount = (Long) cData.get( ITEM_NAMES[i++] );
}
/**
* Update the internal stats
*
* @param stats The incoming stats
*/
public void add(CollectionStats stats) {
loadCount += stats.getLoadCount();
fetchCount += stats.getFetchCount();
updateCount += stats.getUpdateCount();
removeCount += stats.getRemoveCount();
recreateCount += stats.getRecreateCount();
}
@Override
public String toString() {
return "roleName=" + roleName + "shortName=" + shortName + ", loadCount=" + loadCount + ", fetchCount="
+ fetchCount + ", updateCount=" + updateCount + ", removeCount=" + removeCount + ", recreateCount"
+ recreateCount;
}
@SuppressWarnings("UnusedDeclaration")
public String getRoleName() {
return roleName;
}
@SuppressWarnings("UnusedDeclaration")
public String getShortName() {
return shortName;
}
public long getLoadCount() {
return loadCount;
}
public long getFetchCount() {
return fetchCount;
}
public long getUpdateCount() {
return updateCount;
}
public long getRemoveCount() {
return removeCount;
}
public long getRecreateCount() {
return recreateCount;
}
/**
* 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 }
);
}
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
/**
* Builds a JMX TabularData
*
* @return JMX TabularData
*/
public static TabularData newTabularDataInstance() {
return new TabularDataSupport( TABULAR_TYPE );
}
/**
* 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<CollectionStats>( tabularData.size() );
for ( Object o : tabularData.values() ) {
countList.add( new CollectionStats( (CompositeData) o ) );
}
return countList.toArray( new CollectionStats[countList.size()] );
}
}

View File

@ -1,646 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
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 net.sf.ehcache.CacheManager;
import net.sf.ehcache.hibernate.management.api.EhcacheHibernateMBean;
import net.sf.ehcache.hibernate.management.api.EhcacheStats;
import net.sf.ehcache.hibernate.management.api.HibernateStats;
import org.hibernate.SessionFactory;
/**
* Implementation of the {@link EhcacheHibernateMBean}
* <p/>
* <p/>
*
* @author <a href="mailto:asanoujam@terracottatech.com">Abhishek Sanoujam</a>
*/
public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibernateMBean {
private static final MBeanNotificationInfo NOTIFICATION_INFO;
private final AtomicBoolean statsEnabled = new AtomicBoolean( true );
private EhcacheStats ehcacheStats;
private volatile HibernateStats hibernateStats = NullHibernateStats.INSTANCE;
static {
final String[] notifTypes = new String[] {};
final String name = Notification.class.getName();
final String description = "Ehcache Hibernate Statistics Event";
NOTIFICATION_INFO = new MBeanNotificationInfo( notifTypes, name, description );
}
/**
* Constructor accepting the backing {@link CacheManager}
*
* @param manager the backing {@link CacheManager}
*
* @throws NotCompliantMBeanException if bean doesn't comply
*/
public EhcacheHibernate(CacheManager manager) throws NotCompliantMBeanException {
super( EhcacheHibernateMBean.class );
ehcacheStats = new EhcacheStatsImpl( manager );
}
/**
* Enable hibernate statistics with the input session factory
* @param sessionFactory the session factory to enable stats for
*/
public void enableHibernateStatistics(SessionFactory sessionFactory) {
try {
hibernateStats = new HibernateStatsImpl( sessionFactory );
}
catch ( Exception e ) {
throw new RuntimeException( e );
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isHibernateStatisticsSupported() {
return hibernateStats instanceof HibernateStatsImpl;
}
/**
* {@inheritDoc}
*/
@Override
public void setStatisticsEnabled(boolean flag) {
if ( flag ) {
hibernateStats.enableStats();
}
else {
hibernateStats.disableStats();
}
statsEnabled.set( flag );
sendNotification( HibernateStats.CACHE_STATISTICS_ENABLED, flag );
}
/**
* {@inheritDoc}
*/
@Override
public boolean isStatisticsEnabled() {
return statsEnabled.get();
}
/**
* {@inheritDoc}
*/
@Override
public void clearStats() {
hibernateStats.clearStats();
}
/**
* {@inheritDoc}
*/
@Override
public void disableStats() {
setStatisticsEnabled( false );
}
/**
* {@inheritDoc}
*/
@Override
public void enableStats() {
setStatisticsEnabled( true );
}
/**
* {@inheritDoc}
*/
@Override
public void flushRegionCache(String region) {
ehcacheStats.flushRegionCache( region );
sendNotification( HibernateStats.CACHE_REGION_FLUSHED, region );
}
/**
* {@inheritDoc}
*/
@Override
public void flushRegionCaches() {
ehcacheStats.flushRegionCaches();
sendNotification( HibernateStats.CACHE_FLUSHED );
}
/**
* {@inheritDoc}
*/
@Override
public String generateActiveConfigDeclaration() {
return ehcacheStats.generateActiveConfigDeclaration();
}
/**
* {@inheritDoc}
*/
@Override
public String generateActiveConfigDeclaration(String region) {
return ehcacheStats.generateActiveConfigDeclaration( region );
}
/**
* {@inheritDoc}
*/
@Override
public long getCacheHitCount() {
return ehcacheStats.getCacheHitCount();
}
/**
* {@inheritDoc}
*/
@Override
public double getCacheHitRate() {
return ehcacheStats.getCacheHitRate();
}
/**
* {@inheritDoc}
*/
@Override
public long getCacheHitSample() {
return ehcacheStats.getCacheHitSample();
}
/**
* {@inheritDoc}
*/
@Override
public long getCacheMissCount() {
return ehcacheStats.getCacheMissCount();
}
/**
* {@inheritDoc}
*/
@Override
public double getCacheMissRate() {
return ehcacheStats.getCacheMissRate();
}
/**
* {@inheritDoc}
*/
@Override
public long getCacheMissSample() {
return ehcacheStats.getCacheMissSample();
}
/**
* {@inheritDoc}
*/
@Override
public long getCachePutCount() {
return ehcacheStats.getCachePutCount();
}
/**
* {@inheritDoc}
*/
@Override
public double getCachePutRate() {
return ehcacheStats.getCachePutRate();
}
/**
* {@inheritDoc}
*/
@Override
public long getCachePutSample() {
return ehcacheStats.getCachePutSample();
}
/**
* {@inheritDoc}
*/
@Override
public TabularData getCacheRegionStats() {
return hibernateStats.getCacheRegionStats();
}
/**
* {@inheritDoc}
*/
@Override
public long getCloseStatementCount() {
return hibernateStats.getCloseStatementCount();
}
/**
* {@inheritDoc}
*/
@Override
public TabularData getCollectionStats() {
return hibernateStats.getCollectionStats();
}
/**
* {@inheritDoc}
*/
@Override
public long getConnectCount() {
return hibernateStats.getConnectCount();
}
/**
* {@inheritDoc}
*/
@Override
public TabularData getEntityStats() {
return hibernateStats.getEntityStats();
}
/**
* {@inheritDoc}
*/
@Override
public long getFlushCount() {
return hibernateStats.getFlushCount();
}
/**
* {@inheritDoc}
*/
@Override
public long getOptimisticFailureCount() {
return hibernateStats.getOptimisticFailureCount();
}
/**
* {@inheritDoc}
*/
@Override
public String getOriginalConfigDeclaration() {
return ehcacheStats.getOriginalConfigDeclaration();
}
/**
* {@inheritDoc}
*/
@Override
public String getOriginalConfigDeclaration(String region) {
return ehcacheStats.getOriginalConfigDeclaration( region );
}
/**
* {@inheritDoc}
*/
@Override
public long getPrepareStatementCount() {
return hibernateStats.getPrepareStatementCount();
}
/**
* {@inheritDoc}
*/
@Override
public long getQueryExecutionCount() {
return hibernateStats.getQueryExecutionCount();
}
/**
* {@inheritDoc}
*/
@Override
public double getQueryExecutionRate() {
return hibernateStats.getQueryExecutionRate();
}
/**
* {@inheritDoc}
*/
@Override
public long getQueryExecutionSample() {
return hibernateStats.getQueryExecutionSample();
}
/**
* {@inheritDoc}
*/
@Override
public TabularData getQueryStats() {
return hibernateStats.getQueryStats();
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, Map<String, Object>> getRegionCacheAttributes() {
return ehcacheStats.getRegionCacheAttributes();
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, Object> getRegionCacheAttributes(String regionName) {
return ehcacheStats.getRegionCacheAttributes( regionName );
}
/**
* {@inheritDoc}
*/
@Override
public int getRegionCacheMaxTTISeconds(String region) {
return ehcacheStats.getRegionCacheMaxTTISeconds( region );
}
/**
* {@inheritDoc}
*/
@Override
public int getRegionCacheMaxTTLSeconds(String region) {
return ehcacheStats.getRegionCacheMaxTTLSeconds( region );
}
/**
* {@inheritDoc}
*/
@Override
public int getRegionCacheOrphanEvictionPeriod(String region) {
return ehcacheStats.getRegionCacheOrphanEvictionPeriod( region );
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, int[]> getRegionCacheSamples() {
return ehcacheStats.getRegionCacheSamples();
}
/**
* {@inheritDoc}
*/
@Override
public int getRegionCacheTargetMaxInMemoryCount(String region) {
return ehcacheStats.getRegionCacheTargetMaxInMemoryCount( region );
}
/**
* {@inheritDoc}
*/
@Override
public int getRegionCacheTargetMaxTotalCount(String region) {
return ehcacheStats.getRegionCacheTargetMaxTotalCount( region );
}
/**
* {@inheritDoc}
*/
@Override
public long getSessionCloseCount() {
return hibernateStats.getSessionCloseCount();
}
/**
* {@inheritDoc}
*/
@Override
public long getSessionOpenCount() {
return hibernateStats.getSessionOpenCount();
}
/**
* {@inheritDoc}
*/
@Override
public long getSuccessfulTransactionCount() {
return hibernateStats.getSuccessfulTransactionCount();
}
/**
* {@inheritDoc}
*/
@Override
public String[] getTerracottaHibernateCacheRegionNames() {
return ehcacheStats.getTerracottaHibernateCacheRegionNames();
}
/**
* {@inheritDoc}
*/
@Override
public long getTransactionCount() {
return hibernateStats.getTransactionCount();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isRegionCacheEnabled(String region) {
return ehcacheStats.isRegionCacheEnabled( region );
}
/**
* {@inheritDoc}
*/
@Override
public void setRegionCachesEnabled(boolean enabled) {
ehcacheStats.setRegionCachesEnabled( enabled );
sendNotification( HibernateStats.CACHE_ENABLED, enabled );
}
/**
* {@inheritDoc}
*/
@Override
public void setRegionCacheEnabled(String region, boolean enabled) {
ehcacheStats.setRegionCacheEnabled( region, enabled );
sendNotification( HibernateStats.CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region );
}
/**
* {@inheritDoc}
*/
@Override
public boolean isRegionCacheLoggingEnabled(String region) {
return ehcacheStats.isRegionCacheLoggingEnabled( region );
}
/**
* {@inheritDoc}
*/
@Override
public boolean isRegionCacheOrphanEvictionEnabled(String region) {
return ehcacheStats.isRegionCacheOrphanEvictionEnabled( region );
}
/**
* {@inheritDoc}
*/
@Override
public boolean isRegionCachesEnabled() {
return ehcacheStats.isRegionCachesEnabled();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTerracottaHibernateCache(String region) {
return ehcacheStats.isTerracottaHibernateCache( region );
}
/**
* {@inheritDoc}
*/
@Override
public void setRegionCacheLoggingEnabled(String region, boolean loggingEnabled) {
ehcacheStats.setRegionCacheLoggingEnabled( region, loggingEnabled );
sendNotification( HibernateStats.CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region );
}
/**
* {@inheritDoc}
*/
@Override
public void setRegionCacheMaxTTISeconds(String region, int maxTTISeconds) {
ehcacheStats.setRegionCacheMaxTTISeconds( region, maxTTISeconds );
sendNotification( HibernateStats.CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region );
}
/**
* {@inheritDoc}
*/
@Override
public void setRegionCacheMaxTTLSeconds(String region, int maxTTLSeconds) {
ehcacheStats.setRegionCacheMaxTTLSeconds( region, maxTTLSeconds );
sendNotification( HibernateStats.CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region );
}
/**
* {@inheritDoc}
*/
@Override
public void setRegionCacheTargetMaxInMemoryCount(String region, int targetMaxInMemoryCount) {
ehcacheStats.setRegionCacheTargetMaxInMemoryCount( region, targetMaxInMemoryCount );
sendNotification( HibernateStats.CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region );
}
/**
* {@inheritDoc}
*/
@Override
public void setRegionCacheTargetMaxTotalCount(String region, int targetMaxTotalCount) {
ehcacheStats.setRegionCacheTargetMaxTotalCount( region, targetMaxTotalCount );
sendNotification( HibernateStats.CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region );
}
/**
* {@inheritDoc}
*
* @see EhcacheStats#getNumberOfElementsInMemory(java.lang.String)
*/
@Override
public int getNumberOfElementsInMemory(String region) {
return ehcacheStats.getNumberOfElementsInMemory( region );
}
/**
* {@inheritDoc}
*
* @see EhcacheStats#getNumberOfElementsInMemory(java.lang.String)
*/
@Override
public int getNumberOfElementsOffHeap(String region) {
return ehcacheStats.getNumberOfElementsOffHeap( region );
}
/**
* {@inheritDoc}
*
* @see EhcacheStats#getNumberOfElementsOnDisk(java.lang.String)
*/
@Override
public int getNumberOfElementsOnDisk(String region) {
return ehcacheStats.getNumberOfElementsOnDisk( region );
}
/**
* {@inheritDoc}
*
* @see EhcacheStats#getMaxGetTimeMillis()
*/
@Override
public long getMaxGetTimeMillis() {
return ehcacheStats.getMaxGetTimeMillis();
}
/**
* {@inheritDoc}
*
* @see EhcacheStats#getMaxGetTimeMillis(java.lang.String)
*/
@Override
public long getMaxGetTimeMillis(String cacheName) {
return ehcacheStats.getMaxGetTimeMillis( cacheName );
}
/**
* {@inheritDoc}
*
* @see EhcacheStats#getMinGetTimeMillis()
*/
@Override
public long getMinGetTimeMillis() {
return ehcacheStats.getMinGetTimeMillis();
}
/**
* {@inheritDoc}
*
* @see EhcacheStats#getMinGetTimeMillis(java.lang.String)
*/
@Override
public long getMinGetTimeMillis(String cacheName) {
return ehcacheStats.getMinGetTimeMillis( cacheName );
}
/**
* {@inheritDoc}
*
* @see EhcacheStats#getAverageGetTimeMillis(java.lang.String)
*/
@Override
public float getAverageGetTimeMillis(String region) {
return ehcacheStats.getAverageGetTimeMillis( region );
}
/**
* {@inheritDoc}
*/
@Override
protected void doDispose() {
// no-op
}
/**
* {@inheritDoc}
*
* @see AbstractEmitterBean#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
return new MBeanNotificationInfo[] { NOTIFICATION_INFO };
}
}

View File

@ -1,44 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.management.impl;
import java.util.Properties;
import net.sf.ehcache.CacheManager;
import org.hibernate.SessionFactory;
/**
* Interface for helping registering mbeans for ehcache backed hibernate second-level cache
* <p/>
* <p/>
*
* @author <a href="mailto:asanoujam@terracottatech.com">Abhishek Sanoujam</a>
*/
public interface EhcacheHibernateMBeanRegistration {
/**
* Registers MBean for the input manager and session factory properties.
* <p/>
* MBeans will be registered based on the input session factory name. If the input name is null or blank, the name of the cache-manager
* is used
*
* @param manager the {@link CacheManager} to register the MBean for
* @param properties properties to used to create the associated {@link SessionFactory}
*
* @throws Exception reflecting the source of the problem registering the MBean
*/
public void registerMBeanForCacheManager(CacheManager manager, Properties properties) throws Exception;
/**
* Enable hibernate statistics in the mbean.
*
* @param sessionFactory the {@link SessionFactory} to enable stats for
*/
public void enableHibernateStatisticsSupport(SessionFactory sessionFactory);
}

View File

@ -1,163 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
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 net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Status;
import net.sf.ehcache.event.CacheManagerEventListener;
import org.hibernate.SessionFactory;
import org.hibernate.cache.ehcache.EhCacheMessageLogger;
import org.hibernate.cfg.Environment;
import org.jboss.logging.Logger;
/**
* Implementation of {@link EhcacheHibernateMBeanRegistration}.
* Also implements {@link net.sf.ehcache.event.CacheManagerEventListener}. Deregisters mbeans when the associated cachemanager is shutdown.
* <p/>
* <p/>
*
* @author <a href="mailto:asanoujam@terracottatech.com">Abhishek Sanoujam</a>
*/
public class EhcacheHibernateMBeanRegistrationImpl
implements EhcacheHibernateMBeanRegistration, CacheManagerEventListener {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
EhcacheHibernateMBeanRegistrationImpl.class.getName()
);
private static final int MAX_MBEAN_REGISTRATION_RETRIES = 50;
private Status status = Status.STATUS_UNINITIALISED;
private volatile EhcacheHibernate ehcacheHibernate;
private volatile ObjectName cacheManagerObjectName;
@Override
public synchronized void registerMBeanForCacheManager(final CacheManager manager, final Properties properties)
throws Exception {
final String sessionFactoryName = properties.getProperty( Environment.SESSION_FACTORY_NAME );
final String name;
if ( sessionFactoryName == null ) {
name = manager.getName();
}
else {
name = "".equals( sessionFactoryName.trim() ) ? manager.getName() : sessionFactoryName;
}
registerBean( name, manager );
}
private void registerBean(String name, CacheManager manager) throws Exception {
ehcacheHibernate = new EhcacheHibernate( manager );
int tries = 0;
boolean success;
Exception exception = null;
final String cacheManagerClusterUUID = manager.getClusterUUID();
String registeredCacheManagerName;
do {
registeredCacheManagerName = name;
if ( tries != 0 ) {
registeredCacheManagerName += "_" + tries;
}
try {
// register the CacheManager MBean
final MBeanServer mBeanServer = getMBeanServer();
cacheManagerObjectName = EhcacheHibernateMbeanNames.getCacheManagerObjectName(
cacheManagerClusterUUID,
registeredCacheManagerName
);
mBeanServer.registerMBean( ehcacheHibernate, cacheManagerObjectName );
success = true;
break;
}
catch (InstanceAlreadyExistsException e) {
success = false;
exception = e;
}
tries++;
} while ( tries < MAX_MBEAN_REGISTRATION_RETRIES );
if ( !success ) {
throw new Exception(
"Cannot register mbean for CacheManager with name" + manager.getName() + " after "
+ MAX_MBEAN_REGISTRATION_RETRIES + " retries. Last tried name=" + registeredCacheManagerName,
exception
);
}
status = Status.STATUS_ALIVE;
}
private MBeanServer getMBeanServer() {
return ManagementFactory.getPlatformMBeanServer();
}
@Override
public void enableHibernateStatisticsSupport(SessionFactory sessionFactory) {
ehcacheHibernate.enableHibernateStatistics( sessionFactory );
}
@Override
public synchronized void dispose() throws CacheException {
if ( status == Status.STATUS_SHUTDOWN ) {
return;
}
try {
getMBeanServer().unregisterMBean( cacheManagerObjectName );
}
catch (Exception e) {
LOG.warn(
"Error unregistering object instance " + cacheManagerObjectName + " . Error was " + e.getMessage(),
e
);
}
ehcacheHibernate = null;
cacheManagerObjectName = null;
status = Status.STATUS_SHUTDOWN;
}
@Override
public synchronized Status getStatus() {
return status;
}
/**
* {@inheritDoc}
* <p/>
* NOTE : No-op in this case
*/
@Override
public void init() throws CacheException {
// no-op
}
/**
* {@inheritDoc}
* <p/>
* NOTE : No-op in this case
*/
@Override
public void notifyCacheAdded(String cacheName) {
// no-op
}
/**
* {@inheritDoc}
* <p/>
* NOTE : No-op in this case
*/
@Override
public void notifyCacheRemoved(String cacheName) {
// no-op
}
}

View File

@ -1,72 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.management.impl;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
/**
* Utility class used for getting {@link javax.management.ObjectName}'s for ehcache hibernate MBeans
* <p/>
* <p/>
*
* @author <a href="mailto:asanoujam@terracottatech.com">Abhishek Sanoujam</a>
* @since 1.7
*/
public abstract class EhcacheHibernateMbeanNames {
/**
* Group id for all sampled mbeans registered
*/
public static final String GROUP_ID = "net.sf.ehcache.hibernate";
/**
* Type for the ehcache backed hibernate second level cache statistics mbean
*/
public static final String EHCACHE_HIBERNATE_TYPE = "EhcacheHibernateStats";
/**
* Filter out invalid ObjectName characters from s.
*
* @param s the name to be filtered out
*
* @return A valid JMX ObjectName attribute value.
*/
public static String mbeanSafe(String s) {
return s == null ? "" : s.replaceAll( ":|=|\n", "." );
}
/**
* Returns an ObjectName for the passed name
*
* @param cacheManagerClusterUUID the UUID of the cacheManager within the cluster
* @param name the name to use, which should be made "mbean safe"
*
* @return An {@link javax.management.ObjectName} using the input name of cache manager
*
* @throws javax.management.MalformedObjectNameException The name derived from the params does not correspond to a valid ObjectName
*/
public static ObjectName getCacheManagerObjectName(String cacheManagerClusterUUID, String name)
throws MalformedObjectNameException {
return new ObjectName(
GROUP_ID + ":type=" + EHCACHE_HIBERNATE_TYPE
+ ",name=" + mbeanSafe( name ) + getBeanNameSuffix( cacheManagerClusterUUID )
);
}
private static String getBeanNameSuffix(String cacheManagerClusterUUID) {
String suffix = "";
if ( !isBlank( cacheManagerClusterUUID ) ) {
suffix = ",node=" + cacheManagerClusterUUID;
}
return suffix;
}
private static boolean isBlank(String param) {
return param == null || "".equals( param.trim() );
}
}

View File

@ -1,547 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.management.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.hibernate.management.api.EhcacheStats;
/**
* Implementation of {@link EhcacheStats}
* <p/>
* <p/>
*
* @author <a href="mailto:asanoujam@terracottatech.com">Abhishek Sanoujam</a>
*/
public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStats {
private static final long MILLIS_PER_SECOND = 1000;
private static final MBeanNotificationInfo NOTIFICATION_INFO;
private final CacheManager cacheManager;
private long statsSince = System.currentTimeMillis();
static {
final String[] notifTypes = new String[] {
CACHE_ENABLED, CACHE_REGION_CHANGED, CACHE_FLUSHED, CACHE_REGION_FLUSHED,
CACHE_STATISTICS_ENABLED, CACHE_STATISTICS_RESET,
};
final String name = Notification.class.getName();
final String description = "Ehcache Hibernate Statistics Event";
NOTIFICATION_INFO = new MBeanNotificationInfo( notifTypes, name, description );
}
/**
* Constructor accepting the backing {@link CacheManager}
*
* @param manager The {@link CacheManager} to expose stats for
*
* @throws javax.management.NotCompliantMBeanException should registering the MBean fail
*/
public EhcacheStatsImpl(CacheManager manager) throws NotCompliantMBeanException {
super( EhcacheStats.class );
this.cacheManager = manager;
}
@Override
public void flushRegionCache(String region) {
final Cache cache = this.cacheManager.getCache( region );
if ( cache != null ) {
cache.flush();
}
}
@Override
public void flushRegionCaches() {
for ( String name : cacheManager.getCacheNames() ) {
final Cache cache = this.cacheManager.getCache( name );
if ( cache != null ) {
cache.flush();
}
}
}
@Override
public String generateActiveConfigDeclaration() {
return this.cacheManager.getActiveConfigurationText();
}
@Override
public String generateActiveConfigDeclaration(String region) {
return this.cacheManager.getActiveConfigurationText( region );
}
@Override
public long getCacheHitCount() {
long count = 0;
for ( String name : cacheManager.getCacheNames() ) {
final Cache cache = cacheManager.getCache( name );
if ( cache != null ) {
count += cache.getStatistics().cacheHitCount();
}
}
return count;
}
@Override
public double getCacheHitRate() {
final long now = System.currentTimeMillis();
final double deltaSecs = (double) ( now - statsSince ) / MILLIS_PER_SECOND;
return getCacheHitCount() / deltaSecs;
}
@Override
public long getCacheHitSample() {
long count = 0;
for ( String name : cacheManager.getCacheNames() ) {
final Cache cache = cacheManager.getCache( name );
if ( cache != null ) {
count += cache.getStatistics().cacheHitOperation().rate().value().longValue();
}
}
return count;
}
@Override
public long getCacheMissCount() {
long count = 0;
for ( String name : cacheManager.getCacheNames() ) {
final Cache cache = cacheManager.getCache( name );
if ( cache != null ) {
count += cache.getStatistics().cacheMissCount();
}
}
return count;
}
@Override
public double getCacheMissRate() {
final long now = System.currentTimeMillis();
final double deltaSecs = (double) ( now - statsSince ) / MILLIS_PER_SECOND;
return getCacheMissCount() / deltaSecs;
}
@Override
public long getCacheMissSample() {
long count = 0;
for ( String name : cacheManager.getCacheNames() ) {
final Cache cache = cacheManager.getCache( name );
if ( cache != null ) {
count += cache.getStatistics().cacheMissOperation().rate().value().longValue();
}
}
return count;
}
@Override
public long getCachePutCount() {
long count = 0;
for ( String name : cacheManager.getCacheNames() ) {
final Cache cache = cacheManager.getCache( name );
if ( cache != null ) {
count += cache.getStatistics().cachePutCount();
}
}
return count;
}
@Override
public double getCachePutRate() {
final long now = System.currentTimeMillis();
final double deltaSecs = (double) ( now - statsSince ) / MILLIS_PER_SECOND;
return getCachePutCount() / deltaSecs;
}
@Override
public long getCachePutSample() {
long count = 0;
for ( String name : cacheManager.getCacheNames() ) {
final Cache cache = cacheManager.getCache( name );
if ( cache != null ) {
count += cache.getStatistics().cachePutOperation().rate().value().longValue();
}
}
return count;
}
@Override
public String getOriginalConfigDeclaration() {
return this.cacheManager.getOriginalConfigurationText();
}
@Override
public String getOriginalConfigDeclaration(String region) {
return this.cacheManager.getOriginalConfigurationText( region );
}
@Override
public Map<String, Map<String, Object>> getRegionCacheAttributes() {
final Map<String, Map<String, Object>> result = new HashMap<String, Map<String, Object>>();
for ( String regionName : this.cacheManager.getCacheNames() ) {
result.put( regionName, getRegionCacheAttributes( regionName ) );
}
return result;
}
@Override
public Map<String, Object> getRegionCacheAttributes(String regionName) {
final Map<String, Object> result = new HashMap<String, Object>();
result.put( "Enabled", isRegionCacheEnabled( regionName ) );
result.put( "LoggingEnabled", isRegionCacheLoggingEnabled( regionName ) );
result.put( "MaxTTISeconds", getRegionCacheMaxTTISeconds( regionName ) );
result.put( "MaxTTLSeconds", getRegionCacheMaxTTLSeconds( regionName ) );
result.put( "TargetMaxInMemoryCount", getRegionCacheTargetMaxInMemoryCount( regionName ) );
result.put( "TargetMaxTotalCount", getRegionCacheTargetMaxTotalCount( regionName ) );
result.put( "OrphanEvictionEnabled", isRegionCacheOrphanEvictionEnabled( regionName ) );
result.put( "OrphanEvictionPeriod", getRegionCacheOrphanEvictionPeriod( regionName ) );
return result;
}
@Override
public int getRegionCacheMaxTTISeconds(String region) {
final Cache cache = cacheManager.getCache( region );
if ( cache != null ) {
return (int) cache.getCacheConfiguration().getTimeToIdleSeconds();
}
else {
return -1;
}
}
@Override
public int getRegionCacheMaxTTLSeconds(String region) {
final Cache cache = cacheManager.getCache( region );
if ( cache != null ) {
return (int) cache.getCacheConfiguration().getTimeToLiveSeconds();
}
else {
return -1;
}
}
@Override
public int getRegionCacheOrphanEvictionPeriod(String region) {
final Cache cache = this.cacheManager.getCache( region );
if ( cache != null && cache.isTerracottaClustered() ) {
return cache.getCacheConfiguration().getTerracottaConfiguration().getOrphanEvictionPeriod();
}
else {
return -1;
}
}
@Override
public Map<String, int[]> getRegionCacheSamples() {
final Map<String, int[]> rv = new HashMap<String, int[]>();
for ( String name : cacheManager.getCacheNames() ) {
final Cache cache = cacheManager.getCache( name );
if ( cache != null ) {
final Double hits = cache.getStatistics().cacheHitOperation().rate().value();
final Double misses = cache.getStatistics().cacheMissNotFoundOperation().rate().value();
final Double expired = cache.getStatistics().cacheMissExpiredOperation().rate().value();
final Double puts = cache.getStatistics().cachePutOperation().rate().value();
rv.put(
name, new int[] {
hits.intValue(),
misses.intValue(),
expired.intValue(),
puts.intValue()
}
);
}
}
return rv;
}
@Override
public int getRegionCacheTargetMaxInMemoryCount(String region) {
final Cache cache = cacheManager.getCache( region );
if ( cache != null ) {
return cache.getCacheConfiguration().getMaxElementsInMemory();
}
else {
return -1;
}
}
@Override
public int getRegionCacheTargetMaxTotalCount(String region) {
final Cache cache = cacheManager.getCache( region );
if ( cache != null ) {
return cache.getCacheConfiguration().getMaxElementsOnDisk();
}
else {
return -1;
}
}
@Override
public String[] getTerracottaHibernateCacheRegionNames() {
final ArrayList<String> rv = new ArrayList<String>();
for ( String name : cacheManager.getCacheNames() ) {
final Cache cache = cacheManager.getCache( name );
if ( cache != null ) {
if ( cache.getCacheConfiguration().isTerracottaClustered() ) {
rv.add( name );
}
}
}
return rv.toArray( new String[rv.size()] );
}
@Override
public boolean isRegionCacheEnabled(String region) {
final Cache cache = this.cacheManager.getCache( region );
return cache != null && !cache.isDisabled();
}
@Override
public void setRegionCacheEnabled(String region, boolean enabled) {
final Cache cache = this.cacheManager.getCache( region );
if ( cache != null ) {
cache.setDisabled( !enabled );
}
sendNotification( CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region );
}
@Override
public boolean isRegionCachesEnabled() {
for ( String name : this.cacheManager.getCacheNames() ) {
final Cache cache = this.cacheManager.getCache( name );
if ( cache != null ) {
if ( cache.isDisabled() ) {
return false;
}
}
}
return true;
}
@Override
public void setRegionCachesEnabled(final boolean flag) {
for ( String name : this.cacheManager.getCacheNames() ) {
final Cache cache = this.cacheManager.getCache( name );
if ( cache != null ) {
cache.setDisabled( !flag );
}
}
sendNotification( CACHE_ENABLED, flag );
}
@Override
public boolean isRegionCacheLoggingEnabled(String region) {
final Cache cache = this.cacheManager.getCache( region );
return cache != null && cache.getCacheConfiguration().getLogging();
}
@Override
public boolean isRegionCacheOrphanEvictionEnabled(String region) {
final Cache cache = this.cacheManager.getCache( region );
return cache != null && cache.isTerracottaClustered() && cache.getCacheConfiguration()
.getTerracottaConfiguration()
.getOrphanEviction();
}
@Override
public boolean isTerracottaHibernateCache(String region) {
final Cache cache = cacheManager.getCache( region );
return cache != null && cache.getCacheConfiguration().isTerracottaClustered();
}
@Override
public void setRegionCacheLoggingEnabled(String region, boolean loggingEnabled) {
final Cache cache = this.cacheManager.getCache( region );
if ( cache != null ) {
cache.getCacheConfiguration().setLogging( loggingEnabled );
sendNotification( CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region );
}
}
@Override
public void setRegionCacheMaxTTISeconds(String region, int maxTTISeconds) {
final Cache cache = this.cacheManager.getCache( region );
if ( cache != null ) {
cache.getCacheConfiguration().setTimeToIdleSeconds( maxTTISeconds );
sendNotification( CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region );
}
}
@Override
public void setRegionCacheMaxTTLSeconds(String region, int maxTTLSeconds) {
final Cache cache = this.cacheManager.getCache( region );
if ( cache != null ) {
cache.getCacheConfiguration().setTimeToLiveSeconds( maxTTLSeconds );
sendNotification( CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region );
}
}
@Override
public void setRegionCacheTargetMaxInMemoryCount(String region, int targetMaxInMemoryCount) {
final Cache cache = this.cacheManager.getCache( region );
if ( cache != null ) {
cache.getCacheConfiguration().setMaxElementsInMemory( targetMaxInMemoryCount );
sendNotification( CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region );
}
}
@Override
public void setRegionCacheTargetMaxTotalCount(String region, int targetMaxTotalCount) {
final Cache cache = this.cacheManager.getCache( region );
if ( cache != null ) {
cache.getCacheConfiguration().setMaxElementsOnDisk( targetMaxTotalCount );
sendNotification( CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region );
}
}
@Override
public int getNumberOfElementsInMemory(String region) {
final Cache cache = this.cacheManager.getCache( region );
if ( cache != null ) {
return (int) cache.getMemoryStoreSize();
}
else {
return -1;
}
}
@Override
public int getNumberOfElementsOffHeap(String region) {
final Cache cache = this.cacheManager.getCache( region );
if ( cache != null ) {
return (int) cache.getOffHeapStoreSize();
}
else {
return -1;
}
}
@Override
public int getNumberOfElementsOnDisk(String region) {
final Cache cache = this.cacheManager.getCache( region );
if ( cache != null ) {
return cache.getDiskStoreSize();
}
else {
return -1;
}
}
@Override
public long getMaxGetTimeMillis() {
long rv = 0;
for ( String cacheName : cacheManager.getCacheNames() ) {
final Cache cache = cacheManager.getCache( cacheName );
if ( cache != null ) {
final Long maximum = cache.getStatistics()
.cacheGetOperation().latency().maximum().value();
if ( maximum != null ) {
rv = Math.max(
rv, TimeUnit.MILLISECONDS.convert(
maximum,
TimeUnit.NANOSECONDS
)
);
}
}
}
return rv;
}
@Override
public long getMinGetTimeMillis() {
long rv = Long.MAX_VALUE;
for ( String cacheName : cacheManager.getCacheNames() ) {
final Cache cache = cacheManager.getCache( cacheName );
if ( cache != null ) {
final Long minimum = cache.getStatistics()
.cacheGetOperation()
.latency()
.minimum().value();
if ( minimum != null ) {
rv = Math.min(
rv, TimeUnit.MILLISECONDS.convert(
minimum,
TimeUnit.NANOSECONDS
)
);
}
}
}
return rv == Long.MAX_VALUE ? 0 : rv;
}
@Override
public long getMaxGetTimeMillis(String cacheName) {
final Cache cache = cacheManager.getCache( cacheName );
if ( cache != null ) {
final Long maximum = cache.getStatistics()
.cacheGetOperation()
.latency()
.maximum().value();
return maximum == null ? 0 : TimeUnit.MILLISECONDS.convert(
maximum,
TimeUnit.NANOSECONDS
);
}
else {
return 0;
}
}
@Override
public long getMinGetTimeMillis(String cacheName) {
final Cache cache = cacheManager.getCache( cacheName );
if ( cache != null ) {
final Long minimum = cache.getStatistics()
.cacheGetOperation()
.latency()
.minimum().value();
return minimum == null ? 0 : TimeUnit.MILLISECONDS.convert(
minimum,
TimeUnit.NANOSECONDS
);
}
else {
return 0;
}
}
@Override
public float getAverageGetTimeMillis(String region) {
final Cache cache = this.cacheManager.getCache( region );
if ( cache != null ) {
final Double avg = cache.getStatistics()
.cacheGetOperation()
.latency()
.average().value();
return TimeUnit.MILLISECONDS.convert(
avg.longValue(),
TimeUnit.NANOSECONDS
);
}
else {
return -1f;
}
}
@Override
protected void doDispose() {
// no-op
}
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
return new MBeanNotificationInfo[] { NOTIFICATION_INFO };
}
}

View File

@ -1,280 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.management.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
import org.hibernate.stat.EntityStatistics;
/**
* When we only support Java 6, all of this OpenMBean scaffolding can be removed in favor or MXBeans.
*
* @author gkeim
*/
public class EntityStats implements Serializable {
private static final String COMPOSITE_TYPE_NAME = "EntityStats";
private static final String COMPOSITE_TYPE_DESCRIPTION = "Statistics per Entity";
private static final String[] ITEM_NAMES = new String[] {
"name", "shortName", "loadCount",
"updateCount", "insertCount", "deleteCount", "fetchCount", "optimisticFailureCount",
};
private static final String[] ITEM_DESCRIPTIONS = new String[] {
"name", "shortName", "loadCount",
"updateCount", "insertCount", "deleteCount", "fetchCount", "optimisticFailureCount",
};
private static final OpenType[] ITEM_TYPES = new OpenType[] {
SimpleType.STRING,
SimpleType.STRING, SimpleType.LONG, SimpleType.LONG, SimpleType.LONG, SimpleType.LONG, SimpleType.LONG,
SimpleType.LONG,
};
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Entity";
private static final String TABULAR_TYPE_DESCRIPTION = "All Entity Statistics";
private static final String[] INDEX_NAMES = new String[] {"name",};
private static final TabularType TABULAR_TYPE;
static {
try {
COMPOSITE_TYPE = new CompositeType(
COMPOSITE_TYPE_NAME, COMPOSITE_TYPE_DESCRIPTION, ITEM_NAMES,
ITEM_DESCRIPTIONS, ITEM_TYPES
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
/**
* name
*/
protected final String name;
/**
* shortName
*/
protected final String shortName;
/**
* loadCount
*/
protected long loadCount;
/**
* updateCount
*/
protected long updateCount;
/**
* insertCount
*/
protected long insertCount;
/**
* deleteCount
*/
protected long deleteCount;
/**
* fetchCount
*/
protected long fetchCount;
/**
* optimisticFailureCount
*/
protected long optimisticFailureCount;
/**
* Constructor only naming the stat
* @param name the name of the entity
*/
public EntityStats(String name) {
this.name = name;
this.shortName = CacheRegionUtils.determineShortName( name );
}
/**
* Constructor naming the stat and sourcing stats
* @param name the name of the entity
* @param src its source for the stats to expose
*/
public EntityStats(String name, EntityStatistics src) {
this( name );
try {
this.loadCount = BeanUtils.getLongBeanProperty( src, "loadCount" );
this.updateCount = BeanUtils.getLongBeanProperty( src, "updateCount" );
this.insertCount = BeanUtils.getLongBeanProperty( src, "insertCount" );
this.deleteCount = BeanUtils.getLongBeanProperty( src, "deleteCount" );
this.fetchCount = BeanUtils.getLongBeanProperty( src, "fetchCount" );
this.optimisticFailureCount = BeanUtils.getLongBeanProperty( src, "optimisticFailureCount" );
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
}
/**
* Constructor from compositeDate
* @param cData CompositeData of the stats
*/
@SuppressWarnings("UnusedAssignment")
public EntityStats(final CompositeData cData) {
int i = 0;
name = (String) cData.get( ITEM_NAMES[i++] );
shortName = (String) cData.get( ITEM_NAMES[i++] );
loadCount = (Long) cData.get( ITEM_NAMES[i++] );
updateCount = (Long) cData.get( ITEM_NAMES[i++] );
insertCount = (Long) cData.get( ITEM_NAMES[i++] );
deleteCount = (Long) cData.get( ITEM_NAMES[i++] );
fetchCount = (Long) cData.get( ITEM_NAMES[i++] );
optimisticFailureCount = (Long) cData.get( ITEM_NAMES[i++] );
}
/**
* Adds the counters of this instance up with the ones passed in
* @param stats the stats to add to this one
*/
public void add(EntityStats stats) {
loadCount += stats.getLoadCount();
updateCount += stats.getUpdateCount();
insertCount += stats.getInsertCount();
deleteCount += stats.getDeleteCount();
fetchCount += stats.getFetchCount();
optimisticFailureCount += stats.getOptimisticFailureCount();
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "name=" + name + ", shortName=" + shortName + ",loadCount=" + loadCount + ", updateCount=" + updateCount
+ ", insertCount=" + insertCount + ", deleteCount=" + deleteCount + ", fetchCount=" + fetchCount
+ ", optimisticFailureCount" + optimisticFailureCount;
}
/**
* The name of the entity those stats are about
* @return the entity name
*/
public String getName() {
return name;
}
/**
* The short name of the entity those stats are about
* @return the shortName of the entity
*/
@SuppressWarnings("UnusedDeclaration")
public String getShortName() {
return shortName;
}
/**
* Amount of load ops on the entity
* @return the load count
*/
public long getLoadCount() {
return loadCount;
}
/**
* Amount of update ops on the entity
* @return the update count
*/
public long getUpdateCount() {
return updateCount;
}
/**
* Amount of insert ops on the entity
* @return the insert count
*/
public long getInsertCount() {
return insertCount;
}
/**
* Amount of delete ops on the entity
* @return the delete count
*/
public long getDeleteCount() {
return deleteCount;
}
/**
* Amount of fetch ops on the entity
* @return the fetch count
*/
public long getFetchCount() {
return fetchCount;
}
/**
* Amount of optimistic failures on the entity
* @return the optimistic failure count
*/
public long getOptimisticFailureCount() {
return optimisticFailureCount;
}
/**
* Creates a CompositeData instance of this instance
* @return the compositeData representation of this instance
*/
public CompositeData toCompositeData() {
try {
return new CompositeDataSupport(
COMPOSITE_TYPE, ITEM_NAMES, new Object[] {
name, shortName, loadCount,
updateCount, insertCount, deleteCount, fetchCount, optimisticFailureCount,
}
);
}
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
/**
* Creates a new TabularData
* @return a new TabularData instance
*/
public static TabularData newTabularDataInstance() {
return new TabularDataSupport( TABULAR_TYPE );
}
/**
* Reads an array of entityStats from TabularData
* @param tabularData the tabularData with the {@link CompositeData} of stats to extract
* @return all entityStats as an array
*/
@SuppressWarnings({"unchecked", "UnusedDeclaration"})
public static EntityStats[] fromTabularData(final TabularData tabularData) {
final List<EntityStats> countList = new ArrayList( tabularData.size() );
for ( Object o : tabularData.values() ) {
countList.add( new EntityStats( (CompositeData) o ) );
}
return countList.toArray( new EntityStats[countList.size()] );
}
}

View File

@ -1,230 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
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 net.sf.ehcache.hibernate.management.api.HibernateStats;
import org.hibernate.SessionFactory;
import org.hibernate.stat.Statistics;
/**
* Implementation of {@link HibernateStats}
* <p/>
* <p/>
*
* @author <a href="mailto:asanoujam@terracottatech.com">Abhishek Sanoujam</a>
*/
public class HibernateStatsImpl extends AbstractEmitterBean implements HibernateStats {
private static final double MILLIS_PER_SECOND = 1000;
private static final MBeanNotificationInfo NOTIFICATION_INFO;
private final SessionFactory sessionFactory;
static {
final String[] notifTypes = new String[] {};
final String name = Notification.class.getName();
final String description = "Hibernate Statistics Event";
NOTIFICATION_INFO = new MBeanNotificationInfo( notifTypes, name, description );
}
/**
* Constructor accepting the backing {@link SessionFactory}
*
* @param sessionFactory the {@link SessionFactory} to source stats from
*
* @throws javax.management.NotCompliantMBeanException thrown from JMX super ctor
*/
public HibernateStatsImpl(SessionFactory sessionFactory) throws NotCompliantMBeanException {
super( HibernateStats.class );
this.sessionFactory = sessionFactory;
}
/**
* @return statistics
*/
private Statistics getStatistics() {
return sessionFactory.getStatistics();
}
@Override
public void clearStats() {
getStatistics().clear();
sendNotification( CACHE_STATISTICS_RESET );
}
@Override
public void disableStats() {
setStatisticsEnabled( false );
}
@Override
public void enableStats() {
setStatisticsEnabled( true );
}
@Override
public long getCloseStatementCount() {
return getStatistics().getCloseStatementCount();
}
@Override
public long getConnectCount() {
return getStatistics().getConnectCount();
}
/**
* Unsupported operation
* @return nothing ever, this only throws!
* @throws UnsupportedOperationException
* @deprecated DO NOT USE, WILL ONLY THROW AT YOU!
*/
@Deprecated
@SuppressWarnings("UnusedDeclaration")
public long getDBSQLExecutionSample() {
throw new UnsupportedOperationException( "Use getQueryExecutionCount() instead" );
}
@Override
public long getFlushCount() {
return getStatistics().getFlushCount();
}
@Override
public long getOptimisticFailureCount() {
return getStatistics().getOptimisticFailureCount();
}
@Override
public long getPrepareStatementCount() {
return getStatistics().getPrepareStatementCount();
}
@Override
public long getQueryExecutionCount() {
return getStatistics().getQueryExecutionCount();
}
@Override
public double getQueryExecutionRate() {
final long startTime = getStatistics().getStartTime();
final long now = System.currentTimeMillis();
final double deltaSecs = (now - startTime) / MILLIS_PER_SECOND;
return getQueryExecutionCount() / deltaSecs;
}
@Override
public long getQueryExecutionSample() {
throw new UnsupportedOperationException( "TODO: need to impl. rates for query execution" );
}
@Override
public long getSessionCloseCount() {
return getStatistics().getSessionCloseCount();
}
@Override
public long getSessionOpenCount() {
return getStatistics().getSessionOpenCount();
}
@Override
public long getSuccessfulTransactionCount() {
return getStatistics().getSuccessfulTransactionCount();
}
@Override
public long getTransactionCount() {
return getStatistics().getTransactionCount();
}
@Override
public boolean isStatisticsEnabled() {
return getStatistics().isStatisticsEnabled();
}
@Override
public void setStatisticsEnabled(boolean flag) {
getStatistics().setStatisticsEnabled( flag );
sendNotification( CACHE_STATISTICS_ENABLED, flag );
}
@Override
public TabularData getEntityStats() {
final List<CompositeData> result = new ArrayList<CompositeData>();
final Statistics statistics = getStatistics();
for ( String entity : statistics.getEntityNames() ) {
final EntityStats entityStats = new EntityStats( entity, statistics.getEntityStatistics( entity ) );
result.add( entityStats.toCompositeData() );
}
final TabularData td = EntityStats.newTabularDataInstance();
td.putAll( result.toArray( new CompositeData[result.size()] ) );
return td;
}
@Override
public TabularData getCollectionStats() {
final List<CompositeData> result = new ArrayList<CompositeData>();
final Statistics statistics = getStatistics();
for ( String roleName : statistics.getCollectionRoleNames() ) {
final CollectionStats collectionStats = new CollectionStats(
roleName,
statistics.getCollectionStatistics( roleName )
);
result.add( collectionStats.toCompositeData() );
}
final TabularData td = CollectionStats.newTabularDataInstance();
td.putAll( result.toArray( new CompositeData[result.size()] ) );
return td;
}
@Override
public TabularData getQueryStats() {
final List<CompositeData> result = new ArrayList<CompositeData>();
final Statistics statistics = getStatistics();
for ( String query : statistics.getQueries() ) {
final QueryStats queryStats = new QueryStats( query, statistics.getQueryStatistics( query ) );
result.add( queryStats.toCompositeData() );
}
final TabularData td = QueryStats.newTabularDataInstance();
td.putAll( result.toArray( new CompositeData[result.size()] ) );
return td;
}
@Override
public TabularData getCacheRegionStats() {
final List<CompositeData> list = new ArrayList<CompositeData>();
final Statistics statistics = getStatistics();
for ( String region : statistics.getSecondLevelCacheRegionNames() ) {
final CacheRegionStats l2CacheStats = new CacheRegionStats(
region,
statistics.getDomainDataRegionStatistics( region )
);
list.add( l2CacheStats.toCompositeData() );
}
final TabularData td = CacheRegionStats.newTabularDataInstance();
td.putAll( list.toArray( new CompositeData[list.size()] ) );
return td;
}
@Override
protected void doDispose() {
// no-op
}
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
return new MBeanNotificationInfo[] {NOTIFICATION_INFO};
}
}

View File

@ -1,315 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.management.impl;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanNotificationInfo;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.openmbean.TabularData;
import net.sf.ehcache.hibernate.management.api.HibernateStats;
/**
* Implementation of {@link HibernateStats} that does nothing
* <p/>
* <p/>
*
* @author <a href="mailto:asanoujam@terracottatech.com">Abhishek Sanoujam</a>
*/
public final class NullHibernateStats implements HibernateStats {
/**
* Singleton instance.
*/
public static final HibernateStats INSTANCE = new NullHibernateStats();
/**
* private constructor. No need to create instances of this. Use singleton instance
*/
private NullHibernateStats() {
super();
// TODO Auto-generated constructor stub
}
/**
* {@inheritDoc}
*
* @see HibernateStats#clearStats()
*/
@Override
public void clearStats() {
// no-op
}
/**
* {@inheritDoc}
*
* @see HibernateStats#disableStats()
*/
@Override
public void disableStats() {
// no-op
}
/**
* {@inheritDoc}
*
* @see HibernateStats#enableStats()
*/
@Override
public void enableStats() {
// no-op
}
/**
* {@inheritDoc}
*
* @see HibernateStats#getCloseStatementCount()
*/
@Override
public long getCloseStatementCount() {
// no-op
return 0;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#getCollectionStats()
*/
@Override
public TabularData getCollectionStats() {
// no-op
return null;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#getConnectCount()
*/
@Override
public long getConnectCount() {
// no-op
return 0;
}
/**
* Not supported right now
* @return 0 always
*/
@SuppressWarnings("UnusedDeclaration")
public long getDBSQLExecutionSample() {
// no-op
return 0;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#getEntityStats()
*/
@Override
public TabularData getEntityStats() {
// no-op
return null;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#getFlushCount()
*/
@Override
public long getFlushCount() {
// no-op
return 0;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#getOptimisticFailureCount()
*/
@Override
public long getOptimisticFailureCount() {
// no-op
return 0;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#getPrepareStatementCount()
*/
@Override
public long getPrepareStatementCount() {
// no-op
return 0;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#getQueryExecutionCount()
*/
@Override
public long getQueryExecutionCount() {
// no-op
return 0;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#getQueryExecutionRate()
*/
@Override
public double getQueryExecutionRate() {
// no-op
return 0;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#getQueryExecutionSample()
*/
@Override
public long getQueryExecutionSample() {
// no-op
return 0;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#getQueryStats()
*/
@Override
public TabularData getQueryStats() {
// no-op
return null;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#getSessionCloseCount()
*/
@Override
public long getSessionCloseCount() {
// no-op
return 0;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#getSessionOpenCount()
*/
@Override
public long getSessionOpenCount() {
// no-op
return 0;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#getSuccessfulTransactionCount()
*/
@Override
public long getSuccessfulTransactionCount() {
// no-op
return 0;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#getTransactionCount()
*/
@Override
public long getTransactionCount() {
// no-op
return 0;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#isStatisticsEnabled()
*/
@Override
public boolean isStatisticsEnabled() {
// no-op
return false;
}
/**
* {@inheritDoc}
*
* @see HibernateStats#setStatisticsEnabled(boolean)
*/
@Override
public void setStatisticsEnabled(boolean flag) {
// no-op
}
/**
* {@inheritDoc}
* @see HibernateStats#getCacheRegionStats()
*/
@Override
public TabularData getCacheRegionStats() {
return null;
}
/**
* {@inheritDoc}
* @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object)
*/
@Override
public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback)
throws ListenerNotFoundException {
/**/
}
/**
* {@inheritDoc}
* @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object)
*/
@Override
public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback)
throws IllegalArgumentException {
/**/
}
/**
* {@inheritDoc}
* @see javax.management.NotificationBroadcaster#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
return null;
}
/**
* {@inheritDoc}
* @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener)
*/
@Override
public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
/**/
}
}

View File

@ -1,170 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.management.impl;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Properties;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import net.sf.ehcache.CacheManager;
import org.hibernate.SessionFactory;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.EhCacheMessageLogger;
import org.hibernate.cfg.Environment;
import org.hibernate.internal.SessionFactoryRegistry;
import org.hibernate.internal.util.ReflectHelper;
import org.jboss.logging.Logger;
/**
* Helper class for registering mbeans for ehcache backed hibernate second level cache
* <p/>
* <p/>
*
* @author <a href="mailto:asanoujam@terracottatech.com">Abhishek Sanoujam</a>
* @author <a href="mailto:alexsnaps@terracottatech.com">Alex Snaps</a>
*/
public class ProviderMBeanRegistrationHelper {
private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
EhCacheMessageLogger.class,
ProviderMBeanRegistrationHelper.class.getName()
);
private static final int MILLIS_PER_SECOND = 1000;
private static final int SLEEP_MILLIS = 500;
private volatile EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration;
/**
* Registers mbean for the input cache manager and the session factory name
*
* @param manager the backing cachemanager
* @param properties session factory config properties
*/
public void registerMBean(final CacheManager manager, final Properties properties) {
if ( Boolean.getBoolean( "tc.active" ) ) {
ehcacheHibernateMBeanRegistration = new EhcacheHibernateMBeanRegistrationImpl();
manager.getTimer().scheduleAtFixedRate(
new RegisterMBeansTask( ehcacheHibernateMBeanRegistration, manager, properties ), SLEEP_MILLIS,
SLEEP_MILLIS
);
}
}
/**
* Unregisters previously registered mbean.
*/
public void unregisterMBean() {
if ( ehcacheHibernateMBeanRegistration != null ) {
ehcacheHibernateMBeanRegistration.dispose();
ehcacheHibernateMBeanRegistration = null;
}
}
/**
* Task for running mbean registration that can be scheduled in a timer
*/
private static class RegisterMBeansTask extends TimerTask {
private static final int NUM_SECONDS = 30;
private long startTime;
private final AtomicBoolean mbeanRegistered = new AtomicBoolean( false );
private final EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration;
private final CacheManager manager;
private final Properties properties;
public RegisterMBeansTask(
EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration,
CacheManager manager, Properties properties) {
this.ehcacheHibernateMBeanRegistration = ehcacheHibernateMBeanRegistration;
this.manager = manager;
this.properties = properties;
}
@Override
public void run() {
LOG.debug( "Running mbean initializer task for ehcache hibernate..." );
startTime = System.currentTimeMillis();
if ( mbeanRegistered.compareAndSet( false, true ) ) {
try {
ehcacheHibernateMBeanRegistration.registerMBeanForCacheManager( manager, properties );
LOG.debug( "Successfully registered bean" );
}
catch (Exception e) {
throw new CacheException( e );
}
}
final SessionFactory sessionFactory = locateSessionFactory();
if ( sessionFactory == null ) {
LOG.debug(
"SessionFactory is probably still being initialized..."
+ " waiting for it to complete before enabling hibernate statistics monitoring via JMX"
);
if ( System.currentTimeMillis() > startTime + (NUM_SECONDS * MILLIS_PER_SECOND) ) {
LOG.info( "Hibernate statistics monitoring through JMX is DISABLED." );
LOG.info(
"Failed to look up SessionFactory after " + NUM_SECONDS + " seconds using session-factory properties '"
+ properties + "'"
);
this.cancel();
}
}
else {
ehcacheHibernateMBeanRegistration.enableHibernateStatisticsSupport( sessionFactory );
LOG.info( "Hibernate statistics monitoring through JMX is ENABLED. " );
this.cancel();
}
}
private SessionFactory locateSessionFactory() {
final String jndiName = properties.getProperty( Environment.SESSION_FACTORY_NAME );
if ( jndiName != null ) {
return SessionFactoryRegistry.INSTANCE.getNamedSessionFactory( jndiName );
}
try {
final Class factoryType = SessionFactoryRegistry.class;
final Field instancesField = getField( factoryType, "sessionFactoryMap" );
// NOTE : no need to check accessibility here - we know it is private
instancesField.setAccessible( true );
final Map map = (Map) instancesField.get( SessionFactoryRegistry.INSTANCE );
if ( map == null ) {
return null;
}
for ( Object o : map.values() ) {
final SessionFactory sessionFactory = (SessionFactory) o;
final Class sessionFactoryType = sessionFactory.getClass();
final Field propertiesField = getField( sessionFactoryType, "properties" );
if ( propertiesField != null ) {
// NOTE : no need to check accessibility here - we know it is private
propertiesField.setAccessible( true );
final Properties props = (Properties) propertiesField.get( sessionFactory );
if ( props != null && props.equals( properties ) ) {
return sessionFactory;
}
}
}
}
catch (RuntimeException re) {
LOG.error( "Error locating Hibernate Session Factory", re );
}
catch (IllegalAccessException iae) {
LOG.error( "Error locating Hibernate Session Factory", iae );
}
return null;
}
}
private static Field getField(Class c, String fieldName) {
for ( Field field : c.getDeclaredFields() ) {
if ( field.getName().equals( fieldName ) ) {
return field;
}
}
throw new NoSuchFieldError( "Type '" + c + "' has no field '" + fieldName + "'" );
}
}

View File

@ -1,314 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.management.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
import org.hibernate.stat.QueryStatistics;
/**
* Represent point in time state of the query stats of a given query
*
* @author gkeim
* @author Alex Snaps
*/
public class QueryStats implements Serializable {
private static final String COMPOSITE_TYPE_NAME = "QueryStats";
private static final String COMPOSITE_TYPE_DESCRIPTION = "Statistics per Query";
private static final String[] ITEM_NAMES = new String[] {
"query", "cacheHitCount",
"cacheMissCount",
"cachePutCount",
"executionCount",
"executionRowCount",
"executionAvgTime",
"executionMaxTime",
"executionMinTime",
};
private static final String[] ITEM_DESCRIPTIONS = new String[] {
"query", "cacheHitCount",
"cacheMissCount",
"cachePutCount",
"executionCount",
"executionRowCount",
"executionAvgTime",
"executionMaxTime",
"executionMinTime",
};
private static final OpenType[] ITEM_TYPES = new OpenType[] {
SimpleType.STRING, SimpleType.LONG,
SimpleType.LONG, SimpleType.LONG, SimpleType.LONG, SimpleType.LONG, SimpleType.LONG, SimpleType.LONG,
SimpleType.LONG,
};
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Query";
private static final String TABULAR_TYPE_DESCRIPTION = "All Query Statistics";
private static final String[] INDEX_NAMES = new String[] {"query",};
private static final TabularType TABULAR_TYPE;
static {
try {
COMPOSITE_TYPE = new CompositeType(
COMPOSITE_TYPE_NAME, COMPOSITE_TYPE_DESCRIPTION, ITEM_NAMES,
ITEM_DESCRIPTIONS, ITEM_TYPES
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
/**
* query
*/
protected final String query;
/**
* cacheHitCount
*/
protected long cacheHitCount;
/**
* cacheMissCount
*/
protected long cacheMissCount;
/**
* cachePutCount
*/
protected long cachePutCount;
/**
* executionCount
*/
protected long executionCount;
/**
* executionRowCount
*/
protected long executionRowCount;
/**
* executionAvgTime
*/
protected long executionAvgTime;
/**
* executionMaxTime
*/
protected long executionMaxTime;
/**
* executionMinTime
*/
protected long executionMinTime;
/**
* Constructor
* @param name the query string
*/
public QueryStats(String name) {
this.query = name;
}
/**
* Constructor
* @param name the query string
* @param src the source of the stats to this query
*/
public QueryStats(String name, QueryStatistics src) {
this( name );
try {
this.cacheHitCount = BeanUtils.getLongBeanProperty( src, "cacheHitCount" );
this.cacheMissCount = BeanUtils.getLongBeanProperty( src, "cacheMissCount" );
this.cachePutCount = BeanUtils.getLongBeanProperty( src, "cachePutCount" );
this.executionCount = BeanUtils.getLongBeanProperty( src, "executionCount" );
this.executionRowCount = BeanUtils.getLongBeanProperty( src, "executionRowCount" );
this.executionAvgTime = BeanUtils.getLongBeanProperty( src, "executionAvgTime" );
this.executionMaxTime = BeanUtils.getLongBeanProperty( src, "executionMaxTime" );
this.executionMinTime =
BeanUtils.getLongBeanProperty( src, "executionMinTime" );
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
}
/**
* Constructor
* @param cData CompositeDate to construct an instance from
*/
@SuppressWarnings("UnusedAssignment")
public QueryStats(final CompositeData cData) {
int i = 0;
query = (String) cData.get( ITEM_NAMES[i++] );
cacheHitCount = (Long) cData.get( ITEM_NAMES[i++] );
cacheMissCount = (Long) cData.get( ITEM_NAMES[i++] );
cachePutCount = (Long) cData.get( ITEM_NAMES[i++] );
executionCount = (Long) cData.get( ITEM_NAMES[i++] );
executionRowCount = (Long) cData.get( ITEM_NAMES[i++] );
executionAvgTime = (Long) cData.get( ITEM_NAMES[i++] );
executionMaxTime = (Long) cData.get( ITEM_NAMES[i++] );
executionMinTime = (Long) cData.get( ITEM_NAMES[i++] );
}
/**
* Adds to the counter of this instance
* @param stats the counters to add to these ones
*/
public void add(QueryStats stats) {
cacheHitCount += stats.getCacheHitCount();
cacheMissCount += stats.getCacheMissCount();
cachePutCount += stats.getCachePutCount();
executionCount += stats.getExecutionCount();
executionRowCount += stats.getExecutionRowCount();
executionAvgTime += stats.getExecutionAvgTime();
executionMaxTime += stats.getExecutionMaxTime();
executionMinTime += stats.getExecutionMinTime();
}
@Override
public String toString() {
return "query=" + query + ", cacheHitCount=" + cacheHitCount + ", cacheMissCount=" + cacheMissCount
+ ", cachePutCount=" + cachePutCount + ", executionCount=" + executionCount + ", executionRowCount="
+ executionRowCount + ", executionAvgTime=" + executionAvgTime + ", executionMaxTime=" + executionMaxTime
+ ", executionMinTime=" + executionMinTime;
}
/**
* Accessor to the queryString
* @return the query string
*/
@SuppressWarnings("UnusedDeclaration")
public String getQuery() {
return query;
}
/**
* The amount of hits for this query
* @return the hit count
*/
public long getCacheHitCount() {
return cacheHitCount;
}
/**
* The amount of misses for this query
* @return the miss count
*/
public long getCacheMissCount() {
return cacheMissCount;
}
/**
* The amount of puts for this query
* @return the put count
*/
public long getCachePutCount() {
return cachePutCount;
}
/**
* The amount of execution of this query
* @return the execution count
*/
public long getExecutionCount() {
return executionCount;
}
/**
* The amount of rows returned for this query
* @return the row count
*/
public long getExecutionRowCount() {
return executionRowCount;
}
/**
* The avg time to execute this query
* @return the avg time in ms
*/
public long getExecutionAvgTime() {
return executionAvgTime;
}
/**
* The max time to execute this query
* @return the max time in ms
*/
public long getExecutionMaxTime() {
return executionMaxTime;
}
/**
* The minimum time to execute this query
* @return the min time in ms
*/
public long getExecutionMinTime() {
return executionMinTime;
}
/**
* Creates a CompositeData instance of this instance
* @return the compositeData representation of this instance
*/
public CompositeData toCompositeData() {
try {
return new CompositeDataSupport(
COMPOSITE_TYPE, ITEM_NAMES, new Object[] {
query, cacheHitCount, cacheMissCount,
cachePutCount,
executionCount,
executionRowCount,
executionAvgTime,
executionMaxTime,
executionMinTime,
}
);
}
catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
/**
* Creates a new TabularData
* @return a new TabularData instance
*/
public static TabularData newTabularDataInstance() {
return new TabularDataSupport( TABULAR_TYPE );
}
/**
* Reads an array of queryStats from TabularData
* @param tabularData the tabularData with the {@link CompositeData} of stats to extract
* @return all queryStats as an array
*/
@SuppressWarnings({"unchecked", "UnusedDeclaration"})
public static QueryStats[] fromTabularData(final TabularData tabularData) {
final List<QueryStats> countList = new ArrayList( tabularData.size() );
for ( Object o : tabularData.values() ) {
countList.add( new QueryStats( (CompositeData) o ) );
}
return countList.toArray( new QueryStats[countList.size()] );
}
}

View File

@ -1,11 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
/**
* Defines JMX support for the Ehcache integration
*/
package org.hibernate.cache.ehcache.management.impl;

View File

@ -1,11 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
/**
* Defines the integration with Ehcache as a second-level cache service.
*/
package org.hibernate.cache.ehcache;

View File

@ -1,13 +0,0 @@
#
# Hibernate, Relational Persistence for Idiomatic Java
#
# License: GNU Lesser General Public License (LGPL), version 2.1 or later.
# See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
#
#
# Hibernate, Relational Persistence for Idiomatic Java
#
# License: GNU Lesser General Public License (LGPL), version 2.1 or later.
# See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
#
org.hibernate.cache.ehcache.StrategyRegistrationProviderImpl

View File

@ -1,16 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<blueprint default-activation="eager"
xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<bean id="strategyRegistrationProvider" class="org.hibernate.cache.ehcache.StrategyRegistrationProviderImpl"/>
<service ref="strategyRegistrationProvider" interface="org.hibernate.boot.registry.selector.StrategyRegistrationProvider"/>
</blueprint>

View File

@ -1,33 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cache.ehcache.internal.strategy;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.ehcache.internal.regions.EhcacheTransactionalDataRegion;
/**
* @author Alex Snaps
*/
public class ItemValueExtractor extends AbstractReadWriteEhcacheAccessStrategy {
/**
* Creates a read/write cache access strategy around the given cache region.
*/
public ItemValueExtractor(EhcacheTransactionalDataRegion region, SessionFactoryOptions settings) {
super(region, settings);
}
public static <T> T getValue(final Object entry) {
if(!(entry instanceof Item)) {
throw new IllegalArgumentException("Entry needs to be of type " + Item.class.getName());
}
return (T)((Item)entry).getValue();
}
}

View File

@ -1,40 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.cache;
import net.sf.ehcache.CacheManager;
import org.junit.BeforeClass;
import org.junit.Test;
import org.hibernate.cache.ehcache.management.impl.EhcacheStatsImpl;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* @author Alex Snaps
*/
public class EhcacheStatsImplTest {
private static EhcacheStatsImpl stats;
@BeforeClass
public static void createCache() throws Exception {
CacheManager manager = CacheManager.getInstance();
stats = new EhcacheStatsImpl( manager );
}
@Test
public void testIsRegionCacheOrphanEvictionEnabled() {
assertThat( stats.isRegionCacheOrphanEvictionEnabled( "sampleCache1" ), is( false ) );
}
@Test
public void testGetRegionCacheOrphanEvictionPeriod() {
assertThat( stats.getRegionCacheOrphanEvictionPeriod( "sampleCache1" ), is( -1 ) );
}
}

View File

@ -1,248 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.cache;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cache.ehcache.internal.strategy.ItemValueExtractor;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.stat.QueryStatistics;
import org.hibernate.stat.CacheRegionStatistics;
import org.hibernate.stat.Statistics;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.hibernate.test.domain.Event;
import org.hibernate.test.domain.EventManager;
import org.hibernate.test.domain.Item;
import org.hibernate.test.domain.Person;
import org.hibernate.test.domain.PhoneNumber;
import org.hibernate.test.domain.VersionedItem;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* @author Chris Dennis
* @author Brett Meyer
*/
public class HibernateCacheTest extends BaseNonConfigCoreFunctionalTestCase {
private static final String REGION_PREFIX = "hibernate.test.";
public HibernateCacheTest() {
System.setProperty( "derby.system.home", "target/derby" );
}
@Override
@SuppressWarnings("unchecked")
protected void addSettings(Map settings) {
super.addSettings( settings );
settings.put( AvailableSettings.GENERATE_STATISTICS, "true" );
}
@Override
protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) {
super.configureStandardServiceRegistryBuilder( ssrb );
ssrb.configure( "hibernate-config/hibernate.cfg.xml" );
}
@Test
public void testQueryCacheInvalidation() throws Exception {
Session s = sessionFactory().openSession();
Transaction t = s.beginTransaction();
Item i = new Item();
i.setName( "widget" );
i.setDescription( "A really top-quality, full-featured widget." );
s.persist( i );
t.commit();
s.close();
CacheRegionStatistics slcs = sessionFactory()
.getStatistics()
.getDomainDataRegionStatistics( REGION_PREFIX + Item.class.getName() );
assertThat( slcs.getPutCount(), equalTo( 1L ) );
assertThat( slcs.getElementCountInMemory(), equalTo( 1L ) );
assertThat( slcs.getEntries().size(), equalTo( 1 ) );
s = sessionFactory().openSession();
t = s.beginTransaction();
i = (Item) s.get( Item.class, i.getId() );
assertThat( slcs.getHitCount(), equalTo( 1L ) );
assertThat( slcs.getMissCount(), equalTo( 0L ) );
i.setDescription( "A bog standard item" );
t.commit();
s.close();
assertThat( slcs.getPutCount(), equalTo( 2L ) );
Object entry = slcs.getEntries().get( i.getId() );
Map map;
if ( entry instanceof Map ) {
map = (Map) entry;
}
else {
map = ItemValueExtractor.getValue( entry );
}
assertThat( (String) map.get( "description" ), equalTo( "A bog standard item" ) );
assertThat( (String) map.get( "name" ), equalTo( "widget" ) );
// cleanup
s = sessionFactory().openSession();
t = s.beginTransaction();
s.delete( i );
t.commit();
s.close();
}
@Test
public void testEmptySecondLevelCacheEntry() throws Exception {
sessionFactory().getCache().evictEntityRegion( Item.class.getName() );
Statistics stats = sessionFactory().getStatistics();
stats.clear();
CacheRegionStatistics statistics = stats.getDomainDataRegionStatistics( REGION_PREFIX + Item.class.getName() );
Map cacheEntries = statistics.getEntries();
assertThat( cacheEntries.size(), equalTo( 0 ) );
}
@Test
public void testStaleWritesLeaveCacheConsistent() {
Session s = sessionFactory().openSession();
Transaction txn = s.beginTransaction();
VersionedItem item = new VersionedItem();
item.setName( "steve" );
item.setDescription( "steve's item" );
s.save( item );
txn.commit();
s.close();
Long initialVersion = item.getVersion();
// manually revert the version property
item.setVersion( item.getVersion() - 1 );
try {
s = sessionFactory().openSession();
txn = s.beginTransaction();
s.update( item );
txn.commit();
s.close();
fail( "expected stale write to fail" );
}
catch ( Throwable expected ) {
// expected behavior here
if ( txn != null ) {
try {
txn.rollback();
}
catch ( Throwable ignore ) {
}
}
}
finally {
if ( s != null && s.isOpen() ) {
try {
s.close();
}
catch ( Throwable ignore ) {
}
}
}
// check the version value in the cache...
CacheRegionStatistics slcs = sessionFactory().getStatistics()
.getDomainDataRegionStatistics( REGION_PREFIX + VersionedItem.class.getName() );
assertNotNull(slcs);
final Map entries = slcs.getEntries();
Object entry = entries.get( item.getId() );
Long cachedVersionValue;
if ( entry instanceof SoftLock ) {
//FIXME don't know what to test here
//cachedVersionValue = new Long( ( (ReadWriteCache.Lock) entry).getUnlockTimestamp() );
}
else {
cachedVersionValue = (Long) ( (Map) entry ).get( "_version" );
assertThat( initialVersion, equalTo( cachedVersionValue ) );
}
// cleanup
s = sessionFactory().openSession();
txn = s.beginTransaction();
item = (VersionedItem) s.load( VersionedItem.class, item.getId() );
s.delete( item );
txn.commit();
s.close();
}
@Test
public void testGeneralUsage() {
EventManager mgr = new EventManager( sessionFactory() );
Statistics stats = sessionFactory().getStatistics();
// create 3 persons Steve, Orion, Tim
Person stevePerson = new Person();
stevePerson.setFirstname( "Steve" );
stevePerson.setLastname( "Harris" );
Long steveId = mgr.createAndStorePerson( stevePerson );
mgr.addEmailToPerson( steveId, "steve@tc.com" );
mgr.addEmailToPerson( steveId, "sharrif@tc.com" );
mgr.addTalismanToPerson( steveId, "rabbit foot" );
mgr.addTalismanToPerson( steveId, "john de conqueroo" );
PhoneNumber p1 = new PhoneNumber();
p1.setNumberType( "Office" );
p1.setPhone( 111111 );
mgr.addPhoneNumberToPerson( steveId, p1 );
PhoneNumber p2 = new PhoneNumber();
p2.setNumberType( "Home" );
p2.setPhone( 222222 );
mgr.addPhoneNumberToPerson( steveId, p2 );
Person orionPerson = new Person();
orionPerson.setFirstname( "Orion" );
orionPerson.setLastname( "Letizi" );
Long orionId = mgr.createAndStorePerson( orionPerson );
mgr.addEmailToPerson( orionId, "orion@tc.com" );
mgr.addTalismanToPerson( orionId, "voodoo doll" );
Long timId = mgr.createAndStorePerson( "Tim", "Teck" );
mgr.addEmailToPerson( timId, "teck@tc.com" );
mgr.addTalismanToPerson( timId, "magic decoder ring" );
Long engMeetingId = mgr.createAndStoreEvent( "Eng Meeting", stevePerson, new Date() );
mgr.addPersonToEvent( steveId, engMeetingId );
mgr.addPersonToEvent( orionId, engMeetingId );
mgr.addPersonToEvent( timId, engMeetingId );
Long docMeetingId = mgr.createAndStoreEvent( "Doc Meeting", orionPerson, new Date() );
mgr.addPersonToEvent( steveId, docMeetingId );
mgr.addPersonToEvent( orionId, docMeetingId );
for ( Event event : (List<Event>) mgr.listEvents() ) {
mgr.listEmailsOfEvent( event.getId() );
}
QueryStatistics queryStats = stats.getQueryStatistics( "from Event" );
assertThat( "Cache Miss Count", queryStats.getCacheMissCount(), equalTo( 1L ) );
assertThat( "Cache Hit Count", queryStats.getCacheHitCount(), equalTo( 0L ) );
assertThat( "Cache Put Count", queryStats.getCachePutCount(), equalTo( 1L ) );
}
}

View File

@ -1,53 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.cache.ehcache;
import java.lang.reflect.Field;
import java.util.Map;
import org.hibernate.cache.ehcache.EhCacheRegionFactory;
import org.hibernate.cfg.Environment;
/**
* @author Alex Snaps
*/
public class EhCacheRegionFactoryImpl extends EhCacheTest {
@Override
@SuppressWarnings("unchecked")
protected void addSettings(Map settings) {
super.addSettings( settings );
settings.put( Environment.CACHE_REGION_FACTORY, EhCacheRegionFactory.class.getName() );
settings.put( Environment.CACHE_PROVIDER_CONFIG, "ehcache.xml" );
}
@Override
protected Map getMapFromCacheEntry(final Object entry) {
final Map map;
if ( "org.hibernate.cache.ehcache.internal.strategy.AbstractReadWriteEhcacheAccessStrategy$Item".equals(
entry.getClass()
.getName()
) ) {
try {
Field field = entry.getClass().getDeclaredField( "value" );
field.setAccessible( true );
map = (Map) field.get( entry );
}
catch ( NoSuchFieldException e ) {
throw new RuntimeException( e );
}
catch ( IllegalAccessException e ) {
throw new RuntimeException( e );
}
}
else {
map = (Map) entry;
}
return map;
}
}

View File

@ -1,41 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.cache.ehcache;
import java.util.Map;
import org.hibernate.cache.ehcache.EhCacheRegionFactory;
import org.hibernate.cache.ehcache.internal.strategy.ItemValueExtractor;
import org.hibernate.cfg.Environment;
/**
* @author Alex Snaps
*/
public class EhCacheRegionTest extends EhCacheTest {
@Override
@SuppressWarnings("unchecked")
protected void addSettings(Map settings) {
super.addSettings( settings );
settings.put( Environment.CACHE_REGION_FACTORY, EhCacheRegionFactory.class.getName() );
settings.put( Environment.CACHE_PROVIDER_CONFIG, "ehcache.xml" );
}
@Override
protected Map getMapFromCacheEntry(final Object entry) {
final Map map;
if ( entry.getClass()
.getName()
.equals( "org.hibernate.cache.ehcache.internal.strategy.AbstractReadWriteEhcacheAccessStrategy$Item" ) ) {
map = ItemValueExtractor.getValue( entry );
}
else {
map = (Map) entry;
}
return map;
}
}

View File

@ -1,188 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.cache.ehcache;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Environment;
import org.hibernate.stat.CacheRegionStatistics;
import org.hibernate.stat.Statistics;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Emmanuel Bernard
* @author Alex Snaps
*/
public abstract class EhCacheTest extends BaseNonConfigCoreFunctionalTestCase {
@Override
public String getBaseForMappings() {
return "org/hibernate/test/cache/ehcache/";
}
@Override
public String[] getMappings() {
return new String[] { "Item.hbm.xml" };
}
@Override
public String getCacheConcurrencyStrategy() {
return "read-write";
}
@Override
protected void addSettings(Map settings) {
super.addSettings( settings );
settings.put( Environment.CACHE_REGION_PREFIX, "" );
settings.put( Environment.USE_SECOND_LEVEL_CACHE, "true" );
settings.put( Environment.GENERATE_STATISTICS, "true" );
settings.put( Environment.USE_STRUCTURED_CACHE, "true" );
// settings.put( Environment.TRANSACTION_STRATEGY, JdbcTransactionFactory.class.getName() );
}
@Test
public void testQueryCacheInvalidation() {
Session s = openSession();
Transaction t = s.beginTransaction();
Item i = new Item();
i.setName( "widget" );
i.setDescription( "A really top-quality, full-featured widget." );
s.persist( i );
t.commit();
s.close();
CacheRegionStatistics slcs = s.getSessionFactory().getStatistics()
.getDomainDataRegionStatistics( Item.class.getName() );
assertEquals( slcs.getPutCount(), 1 );
assertEquals( slcs.getElementCountInMemory(), 1 );
assertEquals( slcs.getEntries().size(), 1 );
s = openSession();
t = s.beginTransaction();
i = (Item) s.get( Item.class, i.getId() );
assertEquals( slcs.getHitCount(), 1 );
assertEquals( slcs.getMissCount(), 0 );
i.setDescription( "A bog standard item" );
t.commit();
s.close();
assertEquals( slcs.getPutCount(), 2 );
Object entry = slcs.getEntries().get( i.getId() );
Map map;
map = getMapFromCacheEntry( entry );
assertTrue( map.get( "description" ).equals( "A bog standard item" ) );
assertTrue( map.get( "name" ).equals( "widget" ) );
// cleanup
s = openSession();
t = s.beginTransaction();
s.delete( i );
t.commit();
s.close();
}
protected abstract Map getMapFromCacheEntry(final Object entry);
@Test
public void testEmptySecondLevelCacheEntry() throws Exception {
sessionFactory().getCache().evictEntityRegion( Item.class.getName() );
Statistics stats = sessionFactory().getStatistics();
stats.clear();
CacheRegionStatistics statistics = stats.getDomainDataRegionStatistics( Item.class.getName() );
Map cacheEntries = statistics.getEntries();
assertEquals( 0, cacheEntries.size() );
}
@SuppressWarnings( { "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment" })
@Test
public void testStaleWritesLeaveCacheConsistent() {
Session s = openSession();
Transaction txn = s.beginTransaction();
VersionedItem item = new VersionedItem();
item.setName( "steve" );
item.setDescription( "steve's item" );
s.save( item );
txn.commit();
s.close();
Long initialVersion = item.getVersion();
// manually revert the version property
item.setVersion( Long.valueOf( item.getVersion().longValue() - 1 ) );
try {
s = openSession();
txn = s.beginTransaction();
s.update( item );
txn.commit();
s.close();
fail( "expected stale write to fail" );
}
catch ( Throwable expected ) {
// expected behavior here
if ( txn != null ) {
try {
txn.rollback();
}
catch ( Throwable ignore ) {
}
}
}
finally {
if ( s != null && s.isOpen() ) {
try {
s.close();
}
catch ( Throwable ignore ) {
}
}
}
// check the version value in the cache...
CacheRegionStatistics slcs = sessionFactory().getStatistics()
.getDomainDataRegionStatistics( VersionedItem.class.getName() );
Object entry = slcs.getEntries().get( item.getId() );
Long cachedVersionValue;
// if ( entry instanceof ReadWriteCache.Lock ) {
// //FIXME don't know what to test here
// cachedVersionValue = Long.valueOf( ((ReadWriteCache.Lock) entry).getUnlockTimestamp() );
// } else
if ( entry.getClass()
.getName()
.equals( "org.hibernate.cache.ehcache.internal.strategy.AbstractReadWriteEhcacheAccessStrategy$Lock" ) ) {
//FIXME don't know what to test here
}
else {
cachedVersionValue = (Long) getMapFromCacheEntry( entry ).get( "_version" );
assertEquals( initialVersion.longValue(), cachedVersionValue.longValue() );
}
// cleanup
s = openSession();
txn = s.beginTransaction();
item = (VersionedItem) s.load( VersionedItem.class, item.getId() );
s.delete( item );
txn.commit();
s.close();
}
}

View File

@ -1,31 +0,0 @@
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.test.cache.ehcache">
<class name="Item" table="Items">
<id name="id">
<generator class="increment"/>
</id>
<property name="name" not-null="true"/>
<property name="description" not-null="true"/>
</class>
<class name="VersionedItem" table="VersionedItems">
<id name="id">
<generator class="increment"/>
</id>
<version name="version" type="long"/>
<property name="name" not-null="true"/>
<property name="description" not-null="true"/>
</class>
</hibernate-mapping>

View File

@ -1,36 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.cache.ehcache;
/**
* @author Gavin King
*/
public class Item {
private Long id;
private String name;
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -1,22 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.cache.ehcache;
/**
* @author Steve Ebersole
*/
public class VersionedItem extends Item {
private Long version;
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}

View File

@ -1,277 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.cache.ehcache.functional;
import java.util.Map;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.Session;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* Tests for handling of data just inserted during a transaction being read from the database
* and placed into cache. Initially these cases went through putFromRead which causes problems because it
* loses the context of that data having just been read.
*
* @author Steve Ebersole
*/
public class InsertedDataTest extends BaseNonConfigCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] {CacheableItem.class};
}
@Override
@SuppressWarnings("unchecked")
protected void addSettings(Map settings) {
super.addSettings( settings );
settings.put( AvailableSettings.CACHE_REGION_PREFIX, "" );
settings.put( AvailableSettings.GENERATE_STATISTICS, "true" );
}
@Override
protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) {
super.configureStandardServiceRegistryBuilder( ssrb );
ssrb.configure( "hibernate-config/hibernate.cfg.xml" );
}
@Test
public void testInsert() {
sessionFactory().getCache().evictEntityRegions();
sessionFactory().getStatistics().clear();
Session s = openSession();
s.beginTransaction();
CacheableItem item = new CacheableItem( "data" );
s.save( item );
s.getTransaction().commit();
s.close();
Map cacheMap = sessionFactory().getStatistics().getDomainDataRegionStatistics( "item" ).getEntries();
assertEquals( 1, cacheMap.size() );
s = openSession();
s.beginTransaction();
s.createQuery( "delete CacheableItem" ).executeUpdate();
s.getTransaction().commit();
s.close();
}
@Test
public void testInsertWithRollback() {
sessionFactory().getCache().evictEntityRegions();
sessionFactory().getStatistics().clear();
Session s = openSession();
s.beginTransaction();
CacheableItem item = new CacheableItem( "data" );
s.save( item );
s.flush();
s.getTransaction().rollback();
s.close();
Map cacheMap = sessionFactory().getStatistics().getDomainDataRegionStatistics( "item" ).getEntries();
assertEquals( 0, cacheMap.size() );
}
@Test
public void testInsertThenUpdate() {
sessionFactory().getCache().evictEntityRegions();
sessionFactory().getStatistics().clear();
Session s = openSession();
s.beginTransaction();
CacheableItem item = new CacheableItem( "data" );
s.save( item );
s.flush();
item.setName( "new data" );
s.getTransaction().commit();
s.close();
Map cacheMap = sessionFactory().getStatistics().getDomainDataRegionStatistics( "item" ).getEntries();
assertEquals( 1, cacheMap.size() );
s = openSession();
s.beginTransaction();
s.createQuery( "delete CacheableItem" ).executeUpdate();
s.getTransaction().commit();
s.close();
}
@Test
public void testInsertThenUpdateThenRollback() {
sessionFactory().getCache().evictEntityRegions();
sessionFactory().getStatistics().clear();
Session s = openSession();
s.beginTransaction();
CacheableItem item = new CacheableItem( "data" );
s.save( item );
s.flush();
item.setName( "new data" );
s.getTransaction().rollback();
s.close();
Map cacheMap = sessionFactory().getStatistics().getDomainDataRegionStatistics( "item" ).getEntries();
assertEquals( 0, cacheMap.size() );
s = openSession();
s.beginTransaction();
s.createQuery( "delete CacheableItem" ).executeUpdate();
s.getTransaction().commit();
s.close();
}
@Test
public void testInsertWithRefresh() {
sessionFactory().getCache().evictEntityRegions();
sessionFactory().getStatistics().clear();
Session s = openSession();
s.beginTransaction();
CacheableItem item = new CacheableItem( "data" );
s.save( item );
s.flush();
s.refresh( item );
s.getTransaction().commit();
s.close();
Map cacheMap = sessionFactory().getStatistics().getDomainDataRegionStatistics( "item" ).getEntries();
assertEquals( 1, cacheMap.size() );
s = openSession();
s.beginTransaction();
s.createQuery( "delete CacheableItem" ).executeUpdate();
s.getTransaction().commit();
s.close();
}
@Test
public void testInsertWithRefreshThenRollback() {
sessionFactory().getCache().evictEntityRegions();
sessionFactory().getStatistics().clear();
Session s = openSession();
s.beginTransaction();
CacheableItem item = new CacheableItem( "data" );
s.save( item );
s.flush();
s.refresh( item );
s.getTransaction().rollback();
s.close();
Map cacheMap = sessionFactory().getStatistics().getDomainDataRegionStatistics( "item" ).getEntries();
assertEquals( 1, cacheMap.size() );
Object lock = cacheMap.values().iterator().next();
assertEquals( "org.hibernate.cache.ehcache.internal.strategy.AbstractReadWriteEhcacheAccessStrategy$Lock", lock.getClass().getName() );
s = openSession();
s.beginTransaction();
item = (CacheableItem) s.get( CacheableItem.class, item.getId() );
s.getTransaction().commit();
s.close();
assertNull( "it should be null", item );
}
@Test
public void testInsertWithClear() {
sessionFactory().getCache().evictEntityRegions();
sessionFactory().getStatistics().clear();
Session s = openSession();
s.beginTransaction();
CacheableItem item = new CacheableItem( "data" );
s.save( item );
s.flush();
s.clear();
s.getTransaction().commit();
s.close();
Map cacheMap = sessionFactory().getStatistics().getDomainDataRegionStatistics( "item" ).getEntries();
assertEquals( 1, cacheMap.size() );
s = openSession();
s.beginTransaction();
s.createQuery( "delete CacheableItem" ).executeUpdate();
s.getTransaction().commit();
s.close();
}
@Test
public void testInsertWithClearThenRollback() {
sessionFactory().getCache().evictEntityRegions();
sessionFactory().getStatistics().clear();
Session s = openSession();
s.beginTransaction();
CacheableItem item = new CacheableItem( "data" );
s.save( item );
s.flush();
s.clear();
item = (CacheableItem) s.get( CacheableItem.class, item.getId() );
s.getTransaction().rollback();
s.close();
Map cacheMap = sessionFactory().getStatistics().getDomainDataRegionStatistics( "item" ).getEntries();
assertEquals( 0, cacheMap.size() );
s = openSession();
s.beginTransaction();
item = (CacheableItem) s.get( CacheableItem.class, item.getId() );
s.getTransaction().commit();
s.close();
assertNull( "it should be null", item );
}
@Entity(name = "CacheableItem")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "item")
public static class CacheableItem {
private Long id;
private String name;
public CacheableItem() {
}
public CacheableItem(String name) {
this.name = name;
}
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}

View File

@ -1,369 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.cache.ehcache.functional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;
import org.hibernate.Session;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.jdbc.SQLServerSnapshotIsolationConnectionProvider;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author Zhenlei Huang
*/
@TestForIssue(jiraKey = "HHH-10649")
public class RefreshUpdatedDataTest extends BaseNonConfigCoreFunctionalTestCase {
private SQLServerSnapshotIsolationConnectionProvider connectionProvider;
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] {
ReadWriteCacheableItem.class,
ReadWriteVersionedCacheableItem.class,
NonStrictReadWriteCacheableItem.class,
NonStrictReadWriteVersionedCacheableItem.class,
};
}
@Override
@SuppressWarnings("unchecked")
protected void addSettings(Map settings) {
super.addSettings( settings );
if ( H2Dialect.class.equals( Dialect.getDialect().getClass() ) ) {
settings.put( Environment.URL, "jdbc:h2:mem:db-mvcc;MVCC=true" );
}
else if( SQLServerDialect.class.isAssignableFrom( Dialect.getDialect().getClass() )) {
connectionProvider = new SQLServerSnapshotIsolationConnectionProvider();
settings.put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
}
settings.put( AvailableSettings.GENERATE_STATISTICS, "true" );
}
@Override
protected void releaseResources() {
super.releaseResources();
if( SQLServerDialect.class.isAssignableFrom( Dialect.getDialect().getClass() )) {
connectionProvider.stop();
}
}
@Override
protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) {
super.configureStandardServiceRegistryBuilder( ssrb );
ssrb.configure( "hibernate-config/hibernate.cfg.xml" );
}
@Test
public void testUpdateAndFlushThenRefresh() {
// prepare data
Session s = openSession();
s.beginTransaction();
final String BEFORE = "before";
ReadWriteCacheableItem readWriteCacheableItem = new ReadWriteCacheableItem( BEFORE );
readWriteCacheableItem.getTags().add( "Hibernate" );
readWriteCacheableItem.getTags().add( "ORM" );
s.persist( readWriteCacheableItem );
ReadWriteVersionedCacheableItem readWriteVersionedCacheableItem = new ReadWriteVersionedCacheableItem( BEFORE );
readWriteVersionedCacheableItem.getTags().add( "Hibernate" );
readWriteVersionedCacheableItem.getTags().add( "ORM" );
s.persist( readWriteVersionedCacheableItem );
NonStrictReadWriteCacheableItem nonStrictReadWriteCacheableItem = new NonStrictReadWriteCacheableItem( BEFORE );
nonStrictReadWriteCacheableItem.getTags().add( "Hibernate" );
nonStrictReadWriteCacheableItem.getTags().add( "ORM" );
s.persist( nonStrictReadWriteCacheableItem );
NonStrictReadWriteVersionedCacheableItem nonStrictReadWriteVersionedCacheableItem = new NonStrictReadWriteVersionedCacheableItem( BEFORE );
nonStrictReadWriteVersionedCacheableItem.getTags().add( "Hibernate" );
nonStrictReadWriteVersionedCacheableItem.getTags().add( "ORM" );
s.persist( nonStrictReadWriteVersionedCacheableItem );
s.getTransaction().commit();
s.close();
Session s1 = openSession();
s1.beginTransaction();
final String AFTER = "after";
ReadWriteCacheableItem readWriteCacheableItem1 = s1.get( ReadWriteCacheableItem.class, readWriteCacheableItem.getId() );
readWriteCacheableItem1.setName( AFTER );
readWriteCacheableItem1.getTags().remove("ORM");
ReadWriteVersionedCacheableItem readWriteVersionedCacheableItem1 = s1.get( ReadWriteVersionedCacheableItem.class, readWriteVersionedCacheableItem.getId() );
readWriteVersionedCacheableItem1.setName( AFTER );
readWriteVersionedCacheableItem1.getTags().remove("ORM");
NonStrictReadWriteCacheableItem nonStrictReadWriteCacheableItem1 = s1.get( NonStrictReadWriteCacheableItem.class, nonStrictReadWriteCacheableItem.getId() );
nonStrictReadWriteCacheableItem1.setName( AFTER );
nonStrictReadWriteCacheableItem1.getTags().remove("ORM");
NonStrictReadWriteVersionedCacheableItem nonStrictReadWriteVersionedCacheableItem1 = s1.get( NonStrictReadWriteVersionedCacheableItem.class, nonStrictReadWriteVersionedCacheableItem.getId() );
nonStrictReadWriteVersionedCacheableItem1.setName( AFTER );
nonStrictReadWriteVersionedCacheableItem1.getTags().remove("ORM");
s1.flush();
s1.refresh( readWriteCacheableItem1 );
s1.refresh( readWriteVersionedCacheableItem1 );
s1.refresh( nonStrictReadWriteCacheableItem1 );
s1.refresh( nonStrictReadWriteVersionedCacheableItem1 );
assertEquals( AFTER, readWriteCacheableItem1.getName() );
assertEquals( 1, readWriteCacheableItem1.getTags().size() );
assertEquals( AFTER, readWriteVersionedCacheableItem1.getName() );
assertEquals( 1, readWriteVersionedCacheableItem1.getTags().size() );
assertEquals( AFTER, nonStrictReadWriteCacheableItem1.getName() );
assertEquals( 1, nonStrictReadWriteCacheableItem1.getTags().size() );
assertEquals( AFTER, nonStrictReadWriteVersionedCacheableItem1.getName() );
assertEquals( 1, nonStrictReadWriteVersionedCacheableItem1.getTags().size() );
// open another session
Session s2 = sessionFactory().openSession();
try {
s2.beginTransaction();
ReadWriteCacheableItem readWriteCacheableItem2 = s2.get( ReadWriteCacheableItem.class, readWriteCacheableItem.getId() );
ReadWriteVersionedCacheableItem readWriteVersionedCacheableItem2 = s2.get( ReadWriteVersionedCacheableItem.class, readWriteVersionedCacheableItem.getId() );
NonStrictReadWriteCacheableItem nonStrictReadWriteCacheableItem2 = s2.get( NonStrictReadWriteCacheableItem.class, nonStrictReadWriteCacheableItem.getId() );
NonStrictReadWriteVersionedCacheableItem nonStrictReadWriteVersionedCacheableItem2 = s2.get( NonStrictReadWriteVersionedCacheableItem.class, nonStrictReadWriteVersionedCacheableItem.getId() );
assertEquals( BEFORE, readWriteCacheableItem2.getName() );
assertEquals( 2, readWriteCacheableItem2.getTags().size() );
assertEquals( BEFORE, readWriteVersionedCacheableItem2.getName() );
assertEquals( 2, readWriteVersionedCacheableItem2.getTags().size() );
//READ_UNCOMMITTED because there is no locking to prevent collections from being cached in the first Session
assertEquals( BEFORE, nonStrictReadWriteCacheableItem2.getName() );
assertEquals( 1, nonStrictReadWriteCacheableItem2.getTags().size());
assertEquals( BEFORE, nonStrictReadWriteVersionedCacheableItem2.getName() );
assertEquals( 1, nonStrictReadWriteVersionedCacheableItem2.getTags().size() );
s2.getTransaction().commit();
}
finally {
if ( s2.getTransaction().getStatus().canRollback() ) {
s2.getTransaction().rollback();
}
s2.close();
}
s1.getTransaction().rollback();
s1.close();
s = openSession();
s.beginTransaction();
s.delete( readWriteCacheableItem );
s.delete( readWriteVersionedCacheableItem );
s.delete( nonStrictReadWriteCacheableItem );
s.delete( nonStrictReadWriteVersionedCacheableItem );
s.getTransaction().commit();
s.close();
}
@Entity(name = "ReadWriteCacheableItem")
@Table(name = "RW_ITEM")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "item")
public static class ReadWriteCacheableItem {
@Id
@GeneratedValue
private Long id;
private String name;
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@ElementCollection
private List<String> tags = new ArrayList<>();
public ReadWriteCacheableItem() {
}
public ReadWriteCacheableItem(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getTags() {
return tags;
}
}
@Entity(name = "ReadWriteVersionedCacheableItem")
@Table(name = "RW_VERSIONED_ITEM")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "item")
public static class ReadWriteVersionedCacheableItem {
@Id
@GeneratedValue
private Long id;
private String name;
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@ElementCollection
private List<String> tags = new ArrayList<>();
@Version
private int version;
public ReadWriteVersionedCacheableItem() {
}
public ReadWriteVersionedCacheableItem(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getTags() {
return tags;
}
}
@Entity(name = "NonStrictReadWriteCacheableItem")
@Table(name = "RW_NOSTRICT_ITEM")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "item")
public static class NonStrictReadWriteCacheableItem {
@Id
@GeneratedValue
private Long id;
private String name;
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@ElementCollection
private List<String> tags = new ArrayList<>();
public NonStrictReadWriteCacheableItem() {
}
public NonStrictReadWriteCacheableItem(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getTags() {
return tags;
}
}
@Entity(name = "NonStrictReadWriteVersionedCacheableItem")
@Table(name = "RW_NOSTRICT_VER_ITEM")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "item")
public static class NonStrictReadWriteVersionedCacheableItem {
@Id
@GeneratedValue
private Long id;
private String name;
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@ElementCollection
private List<String> tags = new ArrayList<>();
@Version
private int version;
public NonStrictReadWriteVersionedCacheableItem() {
}
public NonStrictReadWriteVersionedCacheableItem(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getTags() {
return tags;
}
}
}

View File

@ -1,38 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.domain;
public class Account {
private Long id;
private Person person;
public Account() {
//
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String toString() {
return super.toString();
}
}

View File

@ -1,74 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.domain;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class Event {
private Long id;
private String title;
private Date date;
private Set participants = new HashSet();
private Person organizer;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setOrganizer(Person organizer) {
this.organizer = organizer;
}
public Person getOrganizer() {
return organizer;
}
public Set getParticipants() {
return participants;
}
public void setParticipants(Set participants) {
this.participants = participants;
}
public void addParticipant(Person person) {
participants.add(person);
person.getEvents().add(this);
}
public void removeParticipant(Person person) {
participants.remove(person);
person.getEvents().remove(this);
}
public String toString() {
return getTitle() + ": " + getDate();
}
}

View File

@ -1,240 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.domain;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class EventManager {
private final SessionFactory sessionFactory;
public EventManager(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List listEmailsOfEvent(Long eventId) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
List emailList = new ArrayList();
Event event = (Event)session.load(Event.class, eventId);
for (Iterator it = event.getParticipants().iterator(); it.hasNext(); ) {
Person person = (Person)it.next();
emailList.addAll(person.getEmailAddresses());
}
session.getTransaction().commit();
return emailList;
}
public Long createAndStoreEvent(String title, Person organizer, Date theDate) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);
theEvent.setOrganizer(organizer);
Long eventId = (Long)session.save(theEvent);
session.getTransaction().commit();
return eventId;
}
public Long createAndStorePerson(String firstName, String lastName) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Person person = new Person();
person.setFirstname(firstName);
person.setLastname(lastName);
Long personId = (Long)session.save(person);
session.getTransaction().commit();
return personId;
}
public Long createAndStorePerson(Person person) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Long personId = (Long)session.save(person);
session.getTransaction().commit();
return personId;
}
public List listEvents() {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
List result = session.createQuery("from Event").setCacheable(true).list();
session.getTransaction().commit();
return result;
}
/**
* Call setEntity() on a cacheable query - see FORGE-265
*/
public List listEventsOfOrganizer(Person organizer) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("from Event ev where ev.organizer = :organizer");
query.setCacheable(true);
query.setEntity("organizer", organizer);
List result = query.list();
session.getTransaction().commit();
return result;
}
/**
* Use a Criteria query - see FORGE-247
*/
public List listEventsWithCriteria() {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
List result = session.createCriteria(Event.class)
.setCacheable(true)
.list();
session.getTransaction().commit();
return result;
}
public void addPersonToEvent(Long personId, Long eventId) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Person aPerson = (Person)session.load(Person.class, personId);
Event anEvent = (Event)session.load(Event.class, eventId);
aPerson.getEvents().add(anEvent);
session.getTransaction().commit();
}
public Long addPersonToAccount(Long personId, Account account) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Person aPerson = (Person)session.load(Person.class, personId);
account.setPerson(aPerson);
Long accountId = (Long)session.save(account);
session.getTransaction().commit();
return accountId;
}
public Account getAccount(Long accountId) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Account account = (Account)session.load(Account.class, accountId);
session.getTransaction().commit();
return account;
}
public void addEmailToPerson(Long personId, String emailAddress) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Person aPerson = (Person)session.load(Person.class, personId);
// The getEmailAddresses() might trigger a lazy load of the collection
aPerson.getEmailAddresses().add(emailAddress);
session.getTransaction().commit();
}
public void addPhoneNumberToPerson(Long personId, PhoneNumber pN) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Person aPerson = (Person)session.load(Person.class, personId);
pN.setPersonId(personId.longValue());
aPerson.getPhoneNumbers().add(pN);
session.getTransaction().commit();
}
public void addTalismanToPerson(Long personId, String talisman) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Person aPerson = (Person)session.load(Person.class, personId);
aPerson.addTalisman(talisman);
session.getTransaction().commit();
}
public Long createHolidayCalendar() {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
// delete all existing calendars
List calendars = session.createQuery("from HolidayCalendar").setCacheable(true).list();
for (ListIterator li = calendars.listIterator(); li.hasNext(); ) {
session.delete(li.next());
}
HolidayCalendar calendar = new HolidayCalendar();
calendar.init();
Long calendarId = (Long)session.save(calendar);
session.getTransaction().commit();
return calendarId;
}
public HolidayCalendar getHolidayCalendar() {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
List calendars = session.createQuery("from HolidayCalendar").setCacheable(true).list();
session.getTransaction().commit();
return calendars.isEmpty() ? null : (HolidayCalendar)calendars.get(0);
}
}

View File

@ -1,66 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.domain;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class HolidayCalendar {
private Long id;
// Date -> String
private Map holidays = new HashMap();
public HolidayCalendar init() {
DateFormat df = new SimpleDateFormat("yyyy.MM.dd");
try {
holidays.clear();
holidays.put(df.parse("2009.01.01"), "New Year's Day");
holidays.put(df.parse("2009.02.14"), "Valentine's Day");
holidays.put(df.parse("2009.11.11"), "Armistice Day");
} catch (ParseException e) {
throw new RuntimeException(e);
}
return this;
}
public Map getHolidays() {
return holidays;
}
protected void setHolidays(Map holidays) {
this.holidays = holidays;
}
public void addHoliday(Date d, String name) {
holidays.put(d, name);
}
public String getHoliday(Date d) {
return (String)holidays.get(d);
}
public boolean isHoliday(Date d) {
return holidays.containsKey(d);
}
protected Long getId() {
return id;
}
protected void setId(Long id) {
this.id = id;
}
}

View File

@ -1,37 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.domain;
public class Item {
private Long id;
private String name;
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -1,111 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.domain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Person {
private Long id;
private int age;
private String firstname;
private String lastname;
private List events = new ArrayList(); // list semantics, e.g., indexed
private Set emailAddresses = new HashSet();
private Set phoneNumbers = new HashSet();
private List talismans = new ArrayList(); // a Bag of good-luck charms.
public Person() {
//
}
public List getEvents() {
return events;
}
protected void setEvents(List events) {
this.events = events;
}
public void addToEvent(Event event) {
this.getEvents().add(event);
event.getParticipants().add(this);
}
public void removeFromEvent(Event event) {
this.getEvents().remove(event);
event.getParticipants().remove(this);
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Set getEmailAddresses() {
return emailAddresses;
}
public void setEmailAddresses(Set emailAddresses) {
this.emailAddresses = emailAddresses;
}
public Set getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(Set phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public void addTalisman(String name) {
talismans.add(name);
}
public List getTalismans() {
return talismans;
}
public void setTalismans(List talismans) {
this.talismans = talismans;
}
public String toString() {
return getFirstname() + " " + getLastname();
}
}

View File

@ -1,78 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.domain;
import java.io.Serializable;
/**
* PhoneNumber
*/
public class PhoneNumber implements Serializable {
private long personId = 0;
private String numberType = "home";
private long phone = 0;
public long getPersonId() {
return personId;
}
public void setPersonId(long personId) {
this.personId = personId;
}
public String getNumberType() {
return numberType;
}
public void setNumberType(String numberType) {
this.numberType = numberType;
}
public long getPhone() {
return phone;
}
public void setPhone(long phone) {
this.phone = phone;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((numberType == null) ? 0 : numberType.hashCode());
result = prime * result + (int)(personId ^ (personId >>> 32));
result = prime * result + (int)(phone ^ (phone >>> 32));
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final PhoneNumber other = (PhoneNumber)obj;
if (numberType == null) {
if (other.numberType != null)
return false;
} else if (!numberType.equals(other.numberType))
return false;
if (personId != other.personId)
return false;
if (phone != other.phone)
return false;
return true;
}
public String toString() {
return numberType + ":" + phone;
}
}

View File

@ -1,37 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.domain;
public class UuidItem {
private String id;
private String name;
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -1,19 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.domain;
public class VersionedItem extends Item {
private Long version;
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}

View File

@ -1,94 +0,0 @@
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<ehcache>
<!-- Sets the path to the directory where cache .data files are created.
If the path is a Java System Property it is replaced by
its value in the running VM.
The following properties are translated:
user.home - User's home directory
user.dir - User's current working directory
java.io.tmpdir - Default temp file path -->
<diskStore path="./target/tmp"/>
<!--Default Cache configuration. These will applied to caches programmatically created through
the CacheManager.
The following attributes are required for defaultCache:
maxInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.
-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<!--Predefined caches. Add your cache configuration settings here.
If you do not have a configuration for your cache a WARNING will be issued when the
CacheManager starts
The following attributes are required for defaultCache:
name - Sets the name of the cache. This is used to identify the cache. It must be unique.
maxInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.
-->
<!-- Sample cache named sampleCache1
This cache contains a maximum in memory of 10000 elements, and will expire
an element if it is idle for more than 5 minutes and lives for more than
10 minutes.
If there are more than 10000 elements it will overflow to the
disk cache, which in this configuration will go to wherever java.io.tmp is
defined on your system. On a standard Linux system this will be /tmp"
-->
<cache name="sampleCache1"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
<!-- Sample cache named sampleCache2
This cache contains 1000 elements. Elements will always be held in memory.
They are not expired. -->
<cache name="sampleCache2"
maxElementsInMemory="1000"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/> -->
<!-- Place configuration for your caches following -->
</ehcache>

View File

@ -1,25 +0,0 @@
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.hibernate.test.domain.Account" table="ACCOUNT" lazy="false">
<id name="id" column="ACCOUNT_ID">
<generator class="native"/>
</id>
<many-to-one name="person" class="org.hibernate.test.domain.Person" cascade="save-update,lock"
column="person_id"
unique="true"
not-null="true"/>
</class>
</hibernate-mapping>

Some files were not shown because too many files have changed in this diff Show More