From 11464ea0976343a27ddada0af4d0bca7182ce498 Mon Sep 17 00:00:00 2001
From: Strong Liu
Date: Mon, 22 Apr 2013 18:41:02 +0800
Subject: [PATCH 01/57] HHH-8127 OutOfMemoryError when running tests
---
.../testing/junit4/CustomRunner.java | 19 ++++++++++++++++++-
1 file changed, 18 insertions(+), 1 deletion(-)
diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/junit4/CustomRunner.java b/hibernate-testing/src/main/java/org/hibernate/testing/junit4/CustomRunner.java
index 2e3b8a6ac0..6dc6b197c0 100644
--- a/hibernate-testing/src/main/java/org/hibernate/testing/junit4/CustomRunner.java
+++ b/hibernate-testing/src/main/java/org/hibernate/testing/junit4/CustomRunner.java
@@ -100,7 +100,24 @@ public class CustomRunner extends BlockJUnit4ClassRunner {
return isAllTestsIgnored;
}
- @Override
+
+ @Override
+ public void run(RunNotifier notifier) {
+ super.run( notifier );
+
+ cleanup();
+ }
+
+ private void cleanup() {
+ if ( computedTestMethods != null && !computedTestMethods.isEmpty() ) {
+ computedTestMethods.clear();
+ computedTestMethods = null;
+ }
+ testInstance = null;
+ testClassMetadata = null;
+ }
+
+ @Override
protected Statement withBeforeClasses(Statement statement) {
if ( isAllTestsIgnored() ) {
return super.withBeforeClasses( statement );
From 63093dbfd9f227f059b38f33806a6882e3e34200 Mon Sep 17 00:00:00 2001
From: Steve Ebersole
Date: Mon, 22 Apr 2013 17:14:29 -0500
Subject: [PATCH 02/57] HHH-8159 - Apply fixups indicated by analysis tools
---
.../action/internal/EntityInsertAction.java | 3 +-
.../javassist/TransformingClassLoader.java | 2 +-
.../internal/CacheDataDescriptionImpl.java | 80 ++--
.../internal/NoCachingRegionFactory.java | 18 +-
.../internal/RegionFactoryInitiator.java | 41 +-
.../cache/internal/StandardQueryCache.java | 158 ++++---
.../internal/StandardQueryCacheFactory.java | 8 +-
.../cache/internal/package-info.java | 28 ++
.../cache/spi/UpdateTimestampsCache.java | 1 -
.../spi/entry/StructuredMapCacheEntry.java | 5 +-
.../java/org/hibernate/classic/Lifecycle.java | 12 +-
.../AbstractPersistentCollection.java | 300 +++++++------
.../internal/PersistentArrayHolder.java | 181 +++++---
.../collection/internal/PersistentBag.java | 380 +++++++++--------
.../internal/PersistentElementHolder.java | 218 ++++++----
.../internal/PersistentIdentifierBag.java | 295 ++++++++-----
.../PersistentIndexedElementHolder.java | 221 ++++++----
.../collection/internal/PersistentList.java | 402 ++++++++++--------
.../internal/PersistentListElementHolder.java | 58 ++-
.../collection/internal/PersistentMap.java | 345 ++++++++++-----
.../internal/PersistentMapElementHolder.java | 78 ++--
.../collection/internal/PersistentSet.java | 259 ++++++-----
.../internal/PersistentSortedMap.java | 208 +++++----
.../internal/PersistentSortedSet.java | 131 +++---
.../collection/internal/package-info.java | 28 ++
.../collection/spi/PersistentCollection.java | 220 ++++++++--
.../collection/spi/package-info.java | 28 ++
27 files changed, 2269 insertions(+), 1439 deletions(-)
create mode 100644 hibernate-core/src/main/java/org/hibernate/cache/internal/package-info.java
create mode 100644 hibernate-core/src/main/java/org/hibernate/collection/internal/package-info.java
create mode 100644 hibernate-core/src/main/java/org/hibernate/collection/spi/package-info.java
diff --git a/hibernate-core/src/main/java/org/hibernate/action/internal/EntityInsertAction.java b/hibernate-core/src/main/java/org/hibernate/action/internal/EntityInsertAction.java
index fba5c3e6ef..9c17828b15 100644
--- a/hibernate-core/src/main/java/org/hibernate/action/internal/EntityInsertAction.java
+++ b/hibernate-core/src/main/java/org/hibernate/action/internal/EntityInsertAction.java
@@ -48,7 +48,6 @@ import org.hibernate.persister.entity.EntityPersister;
* @see EntityIdentityInsertAction
*/
public final class EntityInsertAction extends AbstractEntityInsertAction {
-
private Object version;
private Object cacheEntry;
@@ -130,7 +129,7 @@ public final class EntityInsertAction extends AbstractEntityInsertAction {
version,
session
);
- cacheEntry = persister.getCacheEntryStructure().structure(ce);
+ cacheEntry = persister.getCacheEntryStructure().structure( ce );
final CacheKey ck = session.generateCacheKey( id, persister.getIdentifierType(), persister.getRootEntityName() );
final boolean put = persister.getCacheAccessStrategy().insert( ck, cacheEntry, version );
diff --git a/hibernate-core/src/main/java/org/hibernate/bytecode/internal/javassist/TransformingClassLoader.java b/hibernate-core/src/main/java/org/hibernate/bytecode/internal/javassist/TransformingClassLoader.java
index 96661cb461..53ad74fdd7 100644
--- a/hibernate-core/src/main/java/org/hibernate/bytecode/internal/javassist/TransformingClassLoader.java
+++ b/hibernate-core/src/main/java/org/hibernate/bytecode/internal/javassist/TransformingClassLoader.java
@@ -63,7 +63,7 @@ public class TransformingClassLoader extends ClassLoader {
try {
final CtClass cc = classPool.get( name );
// todo : modify the class definition if not already transformed...
- byte[] b = cc.toBytecode();
+ final byte[] b = cc.toBytecode();
return defineClass( name, b, 0, b.length );
}
catch (NotFoundException e) {
diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/CacheDataDescriptionImpl.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/CacheDataDescriptionImpl.java
index aa365cb5bf..e4917d1200 100644
--- a/hibernate-core/src/main/java/org/hibernate/cache/internal/CacheDataDescriptionImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/CacheDataDescriptionImpl.java
@@ -30,10 +30,11 @@ import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.PluralAttributeBinding;
-import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.type.VersionType;
/**
+ * Standard CacheDataDescription implementation.
+ *
* @author Steve Ebersole
*/
public class CacheDataDescriptionImpl implements CacheDataDescription {
@@ -41,48 +42,87 @@ public class CacheDataDescriptionImpl implements CacheDataDescription {
private final boolean versioned;
private final Comparator versionComparator;
+ /**
+ * Constructs a CacheDataDescriptionImpl instance. Generally speaking, code should use one of the
+ * overloaded {@link #decode} methods rather than direct instantiation.
+ *
+ * @param mutable Is the described data mutable?
+ * @param versioned Is the described data versioned?
+ * @param versionComparator The described data's version value comparator (if versioned).
+ */
public CacheDataDescriptionImpl(boolean mutable, boolean versioned, Comparator versionComparator) {
this.mutable = mutable;
this.versioned = versioned;
this.versionComparator = versionComparator;
}
+ @Override
public boolean isMutable() {
return mutable;
}
+ @Override
public boolean isVersioned() {
return versioned;
}
+ @Override
public Comparator getVersionComparator() {
return versionComparator;
}
+ /**
+ * Builds a CacheDataDescriptionImpl from the mapping model of an entity class.
+ *
+ * @param model The mapping model.
+ *
+ * @return The constructed CacheDataDescriptionImpl
+ */
public static CacheDataDescriptionImpl decode(PersistentClass model) {
return new CacheDataDescriptionImpl(
model.isMutable(),
model.isVersioned(),
- model.isVersioned() ? ( ( VersionType ) model.getVersion().getType() ).getComparator() : null
+ model.isVersioned()
+ ? ( (VersionType) model.getVersion().getType() ).getComparator()
+ : null
);
}
+ /**
+ * Builds a CacheDataDescriptionImpl from the mapping model of an entity class (using the new metamodel code).
+ *
+ * @param model The mapping model.
+ *
+ * @return The constructed CacheDataDescriptionImpl
+ */
public static CacheDataDescriptionImpl decode(EntityBinding model) {
- return new CacheDataDescriptionImpl(
- model.isMutable(),
- model.isVersioned(),
- getVersionComparator( model )
- );
+ return new CacheDataDescriptionImpl( model.isMutable(), model.isVersioned(), getVersionComparator( model ) );
}
+ /**
+ * Builds a CacheDataDescriptionImpl from the mapping model of a collection
+ *
+ * @param model The mapping model.
+ *
+ * @return The constructed CacheDataDescriptionImpl
+ */
public static CacheDataDescriptionImpl decode(Collection model) {
return new CacheDataDescriptionImpl(
model.isMutable(),
model.getOwner().isVersioned(),
- model.getOwner().isVersioned() ? ( ( VersionType ) model.getOwner().getVersion().getType() ).getComparator() : null
+ model.getOwner().isVersioned()
+ ? ( (VersionType) model.getOwner().getVersion().getType() ).getComparator()
+ : null
);
}
+ /**
+ * Builds a CacheDataDescriptionImpl from the mapping model of a collection (using the new metamodel code).
+ *
+ * @param model The mapping model.
+ *
+ * @return The constructed CacheDataDescriptionImpl
+ */
public static CacheDataDescriptionImpl decode(PluralAttributeBinding model) {
return new CacheDataDescriptionImpl(
model.isMutable(),
@@ -91,24 +131,16 @@ public class CacheDataDescriptionImpl implements CacheDataDescription {
);
}
- public static CacheDataDescriptionImpl decode(EntityPersister persister) {
- return new CacheDataDescriptionImpl(
- !persister.getEntityMetamodel().hasImmutableNaturalId(),
- false,
- null
- );
- }
-
private static Comparator getVersionComparator(EntityBinding model ) {
- Comparator versionComparator = null;
if ( model.isVersioned() ) {
- versionComparator = (
- ( VersionType ) model.getHierarchyDetails()
- .getVersioningAttributeBinding()
- .getHibernateTypeDescriptor()
- .getResolvedTypeMapping()
- ).getComparator();
+ final VersionType versionType = (VersionType) model.getHierarchyDetails()
+ .getVersioningAttributeBinding()
+ .getHibernateTypeDescriptor()
+ .getResolvedTypeMapping();
+
+ return versionType.getComparator();
}
- return versionComparator;
+
+ return null;
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/NoCachingRegionFactory.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/NoCachingRegionFactory.java
index 7d16fb3e5a..1d52e51630 100644
--- a/hibernate-core/src/main/java/org/hibernate/cache/internal/NoCachingRegionFactory.java
+++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/NoCachingRegionFactory.java
@@ -43,48 +43,64 @@ import org.hibernate.cfg.Settings;
* @author Steve Ebersole
*/
public class NoCachingRegionFactory implements RegionFactory {
+ /**
+ * Singleton access
+ */
public static final NoCachingRegionFactory INSTANCE = new NoCachingRegionFactory();
+ /**
+ * Constructs a NoCachingRegionFactory. Although access should generally use {@link #INSTANCE}
+ */
public NoCachingRegionFactory() {
}
+ @Override
public void start(Settings settings, Properties properties) throws CacheException {
}
+ @Override
public void stop() {
}
+ @Override
public boolean isMinimalPutsEnabledByDefault() {
return false;
}
+ @Override
public AccessType getDefaultAccessType() {
return null;
}
+ @Override
public long nextTimestamp() {
return System.currentTimeMillis() / 100;
}
+ @Override
public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
throw new NoCacheRegionFactoryAvailableException();
}
-
+
+ @Override
public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
throw new NoCacheRegionFactoryAvailableException();
}
+ @Override
public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
throw new NoCacheRegionFactoryAvailableException();
}
+ @Override
public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException {
throw new NoCacheRegionFactoryAvailableException();
}
+ @Override
public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException {
throw new NoCacheRegionFactoryAvailableException();
}
diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java
index 65b13cb453..ffa33b8e72 100644
--- a/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java
@@ -28,8 +28,6 @@ import java.util.Map;
import org.hibernate.boot.registry.StandardServiceInitiator;
import org.hibernate.boot.registry.selector.spi.StrategySelector;
import org.hibernate.cache.spi.RegionFactory;
-import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
-import org.hibernate.service.spi.ServiceException;
import org.hibernate.service.spi.ServiceRegistryImplementor;
/**
@@ -38,6 +36,9 @@ import org.hibernate.service.spi.ServiceRegistryImplementor;
* @author Hardy Ferentschik
*/
public class RegionFactoryInitiator implements StandardServiceInitiator {
+ /**
+ * Singleton access
+ */
public static final RegionFactoryInitiator INSTANCE = new RegionFactoryInitiator();
/**
@@ -59,35 +60,17 @@ public class RegionFactoryInitiator implements StandardServiceInitiator customImplClass = null;
-// if ( Class.class.isInstance( setting ) ) {
-// customImplClass = (Class extends RegionFactory>) setting;
-// }
-// else {
-// customImplClass = registry.getService( ClassLoaderService.class )
-// .classForName( mapLegacyNames( setting.toString() ) );
-// }
-//
-// try {
-// return customImplClass.newInstance();
-// }
-// catch ( Exception e ) {
-// throw new ServiceException(
-// "Could not initialize custom RegionFactory impl [" + customImplClass.getName() + "]", e
-// );
-// }
}
- // todo this shouldn't be public (nor really static):
- // hack for org.hibernate.cfg.SettingsFactory.createRegionFactory()
+ /**
+ * Map legacy names unto the new corollary.
+ *
+ * todo this shouldn't be public, nor really static. hack for org.hibernate.cfg.SettingsFactory.createRegionFactory()
+ *
+ * @param name The (possibly legacy) factory name
+ *
+ * @return The factory name to use.
+ */
public static String mapLegacyNames(final String name) {
if ( "org.hibernate.cache.EhCacheRegionFactory".equals( name ) ) {
return "org.hibernate.cache.ehcache.EhCacheRegionFactory";
diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCache.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCache.java
index 9cb2c7daa7..9d2abf41fb 100644
--- a/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCache.java
+++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCache.java
@@ -48,14 +48,13 @@ import org.hibernate.type.TypeHelper;
/**
* The standard implementation of the Hibernate QueryCache interface. This
* implementation is very good at recognizing stale query results and
- * and re-running queries when it detects this condition, recaching the new
+ * and re-running queries when it detects this condition, re-caching the new
* results.
*
* @author Gavin King
* @author Steve Ebersole
*/
public class StandardQueryCache implements QueryCache {
-
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class,
StandardQueryCache.class.getName()
@@ -67,28 +66,54 @@ public class StandardQueryCache implements QueryCache {
private QueryResultsRegion cacheRegion;
private UpdateTimestampsCache updateTimestampsCache;
- public void clear() throws CacheException {
- cacheRegion.evictAll();
- }
-
+ /**
+ * Constructs a StandardQueryCache instance
+ *
+ * @param settings The SessionFactory settings.
+ * @param props Any properties
+ * @param updateTimestampsCache The update-timestamps cache to use.
+ * @param regionName The base query cache region name
+ */
public StandardQueryCache(
final Settings settings,
final Properties props,
final UpdateTimestampsCache updateTimestampsCache,
- String regionName) throws HibernateException {
- if ( regionName == null ) {
- regionName = StandardQueryCache.class.getName();
+ final String regionName) {
+ String regionNameToUse = regionName;
+ if ( regionNameToUse == null ) {
+ regionNameToUse = StandardQueryCache.class.getName();
}
- String prefix = settings.getCacheRegionPrefix();
+ final String prefix = settings.getCacheRegionPrefix();
if ( prefix != null ) {
- regionName = prefix + '.' + regionName;
+ regionNameToUse = prefix + '.' + regionNameToUse;
}
- LOG.startingQueryCache( regionName );
+ LOG.startingQueryCache( regionNameToUse );
- this.cacheRegion = settings.getRegionFactory().buildQueryResultsRegion( regionName, props );
+ this.cacheRegion = settings.getRegionFactory().buildQueryResultsRegion( regionNameToUse, props );
this.updateTimestampsCache = updateTimestampsCache;
}
+ @Override
+ public QueryResultsRegion getRegion() {
+ return cacheRegion;
+ }
+
+ @Override
+ public void destroy() {
+ try {
+ cacheRegion.destroy();
+ }
+ catch ( Exception e ) {
+ LOG.unableToDestroyQueryCache( cacheRegion.getName(), e.getMessage() );
+ }
+ }
+
+ @Override
+ public void clear() throws CacheException {
+ cacheRegion.evictAll();
+ }
+
+ @Override
@SuppressWarnings({ "unchecked" })
public boolean put(
final QueryKey key,
@@ -99,20 +124,21 @@ public class StandardQueryCache implements QueryCache {
if ( isNaturalKeyLookup && result.isEmpty() ) {
return false;
}
- long ts = cacheRegion.nextTimestamp();
+ final long ts = cacheRegion.nextTimestamp();
- if ( DEBUGGING ) LOG.debugf( "Caching query results in region: %s; timestamp=%s", cacheRegion.getName(), ts );
+ if ( DEBUGGING ) {
+ LOG.debugf( "Caching query results in region: %s; timestamp=%s", cacheRegion.getName(), ts );
+ }
- List cacheable = new ArrayList( result.size() + 1 );
+ final List cacheable = new ArrayList( result.size() + 1 );
logCachedResultDetails( key, null, returnTypes, cacheable );
cacheable.add( ts );
- final boolean singleResult = returnTypes.length == 1;
+
+ final boolean isSingleResult = returnTypes.length == 1;
for ( Object aResult : result ) {
- Serializable cacheItem = singleResult ? returnTypes[0].disassemble(
- aResult,
- session,
- null
- ) : TypeHelper.disassemble( (Object[]) aResult, returnTypes, null, session, null );
+ final Serializable cacheItem = isSingleResult
+ ? returnTypes[0].disassemble( aResult, session, null )
+ : TypeHelper.disassemble( (Object[]) aResult, returnTypes, null, session, null );
cacheable.add( cacheItem );
logCachedResultRowDetails( returnTypes, aResult );
}
@@ -121,6 +147,7 @@ public class StandardQueryCache implements QueryCache {
return true;
}
+ @Override
@SuppressWarnings({ "unchecked" })
public List get(
final QueryKey key,
@@ -128,23 +155,31 @@ public class StandardQueryCache implements QueryCache {
final boolean isNaturalKeyLookup,
final Set spaces,
final SessionImplementor session) throws HibernateException {
- if ( DEBUGGING ) LOG.debugf( "Checking cached query results in region: %s", cacheRegion.getName() );
+ if ( DEBUGGING ) {
+ LOG.debugf( "Checking cached query results in region: %s", cacheRegion.getName() );
+ }
- List cacheable = (List) cacheRegion.get( key );
+ final List cacheable = (List) cacheRegion.get( key );
logCachedResultDetails( key, spaces, returnTypes, cacheable );
if ( cacheable == null ) {
- if ( DEBUGGING ) LOG.debug( "Query results were not found in cache" );
+ if ( DEBUGGING ) {
+ LOG.debug( "Query results were not found in cache" );
+ }
return null;
}
- Long timestamp = (Long) cacheable.get( 0 );
+ final Long timestamp = (Long) cacheable.get( 0 );
if ( !isNaturalKeyLookup && !isUpToDate( spaces, timestamp ) ) {
- if ( DEBUGGING ) LOG.debug( "Cached query results were not up-to-date" );
+ if ( DEBUGGING ) {
+ LOG.debug( "Cached query results were not up-to-date" );
+ }
return null;
}
- if ( DEBUGGING ) LOG.debug( "Returning cached query results" );
+ if ( DEBUGGING ) {
+ LOG.debug( "Returning cached query results" );
+ }
final boolean singleResult = returnTypes.length == 1;
for ( int i = 1; i < cacheable.size(); i++ ) {
if ( singleResult ) {
@@ -154,7 +189,8 @@ public class StandardQueryCache implements QueryCache {
TypeHelper.beforeAssemble( (Serializable[]) cacheable.get( i ), returnTypes, session );
}
}
- List result = new ArrayList( cacheable.size() - 1 );
+
+ final List result = new ArrayList( cacheable.size() - 1 );
for ( int i = 1; i < cacheable.size(); i++ ) {
try {
if ( singleResult ) {
@@ -168,16 +204,18 @@ public class StandardQueryCache implements QueryCache {
logCachedResultRowDetails( returnTypes, result.get( i - 1 ) );
}
catch ( RuntimeException ex ) {
- if ( isNaturalKeyLookup &&
- ( UnresolvableObjectException.class.isInstance( ex ) ||
- EntityNotFoundException.class.isInstance( ex ) ) ) {
- //TODO: not really completely correct, since
- // the uoe could occur while resolving
- // associations, leaving the PC in an
- // inconsistent state
- if ( DEBUGGING ) LOG.debug( "Unable to reassemble cached result set" );
- cacheRegion.evict( key );
- return null;
+ if ( isNaturalKeyLookup ) {
+ // potentially perform special handling for natural-id look ups.
+ if ( UnresolvableObjectException.class.isInstance( ex )
+ || EntityNotFoundException.class.isInstance( ex ) ) {
+ if ( DEBUGGING ) {
+ LOG.debug( "Unable to reassemble cached natural-id query result" );
+ }
+ cacheRegion.evict( key );
+
+ // EARLY EXIT !!!!!
+ return null;
+ }
}
throw ex;
}
@@ -186,23 +224,12 @@ public class StandardQueryCache implements QueryCache {
}
protected boolean isUpToDate(final Set spaces, final Long timestamp) {
- if ( DEBUGGING ) LOG.debugf( "Checking query spaces are up-to-date: %s", spaces );
+ if ( DEBUGGING ) {
+ LOG.debugf( "Checking query spaces are up-to-date: %s", spaces );
+ }
return updateTimestampsCache.isUpToDate( spaces, timestamp );
}
- public void destroy() {
- try {
- cacheRegion.destroy();
- }
- catch ( Exception e ) {
- LOG.unableToDestroyQueryCache( cacheRegion.getName(), e.getMessage() );
- }
- }
-
- public QueryResultsRegion getRegion() {
- return cacheRegion;
- }
-
@Override
public String toString() {
return "StandardQueryCache(" + cacheRegion.getName() + ')';
@@ -222,12 +249,13 @@ public class StandardQueryCache implements QueryCache {
);
}
else {
- StringBuilder returnTypeInfo = new StringBuilder();
- for ( int i = 0; i < returnTypes.length; i++ ) {
+ final StringBuilder returnTypeInfo = new StringBuilder();
+ for ( Type returnType : returnTypes ) {
returnTypeInfo.append( "typename=" )
- .append( returnTypes[i].getName() )
+ .append( returnType.getName() )
.append( " class=" )
- .append( returnTypes[i].getReturnedClass().getName() ).append( ' ' );
+ .append( returnType.getReturnedClass().getName() )
+ .append( ' ' );
}
LOG.trace( "unexpected returnTypes is " + returnTypeInfo.toString() + "! result" );
}
@@ -248,7 +276,10 @@ public class StandardQueryCache implements QueryCache {
return;
}
if ( tuple == null ) {
- LOG.trace( " tuple is null; returnTypes is " + returnTypes == null ? "null" : "Type[" + returnTypes.length + "]" );
+ LOG.tracef(
+ "tuple is null; returnTypes is %s",
+ returnTypes == null ? "null" : "Type[" + returnTypes.length + "]"
+ );
if ( returnTypes != null && returnTypes.length > 1 ) {
LOG.trace(
"Unexpected result tuple! tuple is null; should be Object["
@@ -263,8 +294,12 @@ public class StandardQueryCache implements QueryCache {
+ ( returnTypes == null ? "null" : "empty" )
);
}
- LOG.trace( " tuple is Object[" + tuple.length + "]; returnTypes is Type[" + returnTypes.length + "]" );
- if ( tuple.length != returnTypes.length ) {
+ LOG.tracef(
+ "tuple is Object[%s]; returnTypes is %s",
+ tuple.length,
+ returnTypes == null ? "null" : "Type[" + returnTypes.length + "]"
+ );
+ if ( returnTypes != null && tuple.length != returnTypes.length ) {
LOG.trace(
"Unexpected tuple length! transformer= expected="
+ returnTypes.length + " got=" + tuple.length
@@ -272,7 +307,8 @@ public class StandardQueryCache implements QueryCache {
}
else {
for ( int j = 0; j < tuple.length; j++ ) {
- if ( tuple[j] != null && !returnTypes[j].getReturnedClass().isInstance( tuple[j] ) ) {
+ if ( tuple[j] != null && returnTypes != null
+ && ! returnTypes[j].getReturnedClass().isInstance( tuple[j] ) ) {
LOG.trace(
"Unexpected tuple value type! transformer= expected="
+ returnTypes[j].getReturnedClass().getName()
diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCacheFactory.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCacheFactory.java
index 26f742dc5f..7b584d0be6 100644
--- a/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCacheFactory.java
+++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCacheFactory.java
@@ -38,10 +38,10 @@ import org.hibernate.cfg.Settings;
public class StandardQueryCacheFactory implements QueryCacheFactory {
@Override
public QueryCache getQueryCache(
- final String regionName,
- final UpdateTimestampsCache updateTimestampsCache,
- final Settings settings,
- final Properties props) throws HibernateException {
+ final String regionName,
+ final UpdateTimestampsCache updateTimestampsCache,
+ final Settings settings,
+ final Properties props) throws HibernateException {
return new StandardQueryCache(settings, props, updateTimestampsCache, regionName);
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/package-info.java
new file mode 100644
index 0000000000..39a20475e8
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/package-info.java
@@ -0,0 +1,28 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2013, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+
+/**
+ * Internal implementations and support for second-level caching.
+ */
+package org.hibernate.cache.internal;
diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/UpdateTimestampsCache.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/UpdateTimestampsCache.java
index 59d7c637cb..470174044c 100644
--- a/hibernate-core/src/main/java/org/hibernate/cache/spi/UpdateTimestampsCache.java
+++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/UpdateTimestampsCache.java
@@ -29,7 +29,6 @@ import java.util.Set;
import org.jboss.logging.Logger;
-import org.hibernate.HibernateException;
import org.hibernate.cache.CacheException;
import org.hibernate.cfg.Settings;
import org.hibernate.engine.spi.SessionFactoryImplementor;
diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/entry/StructuredMapCacheEntry.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/entry/StructuredMapCacheEntry.java
index a896e09b44..d7bb2c786a 100755
--- a/hibernate-core/src/main/java/org/hibernate/cache/spi/entry/StructuredMapCacheEntry.java
+++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/entry/StructuredMapCacheEntry.java
@@ -45,8 +45,9 @@ public class StructuredMapCacheEntry implements CacheEntryStructure {
public Object structure(Object item) {
final CollectionCacheEntry entry = (CollectionCacheEntry) item;
final Serializable[] state = entry.getState();
- final Map map = new HashMap(state.length);
- for ( int i=0; i() {
@Override
public Boolean doWork() {
- CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
+ final CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
if ( entry != null ) {
- CollectionPersister persister = entry.getLoadedPersister();
+ final CollectionPersister persister = entry.getLoadedPersister();
if ( persister.isExtraLazy() ) {
if ( hasQueuedOperations() ) {
session.flush();
@@ -168,7 +184,17 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
return false;
}
+ /**
+ * TBH not sure why this is public
+ *
+ * @param The java type of the return for this LazyInitializationWork
+ */
public static interface LazyInitializationWork {
+ /**
+ * Do the represented work and return the result.
+ *
+ * @return The result
+ */
public T doWork();
}
@@ -221,7 +247,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
// be created even if a current session and transaction are
// open (ex: session.clear() was used). We must prevent
// multiple transactions.
- ( ( Session) session ).beginTransaction();
+ ( (Session) session ).beginTransaction();
}
session.getPersistenceContext().addUninitializedDetachedCollection(
@@ -238,7 +264,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
// make sure the just opened temp session gets closed!
try {
if ( !isJTA ) {
- ( ( Session) session ).getTransaction().commit();
+ ( (Session) session ).getTransaction().commit();
}
( (Session) session ).close();
}
@@ -255,19 +281,19 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
throwLazyInitializationException( "SessionFactory UUID not known to create temporary Session for loading" );
}
- SessionFactoryImplementor sf = (SessionFactoryImplementor)
+ final SessionFactoryImplementor sf = (SessionFactoryImplementor)
SessionFactoryRegistry.INSTANCE.getSessionFactory( sessionFactoryUuid );
return (SessionImplementor) sf.openSession();
}
protected Boolean readIndexExistence(final Object index) {
if ( !initialized ) {
- Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded(
+ final Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded(
new LazyInitializationWork() {
@Override
public Boolean doWork() {
- CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
- CollectionPersister persister = entry.getLoadedPersister();
+ final CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
+ final CollectionPersister persister = entry.getLoadedPersister();
if ( persister.isExtraLazy() ) {
if ( hasQueuedOperations() ) {
session.flush();
@@ -290,12 +316,12 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
protected Boolean readElementExistence(final Object element) {
if ( !initialized ) {
- Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded(
+ final Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded(
new LazyInitializationWork() {
@Override
public Boolean doWork() {
- CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
- CollectionPersister persister = entry.getLoadedPersister();
+ final CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
+ final CollectionPersister persister = entry.getLoadedPersister();
if ( persister.isExtraLazy() ) {
if ( hasQueuedOperations() ) {
session.flush();
@@ -326,8 +352,8 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
@Override
public Object doWork() {
- CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
- CollectionPersister persister = entry.getLoadedPersister();
+ final CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
+ final CollectionPersister persister = entry.getLoadedPersister();
isExtraLazy = persister.isExtraLazy();
if ( isExtraLazy ) {
if ( hasQueuedOperations() ) {
@@ -342,7 +368,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
}
- ExtraLazyElementByIndexReader reader = new ExtraLazyElementByIndexReader();
+ final ExtraLazyElementByIndexReader reader = new ExtraLazyElementByIndexReader();
//noinspection unchecked
withTemporarySessionIfNeeded( reader );
if ( reader.isExtraLazy ) {
@@ -358,9 +384,9 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
private boolean isConnectedToSession() {
- return session != null &&
- session.isOpen() &&
- session.getPersistenceContext().containsCollection( this );
+ return session != null
+ && session.isOpen()
+ && session.getPersistenceContext().containsCollection( this );
}
/**
@@ -377,9 +403,9 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
*/
@SuppressWarnings({"JavaDoc"})
protected boolean isOperationQueueEnabled() {
- return !initialized &&
- isConnectedToSession() &&
- isInverseCollection();
+ return !initialized
+ && isConnectedToSession()
+ && isInverseCollection();
}
/**
@@ -389,9 +415,9 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
*/
@SuppressWarnings({"JavaDoc"})
protected boolean isPutQueueEnabled() {
- return !initialized &&
- isConnectedToSession() &&
- isInverseOneToManyOrNoOrphanDelete();
+ return !initialized
+ && isConnectedToSession()
+ && isInverseOneToManyOrNoOrphanDelete();
}
/**
@@ -401,9 +427,9 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
*/
@SuppressWarnings({"JavaDoc"})
protected boolean isClearQueueEnabled() {
- return !initialized &&
- isConnectedToSession() &&
- isInverseCollectionNoOrphanDelete();
+ return !initialized
+ && isConnectedToSession()
+ && isInverseCollectionNoOrphanDelete();
}
/**
@@ -411,7 +437,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
*/
@SuppressWarnings({"JavaDoc"})
private boolean isInverseCollection() {
- CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
+ final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
return ce != null && ce.getLoadedPersister().isInverse();
}
@@ -421,8 +447,9 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
*/
@SuppressWarnings({"JavaDoc"})
private boolean isInverseCollectionNoOrphanDelete() {
- CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
- return ce != null &&
+ final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
+ return ce != null
+ &&
ce.getLoadedPersister().isInverse() &&
!ce.getLoadedPersister().hasOrphanDelete();
}
@@ -433,11 +460,10 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
*/
@SuppressWarnings({"JavaDoc"})
private boolean isInverseOneToManyOrNoOrphanDelete() {
- CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
- return ce != null && ce.getLoadedPersister().isInverse() && (
- ce.getLoadedPersister().isOneToMany() ||
- !ce.getLoadedPersister().hasOrphanDelete()
- );
+ final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
+ return ce != null
+ && ce.getLoadedPersister().isInverse()
+ && ( ce.getLoadedPersister().isOneToMany() || !ce.getLoadedPersister().hasOrphanDelete() );
}
/**
@@ -449,7 +475,8 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
operationQueue = new ArrayList( 10 );
}
operationQueue.add( operation );
- dirty = true; //needed so that we remove this collection from the second-level cache
+ //needed so that we remove this collection from the second-level cache
+ dirty = true;
}
/**
@@ -462,59 +489,38 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
}
- /**
- * After flushing, re-init snapshot state.
- */
+ @Override
public void setSnapshot(Serializable key, String role, Serializable snapshot) {
this.key = key;
this.role = role;
this.storedSnapshot = snapshot;
}
- /**
- * After flushing, clear any "queued" additions, since the
- * database state is now synchronized with the memory state.
- */
+ @Override
public void postAction() {
operationQueue = null;
cachedSize = -1;
clearDirty();
}
- /**
- * Not called by Hibernate, but used by non-JDK serialization,
- * eg. SOAP libraries.
- */
- public AbstractPersistentCollection() {
- }
-
- protected AbstractPersistentCollection(SessionImplementor session) {
- this.session = session;
- }
-
- /**
- * return the user-visible collection (or array) instance
- */
+ @Override
public Object getValue() {
return this;
}
- /**
- * Called just before reading any rows from the JDBC result set
- */
+ @Override
public void beginRead() {
// override on some subclasses
initializing = true;
}
- /**
- * Called after reading all rows from the JDBC result set
- */
+ @Override
public boolean endRead() {
//override on some subclasses
return afterInitialize();
}
+ @Override
public boolean afterInitialize() {
setInitialized();
//do this bit after setting initialized to true or it will recurse
@@ -579,19 +585,12 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
this.directlyAccessible = directlyAccessible;
}
- /**
- * Could the application possibly have a direct reference to
- * the underlying collection implementation?
- */
+ @Override
public boolean isDirectlyAccessible() {
return directlyAccessible;
}
- /**
- * Disassociate this collection from the given session.
- *
- * @return true if this was currently associated with the given session
- */
+ @Override
public final boolean unsetSession(SessionImplementor currentSession) {
prepareForPossibleSpecialSpecjInitialization();
if ( currentSession == this.session ) {
@@ -619,21 +618,14 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
- /**
- * Associate the collection with the given session.
- *
- * @return false if the collection was already associated with the session
- *
- * @throws HibernateException if the collection was already associated
- * with another open session
- */
+ @Override
public final boolean setCurrentSession(SessionImplementor session) throws HibernateException {
if ( session == this.session ) {
return false;
}
else {
if ( isConnectedToSession() ) {
- CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
+ final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
if ( ce == null ) {
throw new HibernateException(
"Illegal attempt to associate a collection with two open sessions"
@@ -656,17 +648,12 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
}
- /**
- * Do we need to completely recreate this collection when it changes?
- */
+ @Override
public boolean needsRecreate(CollectionPersister persister) {
return false;
}
- /**
- * To be called internally by the session, forcing
- * immediate initialization.
- */
+ @Override
public final void forceInitialization() throws HibernateException {
if ( !initialized ) {
if ( initializing ) {
@@ -691,40 +678,38 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
return session.getPersistenceContext().getSnapshot( this );
}
- /**
- * Is this instance initialized?
- */
+ @Override
public final boolean wasInitialized() {
return initialized;
}
+ @Override
public boolean isRowUpdatePossible() {
return true;
}
- /**
- * Does this instance have any "queued" additions?
- */
+ @Override
public final boolean hasQueuedOperations() {
return operationQueue != null;
}
- /**
- * Iterate the "queued" additions
- */
+ @Override
public final Iterator queuedAdditionIterator() {
if ( hasQueuedOperations() ) {
return new Iterator() {
- int i = 0;
+ private int index;
+ @Override
public Object next() {
- return operationQueue.get( i++ ).getAddedInstance();
+ return operationQueue.get( index++ ).getAddedInstance();
}
+ @Override
public boolean hasNext() {
- return i < operationQueue.size();
+ return index < operationQueue.size();
}
+ @Override
public void remove() {
throw new UnsupportedOperationException();
}
@@ -735,14 +720,12 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
}
- /**
- * Iterate the "queued" additions
- */
+ @Override
@SuppressWarnings({"unchecked"})
public final Collection getQueuedOrphans(String entityName) {
if ( hasQueuedOperations() ) {
- Collection additions = new ArrayList( operationQueue.size() );
- Collection removals = new ArrayList( operationQueue.size() );
+ final Collection additions = new ArrayList( operationQueue.size() );
+ final Collection removals = new ArrayList( operationQueue.size() );
for ( DelayedOperation operation : operationQueue ) {
additions.add( operation.getAddedInstance() );
removals.add( operation.getOrphan() );
@@ -754,28 +737,22 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
}
- /**
- * Called before inserting rows, to ensure that any surrogate keys
- * are fully generated
- */
+ @Override
public void preInsert(CollectionPersister persister) throws HibernateException {
}
- /**
- * Called after inserting a row, to fetch the natively generated id
- */
+ @Override
public void afterRowInsert(CollectionPersister persister, Object entry, int i) throws HibernateException {
}
- /**
- * get all "orphaned" elements
- */
+ @Override
public abstract Collection getOrphans(Serializable snapshot, String entityName) throws HibernateException;
/**
- * Get the current session
+ * Get the session currently associated with this collection.
+ *
+ * @return The session
*/
- @SuppressWarnings({"JavaDoc"})
public final SessionImplementor getSession() {
return session;
}
@@ -787,19 +764,21 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
this.itr = itr;
}
+ @Override
public boolean hasNext() {
return itr.hasNext();
}
+ @Override
public Object next() {
return itr.next();
}
+ @Override
public void remove() {
write();
itr.remove();
}
-
}
protected final class ListIteratorProxy implements ListIterator {
@@ -809,47 +788,55 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
this.itr = itr;
}
+ @Override
@SuppressWarnings({"unchecked"})
public void add(Object o) {
write();
itr.add( o );
}
+ @Override
public boolean hasNext() {
return itr.hasNext();
}
+ @Override
public boolean hasPrevious() {
return itr.hasPrevious();
}
+ @Override
public Object next() {
return itr.next();
}
+ @Override
public int nextIndex() {
return itr.nextIndex();
}
+ @Override
public Object previous() {
return itr.previous();
}
+ @Override
public int previousIndex() {
return itr.previousIndex();
}
+ @Override
public void remove() {
write();
itr.remove();
}
+ @Override
@SuppressWarnings({"unchecked"})
public void set(Object o) {
write();
itr.set( o );
}
-
}
protected class SetProxy implements java.util.Set {
@@ -859,67 +846,82 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
this.set = set;
}
+ @Override
@SuppressWarnings({"unchecked"})
public boolean add(Object o) {
write();
return set.add( o );
}
+ @Override
@SuppressWarnings({"unchecked"})
public boolean addAll(Collection c) {
write();
return set.addAll( c );
}
+ @Override
public void clear() {
write();
set.clear();
}
+ @Override
public boolean contains(Object o) {
return set.contains( o );
}
+ @Override
+ @SuppressWarnings("unchecked")
public boolean containsAll(Collection c) {
return set.containsAll( c );
}
+ @Override
public boolean isEmpty() {
return set.isEmpty();
}
+ @Override
public Iterator iterator() {
return new IteratorProxy( set.iterator() );
}
+ @Override
public boolean remove(Object o) {
write();
return set.remove( o );
}
+ @Override
+ @SuppressWarnings("unchecked")
public boolean removeAll(Collection c) {
write();
return set.removeAll( c );
}
+ @Override
+ @SuppressWarnings("unchecked")
public boolean retainAll(Collection c) {
write();
return set.retainAll( c );
}
+ @Override
public int size() {
return set.size();
}
+ @Override
public Object[] toArray() {
return set.toArray();
}
+ @Override
@SuppressWarnings({"unchecked"})
public Object[] toArray(Object[] array) {
return set.toArray( array );
}
-
}
protected final class ListProxy implements java.util.List {
@@ -969,6 +971,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
@Override
+ @SuppressWarnings("unchecked")
public boolean containsAll(Collection c) {
return list.containsAll( c );
}
@@ -1021,12 +1024,14 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
@Override
+ @SuppressWarnings("unchecked")
public boolean removeAll(Collection c) {
write();
return list.removeAll( c );
}
@Override
+ @SuppressWarnings("unchecked")
public boolean retainAll(Collection c) {
write();
return list.retainAll( c );
@@ -1087,34 +1092,36 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
// short-circuit(s)
if ( currentElements.size() == 0 ) {
- return oldElements; // no new elements, the old list contains only Orphans
+ // no new elements, the old list contains only Orphans
+ return oldElements;
}
if ( oldElements.size() == 0 ) {
- return oldElements; // no old elements, so no Orphans neither
+ // no old elements, so no Orphans neither
+ return oldElements;
}
final EntityPersister entityPersister = session.getFactory().getEntityPersister( entityName );
final Type idType = entityPersister.getIdentifierType();
// create the collection holding the Orphans
- Collection res = new ArrayList();
+ final Collection res = new ArrayList();
// collect EntityIdentifier(s) of the *current* elements - add them into a HashSet for fast access
- java.util.Set currentIds = new HashSet();
- java.util.Set currentSaving = new IdentitySet();
+ final java.util.Set currentIds = new HashSet();
+ final java.util.Set currentSaving = new IdentitySet();
for ( Object current : currentElements ) {
if ( current != null && ForeignKeys.isNotTransient( entityName, current, null, session ) ) {
- EntityEntry ee = session.getPersistenceContext().getEntry( current );
+ final EntityEntry ee = session.getPersistenceContext().getEntry( current );
if ( ee != null && ee.getStatus() == Status.SAVING ) {
currentSaving.add( current );
}
else {
- Serializable currentId = ForeignKeys.getEntityIdentifierIfNotUnsaved(
+ final Serializable currentId = ForeignKeys.getEntityIdentifierIfNotUnsaved(
entityName,
current,
session
);
- currentIds.add( new TypedValue( idType, currentId, entityPersister.getEntityMode() ) );
+ currentIds.add( new TypedValue( idType, currentId ) );
}
}
}
@@ -1122,8 +1129,8 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
// iterate over the *old* list
for ( Object old : oldElements ) {
if ( !currentSaving.contains( old ) ) {
- Serializable oldId = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, old, session );
- if ( !currentIds.contains( new TypedValue( idType, oldId, entityPersister.getEntityMode() ) ) ) {
+ final Serializable oldId = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, old, session );
+ if ( !currentIds.contains( new TypedValue( idType, oldId ) ) ) {
res.add( old );
}
}
@@ -1132,20 +1139,28 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
return res;
}
+ /**
+ * Removes entity entries that have an equal identifier with the incoming entity instance
+ *
+ * @param list The list containing the entity instances
+ * @param entityInstance The entity instance to match elements.
+ * @param entityName The entity name
+ * @param session The session
+ */
public static void identityRemove(
Collection list,
- Object object,
+ Object entityInstance,
String entityName,
- SessionImplementor session) throws HibernateException {
+ SessionImplementor session) {
- if ( object != null && ForeignKeys.isNotTransient( entityName, object, null, session ) ) {
+ if ( entityInstance != null && ForeignKeys.isNotTransient( entityName, entityInstance, null, session ) ) {
final EntityPersister entityPersister = session.getFactory().getEntityPersister( entityName );
- Type idType = entityPersister.getIdentifierType();
+ final Type idType = entityPersister.getIdentifierType();
- Serializable idOfCurrent = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, object, session );
- Iterator itr = list.iterator();
+ final Serializable idOfCurrent = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, entityInstance, session );
+ final Iterator itr = list.iterator();
while ( itr.hasNext() ) {
- Serializable idOfOld = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, itr.next(), session );
+ final Serializable idOfOld = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, itr.next(), session );
if ( idType.isEqual( idOfCurrent, idOfOld, session.getFactory() ) ) {
itr.remove();
break;
@@ -1155,14 +1170,17 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
}
+ @Override
public Object getIdentifier(Object entry, int i) {
throw new UnsupportedOperationException();
}
+ @Override
public Object getOwner() {
return owner;
}
+ @Override
public void setOwner(Object owner) {
this.owner = owner;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentArrayHolder.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentArrayHolder.java
index 9ddd1d21aa..8243f08562 100644
--- a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentArrayHolder.java
+++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentArrayHolder.java
@@ -29,6 +29,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.Iterator;
import org.jboss.logging.Logger;
@@ -48,27 +49,52 @@ import org.hibernate.type.Type;
* @author Gavin King
*/
public class PersistentArrayHolder extends AbstractPersistentCollection {
- protected Object array;
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ PersistentArrayHolder.class.getName()
+ );
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, PersistentArrayHolder.class.getName());
+ protected Object array;
//just to help out during the load (ugly, i know)
private transient Class elementClass;
private transient java.util.List tempList;
+ /**
+ * Constructs a PersistentCollection instance for holding an array.
+ *
+ * @param session The session
+ * @param array The array (the persistent "collection").
+ */
public PersistentArrayHolder(SessionImplementor session, Object array) {
- super(session);
+ super( session );
this.array = array;
setInitialized();
}
+ /**
+ * Constructs a PersistentCollection instance for holding an array.
+ *
+ * @param session The session
+ * @param persister The persister for the array
+ */
+ public PersistentArrayHolder(SessionImplementor session, CollectionPersister persister) {
+ super( session );
+ elementClass = persister.getElementClass();
+ }
+
+
+
+ @Override
public Serializable getSnapshot(CollectionPersister persister) throws HibernateException {
- int length = /*(array==null) ? tempList.size() :*/ Array.getLength(array);
- Serializable result = (Serializable) Array.newInstance( persister.getElementClass(), length );
+// final int length = (array==null) ? tempList.size() : Array.getLength( array );
+ final int length = Array.getLength( array );
+ final Serializable result = (Serializable) Array.newInstance( persister.getElementClass(), length );
for ( int i=0; i deletes = new ArrayList();
- Serializable sn = getSnapshot();
- int snSize = Array.getLength(sn);
- int arraySize = Array.getLength(array);
+ final java.util.List deletes = new ArrayList();
+ final Serializable sn = getSnapshot();
+ final int snSize = Array.getLength( sn );
+ final int arraySize = Array.getLength( array );
int end;
if ( snSize > arraySize ) {
- for ( int i=arraySize; i= Array.getLength(sn) || Array.get(sn, i)==null );
+ final Serializable sn = getSnapshot();
+ return Array.get( array, i ) != null && ( i >= Array.getLength( sn ) || Array.get( sn, i ) == null );
}
+ @Override
public boolean needsUpdating(Object entry, int i, Type elemType) throws HibernateException {
- Serializable sn = getSnapshot();
- return i semantics for a
// !
+ @Override
+ @SuppressWarnings("unchecked")
public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula) throws HibernateException {
- //if ( !persister.isOneToMany() ) throw new AssertionFailure("Not implemented for Bags");
- Type elementType = persister.getElementType();
- ArrayList deletes = new ArrayList();
- List sn = (List) getSnapshot();
- Iterator olditer = sn.iterator();
+ final Type elementType = persister.getElementType();
+ final ArrayList deletes = new ArrayList();
+ final List sn = (List) getSnapshot();
+ final Iterator olditer = sn.iterator();
int i=0;
while ( olditer.hasNext() ) {
- Object old = olditer.next();
- Iterator newiter = bag.iterator();
+ final Object old = olditer.next();
+ final Iterator newiter = bag.iterator();
boolean found = false;
- if ( bag.size()>i && elementType.isSame( old, bag.get(i++) ) ) {
+ if ( bag.size()>i && elementType.isSame( old, bag.get( i++ ) ) ) {
//a shortcut if its location didn't change!
found = true;
}
@@ -202,104 +237,91 @@ public class PersistentBag extends AbstractPersistentCollection implements List
}
}
}
- if (!found) deletes.add(old);
+ if ( !found ) {
+ deletes.add( old );
+ }
}
return deletes.iterator();
}
+ @Override
public boolean needsInserting(Object entry, int i, Type elemType) throws HibernateException {
- //if ( !persister.isOneToMany() ) throw new AssertionFailure("Not implemented for Bags");
- List sn = (List) getSnapshot();
- if ( sn.size()>i && elemType.isSame( sn.get(i), entry ) ) {
- //a shortcut if its location didn't change!
+ final List sn = (List) getSnapshot();
+ if ( sn.size() > i && elemType.isSame( sn.get( i ), entry ) ) {
+ //a shortcut if its location didn't change!
return false;
}
else {
//search for it
//note that this code is incorrect for other than one-to-many
- Iterator olditer = sn.iterator();
- while ( olditer.hasNext() ) {
- Object old = olditer.next();
- if ( elemType.isSame( old, entry ) ) return false;
+ for ( Object old : sn ) {
+ if ( elemType.isSame( old, entry ) ) {
+ return false;
+ }
}
return true;
}
}
+ @Override
public boolean isRowUpdatePossible() {
return false;
}
+ @Override
public boolean needsUpdating(Object entry, int i, Type elemType) {
- //if ( !persister.isOneToMany() ) throw new AssertionFailure("Not implemented for Bags");
return false;
}
- /**
- * @see java.util.Collection#size()
- */
+ @Override
public int size() {
return readSize() ? getCachedSize() : bag.size();
}
- /**
- * @see java.util.Collection#isEmpty()
- */
+ @Override
public boolean isEmpty() {
return readSize() ? getCachedSize()==0 : bag.isEmpty();
}
- /**
- * @see java.util.Collection#contains(Object)
- */
+ @Override
+ @SuppressWarnings("UnnecessaryUnboxing")
public boolean contains(Object object) {
- Boolean exists = readElementExistence(object);
- return exists==null ?
- bag.contains(object) :
- exists.booleanValue();
+ final Boolean exists = readElementExistence( object );
+ return exists == null ? bag.contains( object ) : exists.booleanValue();
}
- /**
- * @see java.util.Collection#iterator()
- */
+ @Override
public Iterator iterator() {
read();
return new IteratorProxy( bag.iterator() );
}
- /**
- * @see java.util.Collection#toArray()
- */
+ @Override
public Object[] toArray() {
read();
return bag.toArray();
}
- /**
- * @see java.util.Collection#toArray(Object[])
- */
+ @Override
public Object[] toArray(Object[] a) {
read();
- return bag.toArray(a);
+ return bag.toArray( a );
}
- /**
- * @see java.util.Collection#add(Object)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public boolean add(Object object) {
if ( !isOperationQueueEnabled() ) {
write();
- return bag.add(object);
+ return bag.add( object );
}
else {
- queueOperation( new SimpleAdd(object) );
+ queueOperation( new SimpleAdd( object ) );
return true;
}
}
- /**
- * @see java.util.Collection#remove(Object)
- */
+ @Override
public boolean remove(Object o) {
initialize( true );
if ( bag.remove( o ) ) {
@@ -311,35 +333,33 @@ public class PersistentBag extends AbstractPersistentCollection implements List
}
}
- /**
- * @see java.util.Collection#containsAll(Collection)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public boolean containsAll(Collection c) {
read();
- return bag.containsAll(c);
+ return bag.containsAll( c );
}
- /**
- * @see java.util.Collection#addAll(Collection)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public boolean addAll(Collection values) {
- if ( values.size()==0 ) return false;
+ if ( values.size()==0 ) {
+ return false;
+ }
if ( !isOperationQueueEnabled() ) {
write();
- return bag.addAll(values);
+ return bag.addAll( values );
}
else {
- Iterator iter = values.iterator();
- while ( iter.hasNext() ) {
- queueOperation( new SimpleAdd( iter.next() ) );
+ for ( Object value : values ) {
+ queueOperation( new SimpleAdd( value ) );
}
return values.size()>0;
}
}
- /**
- * @see java.util.Collection#removeAll(Collection)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public boolean removeAll(Collection c) {
if ( c.size()>0 ) {
initialize( true );
@@ -356,9 +376,8 @@ public class PersistentBag extends AbstractPersistentCollection implements List
}
}
- /**
- * @see java.util.Collection#retainAll(Collection)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public boolean retainAll(Collection c) {
initialize( true );
if ( bag.retainAll( c ) ) {
@@ -370,9 +389,8 @@ public class PersistentBag extends AbstractPersistentCollection implements List
}
}
- /**
- * @see java.util.Collection#clear()
- */
+ @Override
+ @SuppressWarnings("unchecked")
public void clear() {
if ( isClearQueueEnabled() ) {
queueOperation( new Clear() );
@@ -386,160 +404,161 @@ public class PersistentBag extends AbstractPersistentCollection implements List
}
}
+ @Override
public Object getIndex(Object entry, int i, CollectionPersister persister) {
throw new UnsupportedOperationException("Bags don't have indexes");
}
+ @Override
public Object getElement(Object entry) {
return entry;
}
+ @Override
public Object getSnapshotElement(Object entry, int i) {
- List sn = (List) getSnapshot();
- return sn.get(i);
+ final List sn = (List) getSnapshot();
+ return sn.get( i );
}
+ /**
+ * Count how many times the given object occurs in the elements
+ *
+ * @param o The object to check
+ *
+ * @return The number of occurences.
+ */
+ @SuppressWarnings("UnusedDeclaration")
public int occurrences(Object o) {
read();
- Iterator iter = bag.iterator();
- int result=0;
- while ( iter.hasNext() ) {
- if ( o.equals( iter.next() ) ) result++;
+ final Iterator itr = bag.iterator();
+ int result = 0;
+ while ( itr.hasNext() ) {
+ if ( o.equals( itr.next() ) ) {
+ result++;
+ }
}
return result;
}
// List OPERATIONS:
- /**
- * @see java.util.List#add(int, Object)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public void add(int i, Object o) {
write();
- bag.add(i, o);
+ bag.add( i, o );
}
- /**
- * @see java.util.List#addAll(int, Collection)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public boolean addAll(int i, Collection c) {
- if ( c.size()>0 ) {
+ if ( c.size() > 0 ) {
write();
- return bag.addAll(i, c);
+ return bag.addAll( i, c );
}
else {
return false;
}
}
- /**
- * @see java.util.List#get(int)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public Object get(int i) {
read();
- return bag.get(i);
+ return bag.get( i );
}
- /**
- * @see java.util.List#indexOf(Object)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public int indexOf(Object o) {
read();
- return bag.indexOf(o);
+ return bag.indexOf( o );
}
- /**
- * @see java.util.List#lastIndexOf(Object)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public int lastIndexOf(Object o) {
read();
- return bag.lastIndexOf(o);
+ return bag.lastIndexOf( o );
}
- /**
- * @see java.util.List#listIterator()
- */
+ @Override
+ @SuppressWarnings("unchecked")
public ListIterator listIterator() {
read();
return new ListIteratorProxy( bag.listIterator() );
}
- /**
- * @see java.util.List#listIterator(int)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public ListIterator listIterator(int i) {
read();
- return new ListIteratorProxy( bag.listIterator(i) );
+ return new ListIteratorProxy( bag.listIterator( i ) );
}
- /**
- * @see java.util.List#remove(int)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public Object remove(int i) {
write();
- return bag.remove(i);
+ return bag.remove( i );
}
- /**
- * @see java.util.List#set(int, Object)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public Object set(int i, Object o) {
write();
- return bag.set(i, o);
+ return bag.set( i, o );
}
- /**
- * @see java.util.List#subList(int, int)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public List subList(int start, int end) {
read();
- return new ListProxy( bag.subList(start, end) );
+ return new ListProxy( bag.subList( start, end ) );
}
+ @Override
+ public boolean entryExists(Object entry, int i) {
+ return entry!=null;
+ }
+
+ @Override
public String toString() {
read();
return bag.toString();
}
- /*public boolean equals(Object other) {
- read();
- return bag.equals(other);
- }
-
- public int hashCode(Object other) {
- read();
- return bag.hashCode();
- }*/
-
- public boolean entryExists(Object entry, int i) {
- return entry!=null;
- }
-
/**
* Bag does not respect the collection API and do an
* JVM instance comparison to do the equals.
* The semantic is broken not to have to initialize a
* collection for a simple equals() operation.
* @see java.lang.Object#equals(java.lang.Object)
+ *
+ * {@inheritDoc}
*/
+ @Override
public boolean equals(Object obj) {
- return super.equals(obj);
+ return super.equals( obj );
}
- /**
- * @see java.lang.Object#hashCode()
- */
+ @Override
public int hashCode() {
return super.hashCode();
}
final class Clear implements DelayedOperation {
+ @Override
public void operate() {
bag.clear();
}
+
+ @Override
public Object getAddedInstance() {
return null;
}
+
+ @Override
public Object getOrphan() {
throw new UnsupportedOperationException("queued clear cannot be used with orphan delete");
}
@@ -551,12 +570,19 @@ public class PersistentBag extends AbstractPersistentCollection implements List
public SimpleAdd(Object value) {
this.value = value;
}
+
+ @Override
+ @SuppressWarnings("unchecked")
public void operate() {
- bag.add(value);
+ bag.add( value );
}
+
+ @Override
public Object getAddedInstance() {
return value;
}
+
+ @Override
public Object getOrphan() {
return null;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentElementHolder.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentElementHolder.java
index 6719fec238..0519943f49 100755
--- a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentElementHolder.java
+++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentElementHolder.java
@@ -52,191 +52,227 @@ import org.hibernate.type.Type;
* HHH-7783 for more information.
*/
@Deprecated
+@SuppressWarnings("UnusedDeclaration")
public class PersistentElementHolder extends AbstractPersistentCollection {
protected Element element;
+ /**
+ * Constructs a PersistentElementHolder
+ *
+ * @param session The session
+ * @param element The DOM element
+ */
+ @SuppressWarnings("UnusedDeclaration")
public PersistentElementHolder(SessionImplementor session, Element element) {
- super(session);
+ super( session );
this.element = element;
setInitialized();
}
- public Serializable getSnapshot(CollectionPersister persister)
- throws HibernateException {
+ /**
+ * Constructs a PersistentElementHolder
+ *
+ * @param session The session
+ * @param persister The collection persister
+ * @param key The collection key (the fk value)
+ */
+ @SuppressWarnings("UnusedDeclaration")
+ public PersistentElementHolder(SessionImplementor session, CollectionPersister persister, Serializable key) {
+ super( session );
+ final Element owner = (Element) session.getPersistenceContext().getCollectionOwner( key, persister );
+ if ( owner == null ) {
+ throw new AssertionFailure("null owner");
+ }
+ final String nodeName = persister.getNodeName();
+ if ( ".".equals( nodeName ) ) {
+ element = owner;
+ }
+ else {
+ element = owner.element( nodeName );
+ if ( element == null ) {
+ element = owner.addElement( nodeName );
+ }
+ }
+ }
+
+ @Override
+ @SuppressWarnings({"unchecked", "deprecation"})
+ public Serializable getSnapshot(CollectionPersister persister) throws HibernateException {
final Type elementType = persister.getElementType();
- List elements = element.elements( persister.getElementNodeName() );
- ArrayList snapshot = new ArrayList( elements.size() );
- for ( int i=0; i= elements.size() ) {
- result.add(old);
+ result.add( old );
}
else {
- Element elem = (Element) elements.get(i);
- Object object = elementType.fromXMLNode( elem, persister.getFactory() );
- if ( elementType.isDirty( old, object, getSession() ) ) result.add(old);
+ final Element elem = (Element) elements.get( i );
+ final Object object = elementType.fromXMLNode( elem, persister.getFactory() );
+ if ( elementType.isDirty( old, object, getSession() ) ) {
+ result.add( old );
+ }
}
}
return result.iterator();
-
}
- public boolean needsInserting(Object entry, int i, Type elementType)
- throws HibernateException {
- ArrayList snapshot = (ArrayList) getSnapshot();
- return i>=snapshot.size() || elementType.isDirty( snapshot.get(i), entry, getSession() );
+ @Override
+ public boolean needsInserting(Object entry, int i, Type elementType) throws HibernateException {
+ final ArrayList snapshot = (ArrayList) getSnapshot();
+ return i >= snapshot.size()
+ || elementType.isDirty( snapshot.get( i ), entry, getSession() );
}
- public boolean needsUpdating(Object entry, int i, Type elementType)
- throws HibernateException {
+ @Override
+ public boolean needsUpdating(Object entry, int i, Type elementType) throws HibernateException {
return false;
}
+ @Override
public Object getIndex(Object entry, int i, CollectionPersister persister) {
throw new UnsupportedOperationException();
}
+ @Override
public Object getElement(Object entry) {
return entry;
}
+ @Override
public Object getSnapshotElement(Object entry, int i) {
throw new UnsupportedOperationException();
}
+ @Override
public boolean entryExists(Object entry, int i) {
return entry!=null;
}
-
}
diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIdentifierBag.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIdentifierBag.java
index beac3d457b..bacd39429f 100644
--- a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIdentifierBag.java
+++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIdentifierBag.java
@@ -53,37 +53,53 @@ import org.hibernate.type.Type;
* @author Gavin King
*/
public class PersistentIdentifierBag extends AbstractPersistentCollection implements List {
+ protected List
+ *
* IMPL NOTE: There is meant to be a one-to-one correspondence between a {@link org.hibernate.internal.SessionImpl}
* and a PersistentContext. Event listeners and other Session collaborators then use the PersistentContext to drive
* their processing.
@@ -90,14 +89,13 @@ import org.hibernate.type.CollectionType;
* @author Steve Ebersole
*/
public class StatefulPersistenceContext implements PersistenceContext {
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ StatefulPersistenceContext.class.getName()
+ );
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, StatefulPersistenceContext.class.getName() );
-
- private static final boolean tracing = LOG.isTraceEnabled();
-
- public static final Object NO_ROW = new MarkerObject( "NO_ROW" );
-
- public static final int INIT_COLL_SIZE = 8;
+ private static final boolean TRACE_ENABLED = LOG.isTraceEnabled();
+ private static final int INIT_COLL_SIZE = 8;
private SessionImplementor session;
@@ -144,12 +142,12 @@ public class StatefulPersistenceContext implements PersistenceContext {
// May be empty or not contains all relation
private Map parentsByChild;
- private int cascading = 0;
- private int loadCounter = 0;
- private boolean flushing = false;
+ private int cascading;
+ private int loadCounter;
+ private boolean flushing;
- private boolean defaultReadOnly = false;
- private boolean hasNonReadOnlyEntities = false;
+ private boolean defaultReadOnly;
+ private boolean hasNonReadOnlyEntities;
private LoadContexts loadContexts;
private BatchFetchQueue batchFetchQueue;
@@ -280,8 +278,8 @@ public class StatefulPersistenceContext implements PersistenceContext {
@Override
public void setEntryStatus(EntityEntry entry, Status status) {
- entry.setStatus(status);
- setHasNonReadOnlyEnties(status);
+ entry.setStatus( status );
+ setHasNonReadOnlyEnties( status );
}
private void setHasNonReadOnlyEnties(Status status) {
@@ -303,25 +301,25 @@ public class StatefulPersistenceContext implements PersistenceContext {
/**
* Get the current state of the entity as known to the underlying
* database, or null if there is no corresponding row
+ *
+ * {@inheritDoc}
*/
@Override
- public Object[] getDatabaseSnapshot(Serializable id, EntityPersister persister)
- throws HibernateException {
+ public Object[] getDatabaseSnapshot(Serializable id, EntityPersister persister) throws HibernateException {
final EntityKey key = session.generateEntityKey( id, persister );
- Object cached = entitySnapshotsByKey.get(key);
- if (cached!=null) {
- return cached==NO_ROW ? null : (Object[]) cached;
+ final Object cached = entitySnapshotsByKey.get( key );
+ if ( cached != null ) {
+ return cached == NO_ROW ? null : (Object[]) cached;
}
else {
- Object[] snapshot = persister.getDatabaseSnapshot( id, session );
- entitySnapshotsByKey.put( key, snapshot==null ? NO_ROW : snapshot );
+ final Object[] snapshot = persister.getDatabaseSnapshot( id, session );
+ entitySnapshotsByKey.put( key, snapshot == null ? NO_ROW : snapshot );
return snapshot;
}
}
@Override
- public Object[] getNaturalIdSnapshot(Serializable id, EntityPersister persister)
- throws HibernateException {
+ public Object[] getNaturalIdSnapshot(Serializable id, EntityPersister persister) throws HibernateException {
if ( !persister.hasNaturalIdentifier() ) {
return null;
}
@@ -371,39 +369,27 @@ public class StatefulPersistenceContext implements PersistenceContext {
return session.getFactory().getEntityPersister( persister.getRootEntityName() );
}
- /**
- * Retrieve the cached database snapshot for the requested entity key.
- *
- * This differs from {@link #getDatabaseSnapshot} is two important respects:
- * - no snapshot is obtained from the database if not already cached
- * - an entry of {@link #NO_ROW} here is interpretet as an exception
- *
- * @param key The entity key for which to retrieve the cached snapshot
- * @return The cached snapshot
- * @throws IllegalStateException if the cached snapshot was == {@link #NO_ROW}.
- */
@Override
public Object[] getCachedDatabaseSnapshot(EntityKey key) {
- Object snapshot = entitySnapshotsByKey.get( key );
+ final Object snapshot = entitySnapshotsByKey.get( key );
if ( snapshot == NO_ROW ) {
- throw new IllegalStateException( "persistence context reported no row snapshot for " + MessageHelper.infoString( key.getEntityName(), key.getIdentifier() ) );
+ throw new IllegalStateException(
+ "persistence context reported no row snapshot for "
+ + MessageHelper.infoString( key.getEntityName(), key.getIdentifier() )
+ );
}
- return ( Object[] ) snapshot;
+ return (Object[]) snapshot;
}
@Override
public void addEntity(EntityKey key, Object entity) {
- entitiesByKey.put(key, entity);
- getBatchFetchQueue().removeBatchLoadableEntityKey(key);
+ entitiesByKey.put( key, entity );
+ getBatchFetchQueue().removeBatchLoadableEntityKey( key );
}
- /**
- * Get the entity instance associated with the given
- * EntityKey
- */
@Override
public Object getEntity(EntityKey key) {
- return entitiesByKey.get(key);
+ return entitiesByKey.get( key );
}
@Override
@@ -411,84 +397,54 @@ public class StatefulPersistenceContext implements PersistenceContext {
return entitiesByKey.containsKey(key);
}
- /**
- * Remove an entity from the session cache, also clear
- * up other state associated with the entity, all except
- * for the EntityEntry
- */
@Override
public Object removeEntity(EntityKey key) {
- Object entity = entitiesByKey.remove(key);
- Iterator iter = entitiesByUniqueKey.values().iterator();
- while ( iter.hasNext() ) {
- if ( iter.next()==entity ) iter.remove();
+ final Object entity = entitiesByKey.remove( key );
+ final Iterator itr = entitiesByUniqueKey.values().iterator();
+ while ( itr.hasNext() ) {
+ if ( itr.next() == entity ) {
+ itr.remove();
+ }
}
// Clear all parent cache
parentsByChild.clear();
- entitySnapshotsByKey.remove(key);
- nullifiableEntityKeys.remove(key);
- getBatchFetchQueue().removeBatchLoadableEntityKey(key);
- getBatchFetchQueue().removeSubselect(key);
+ entitySnapshotsByKey.remove( key );
+ nullifiableEntityKeys.remove( key );
+ getBatchFetchQueue().removeBatchLoadableEntityKey( key );
+ getBatchFetchQueue().removeSubselect( key );
return entity;
}
- /**
- * Get an entity cached by unique key
- */
@Override
public Object getEntity(EntityUniqueKey euk) {
- return entitiesByUniqueKey.get(euk);
+ return entitiesByUniqueKey.get( euk );
}
- /**
- * Add an entity to the cache by unique key
- */
@Override
public void addEntity(EntityUniqueKey euk, Object entity) {
- entitiesByUniqueKey.put(euk, entity);
+ entitiesByUniqueKey.put( euk, entity );
}
- /**
- * Retrieve the EntityEntry representation of the given entity.
- *
- * @param entity The entity for which to locate the EntityEntry.
- * @return The EntityEntry for the given entity.
- */
@Override
public EntityEntry getEntry(Object entity) {
return entityEntryContext.getEntityEntry( entity );
-// return entityEntries.get(entity);
}
- /**
- * Remove an entity entry from the session cache
- */
@Override
public EntityEntry removeEntry(Object entity) {
return entityEntryContext.removeEntityEntry( entity );
-// return entityEntries.remove(entity);
}
- /**
- * Is there an EntityEntry for this instance?
- */
@Override
public boolean isEntryFor(Object entity) {
return entityEntryContext.hasEntityEntry( entity );
-// return entityEntries.containsKey(entity);
}
- /**
- * Get the collection entry for a persistent collection
- */
@Override
public CollectionEntry getCollectionEntry(PersistentCollection coll) {
- return collectionEntries.get(coll);
+ return collectionEntries.get( coll );
}
- /**
- * Adds an entity to the internal caches.
- */
@Override
public EntityEntry addEntity(
final Object entity,
@@ -517,11 +473,6 @@ public class StatefulPersistenceContext implements PersistenceContext {
);
}
-
- /**
- * Generates an appropriate EntityEntry instance and adds it
- * to the event source's internal caches.
- */
@Override
public EntityEntry addEntry(
final Object entity,
@@ -536,7 +487,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
final boolean disableVersionIncrement,
boolean lazyPropertiesAreUnfetched) {
- EntityEntry e = new EntityEntry(
+ final EntityEntry e = new EntityEntry(
status,
loadedState,
rowId,
@@ -555,13 +506,13 @@ public class StatefulPersistenceContext implements PersistenceContext {
entityEntryContext.addEntityEntry( entity, e );
// entityEntries.put(entity, e);
- setHasNonReadOnlyEnties(status);
+ setHasNonReadOnlyEnties( status );
return e;
}
@Override
public boolean containsCollection(PersistentCollection collection) {
- return collectionEntries.containsKey(collection);
+ return collectionEntries.containsKey( collection );
}
@Override
@@ -569,23 +520,16 @@ public class StatefulPersistenceContext implements PersistenceContext {
return proxiesByKey.containsValue( entity );
}
- /**
- * Takes the given object and, if it represents a proxy, reassociates it with this event source.
- *
- * @param value The possible proxy to be reassociated.
- * @return Whether the passed value represented an actual proxy which got initialized.
- * @throws MappingException
- */
@Override
public boolean reassociateIfUninitializedProxy(Object value) throws MappingException {
if ( value instanceof ElementWrapper ) {
value = ( (ElementWrapper) value ).getElement();
}
- if ( !Hibernate.isInitialized(value) ) {
- HibernateProxy proxy = (HibernateProxy) value;
- LazyInitializer li = proxy.getHibernateLazyInitializer();
- reassociateProxy(li, proxy);
+ if ( !Hibernate.isInitialized( value ) ) {
+ final HibernateProxy proxy = (HibernateProxy) value;
+ final LazyInitializer li = proxy.getHibernateLazyInitializer();
+ reassociateProxy( li, proxy );
return true;
}
else {
@@ -593,10 +537,6 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
}
- /**
- * If a deleted entity instance is re-saved, and it has a proxy, we need to
- * reset the identifier of the proxy
- */
@Override
public void reassociateProxy(Object value, Serializable id) throws MappingException {
if ( value instanceof ElementWrapper ) {
@@ -605,10 +545,10 @@ public class StatefulPersistenceContext implements PersistenceContext {
if ( value instanceof HibernateProxy ) {
LOG.debugf( "Setting proxy identifier: %s", id );
- HibernateProxy proxy = (HibernateProxy) value;
- LazyInitializer li = proxy.getHibernateLazyInitializer();
- li.setIdentifier(id);
- reassociateProxy(li, proxy);
+ final HibernateProxy proxy = (HibernateProxy) value;
+ final LazyInitializer li = proxy.getHibernateLazyInitializer();
+ li.setIdentifier( id );
+ reassociateProxy( li, proxy );
}
}
@@ -630,11 +570,6 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
}
- /**
- * Get the entity instance underlying the given proxy, throwing
- * an exception if the proxy is uninitialized. If the given object
- * is not a proxy, simply return the argument.
- */
@Override
public Object unproxy(Object maybeProxy) throws HibernateException {
if ( maybeProxy instanceof ElementWrapper ) {
@@ -642,28 +577,21 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
if ( maybeProxy instanceof HibernateProxy ) {
- HibernateProxy proxy = (HibernateProxy) maybeProxy;
- LazyInitializer li = proxy.getHibernateLazyInitializer();
+ final HibernateProxy proxy = (HibernateProxy) maybeProxy;
+ final LazyInitializer li = proxy.getHibernateLazyInitializer();
if ( li.isUninitialized() ) {
throw new PersistentObjectException(
- "object was an uninitialized proxy for " +
- li.getEntityName()
+ "object was an uninitialized proxy for " + li.getEntityName()
);
}
- return li.getImplementation(); //unwrap the object
+ //unwrap the object and return
+ return li.getImplementation();
}
else {
return maybeProxy;
}
}
- /**
- * Possibly unproxy the given reference and reassociate it with the current session.
- *
- * @param maybeProxy The reference to be unproxied if it currently represents a proxy.
- * @return The unproxied instance.
- * @throws HibernateException
- */
@Override
public Object unproxyAndReassociate(Object maybeProxy) throws HibernateException {
if ( maybeProxy instanceof ElementWrapper ) {
@@ -671,25 +599,20 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
if ( maybeProxy instanceof HibernateProxy ) {
- HibernateProxy proxy = (HibernateProxy) maybeProxy;
- LazyInitializer li = proxy.getHibernateLazyInitializer();
- reassociateProxy(li, proxy);
- return li.getImplementation(); //initialize + unwrap the object
+ final HibernateProxy proxy = (HibernateProxy) maybeProxy;
+ final LazyInitializer li = proxy.getHibernateLazyInitializer();
+ reassociateProxy( li, proxy );
+ //initialize + unwrap the object and return it
+ return li.getImplementation();
}
else {
return maybeProxy;
}
}
- /**
- * Attempts to check whether the given key represents an entity already loaded within the
- * current session.
- * @param object The entity reference against which to perform the uniqueness check.
- * @throws HibernateException
- */
@Override
public void checkUniqueness(EntityKey key, Object object) throws HibernateException {
- Object entity = getEntity(key);
+ final Object entity = getEntity( key );
if ( entity == object ) {
throw new AssertionFailure( "object already associated, but no entry was found" );
}
@@ -698,36 +621,26 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
}
- /**
- * If the existing proxy is insufficiently "narrow" (derived), instantiate a new proxy
- * and overwrite the registration of the old one. This breaks == and occurs only for
- * "class" proxies rather than "interface" proxies. Also init the proxy to point to
- * the given target implementation if necessary.
- *
- * @param proxy The proxy instance to be narrowed.
- * @param persister The persister for the proxied entity.
- * @param key The internal cache key for the proxied entity.
- * @param object (optional) the actual proxied entity instance.
- * @return An appropriately narrowed instance.
- * @throws HibernateException
- */
@Override
+ @SuppressWarnings("unchecked")
public Object narrowProxy(Object proxy, EntityPersister persister, EntityKey key, Object object)
throws HibernateException {
final Class concreteProxyClass = persister.getConcreteProxyClass();
- boolean alreadyNarrow = concreteProxyClass.isAssignableFrom( proxy.getClass() );
+ final boolean alreadyNarrow = concreteProxyClass.isAssignableFrom( proxy.getClass() );
if ( !alreadyNarrow ) {
LOG.narrowingProxy( concreteProxyClass );
if ( object != null ) {
- proxiesByKey.remove(key);
- return object; //return the proxied object
+ proxiesByKey.remove( key );
+ //return the proxied object
+ return object;
}
else {
proxy = persister.createProxy( key.getIdentifier(), session );
- Object proxyOrig = proxiesByKey.put(key, proxy); //overwrite old proxy
+ //overwrite old proxy
+ final Object proxyOrig = proxiesByKey.put( key, proxy );
if ( proxyOrig != null ) {
if ( ! ( proxyOrig instanceof HibernateProxy ) ) {
throw new AssertionFailure(
@@ -735,8 +648,8 @@ public class StatefulPersistenceContext implements PersistenceContext {
);
}
// set the read-only/modifiable mode in the new proxy to what it was in the original proxy
- boolean readOnlyOrig = ( ( HibernateProxy ) proxyOrig ).getHibernateLazyInitializer().isReadOnly();
- ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().setReadOnly( readOnlyOrig );
+ final boolean readOnlyOrig = ( (HibernateProxy) proxyOrig ).getHibernateLazyInitializer().isReadOnly();
+ ( (HibernateProxy) proxy ).getHibernateLazyInitializer().setReadOnly( readOnlyOrig );
}
return proxy;
}
@@ -744,45 +657,28 @@ public class StatefulPersistenceContext implements PersistenceContext {
else {
if ( object != null ) {
- LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer();
- li.setImplementation(object);
+ final LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer();
+ li.setImplementation( object );
}
-
return proxy;
-
}
-
}
- /**
- * Return the existing proxy associated with the given EntityKey, or the
- * third argument (the entity associated with the key) if no proxy exists. Init
- * the proxy to the target implementation, if necessary.
- */
@Override
- public Object proxyFor(EntityPersister persister, EntityKey key, Object impl)
- throws HibernateException {
+ public Object proxyFor(EntityPersister persister, EntityKey key, Object impl) throws HibernateException {
if ( !persister.hasProxy() ) {
return impl;
}
- Object proxy = proxiesByKey.get( key );
+ final Object proxy = proxiesByKey.get( key );
return ( proxy != null ) ? narrowProxy( proxy, persister, key, impl ) : impl;
}
- /**
- * Return the existing proxy associated with the given EntityKey, or the
- * argument (the entity associated with the key) if no proxy exists.
- * (slower than the form above)
- */
@Override
public Object proxyFor(Object impl) throws HibernateException {
- EntityEntry e = getEntry(impl);
+ final EntityEntry e = getEntry( impl );
return proxyFor( e.getPersister(), e.getEntityKey(), impl );
}
- /**
- * Get the entity that owns this persistent collection
- */
@Override
public Object getCollectionOwner(Serializable key, CollectionPersister collectionPersister) throws MappingException {
// todo : we really just need to add a split in the notions of:
@@ -811,7 +707,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
// find the corresponding owner instance
// a) try by EntityUniqueKey
if ( collectionType.getLHSPropertyName() != null ) {
- Object owner = getEntity(
+ final Object owner = getEntity(
new EntityUniqueKey(
ownerPersister.getEntityName(),
collectionType.getLHSPropertyName(),
@@ -846,35 +742,23 @@ public class StatefulPersistenceContext implements PersistenceContext {
return getEntity( session.generateEntityKey( key, collectionPersister.getOwnerEntityPersister() ) );
}
- /**
- * Get the entity that owned this persistent collection when it was loaded
- *
- * @param collection The persistent collection
- * @return the owner, if its entity ID is available from the collection's loaded key
- * and the owner entity is in the persistence context; otherwise, returns null
- */
@Override
public Object getLoadedCollectionOwnerOrNull(PersistentCollection collection) {
- CollectionEntry ce = getCollectionEntry( collection );
+ final CollectionEntry ce = getCollectionEntry( collection );
if ( ce.getLoadedPersister() == null ) {
- return null; // early exit...
+ return null;
}
+
Object loadedOwner = null;
// TODO: an alternative is to check if the owner has changed; if it hasn't then
// return collection.getOwner()
- Serializable entityId = getLoadedCollectionOwnerIdOrNull( ce );
+ final Serializable entityId = getLoadedCollectionOwnerIdOrNull( ce );
if ( entityId != null ) {
loadedOwner = getCollectionOwner( entityId, ce.getLoadedPersister() );
}
return loadedOwner;
}
- /**
- * Get the ID for the entity that owned this persistent collection when it was loaded
- *
- * @param collection The persistent collection
- * @return the owner ID if available from the collection's loaded key; otherwise, returns null
- */
@Override
public Serializable getLoadedCollectionOwnerIdOrNull(PersistentCollection collection) {
return getLoadedCollectionOwnerIdOrNull( getCollectionEntry( collection ) );
@@ -895,39 +779,28 @@ public class StatefulPersistenceContext implements PersistenceContext {
return ce.getLoadedPersister().getCollectionType().getIdOfOwnerOrNull( ce.getLoadedKey(), session );
}
- /**
- * add a collection we just loaded up (still needs initializing)
- */
@Override
public void addUninitializedCollection(CollectionPersister persister, PersistentCollection collection, Serializable id) {
- CollectionEntry ce = new CollectionEntry(collection, persister, id, flushing);
- addCollection(collection, ce, id);
+ final CollectionEntry ce = new CollectionEntry( collection, persister, id, flushing );
+ addCollection( collection, ce, id );
if ( persister.getBatchSize() > 1 ) {
getBatchFetchQueue().addBatchLoadableCollection( collection, ce );
}
}
- /**
- * add a detached uninitialized collection
- */
@Override
public void addUninitializedDetachedCollection(CollectionPersister persister, PersistentCollection collection) {
- CollectionEntry ce = new CollectionEntry( persister, collection.getKey() );
+ final CollectionEntry ce = new CollectionEntry( persister, collection.getKey() );
addCollection( collection, ce, collection.getKey() );
if ( persister.getBatchSize() > 1 ) {
getBatchFetchQueue().addBatchLoadableCollection( collection, ce );
}
}
- /**
- * Add a new collection (ie. a newly created one, just instantiated by the
- * application, with no database state or snapshot)
- * @param collection The collection to be associated with the persistence context
- */
@Override
public void addNewCollection(CollectionPersister persister, PersistentCollection collection)
- throws HibernateException {
- addCollection(collection, persister);
+ throws HibernateException {
+ addCollection( collection, persister );
}
/**
@@ -939,11 +812,11 @@ public class StatefulPersistenceContext implements PersistenceContext {
*/
private void addCollection(PersistentCollection coll, CollectionEntry entry, Serializable key) {
collectionEntries.put( coll, entry );
- CollectionKey collectionKey = new CollectionKey( entry.getLoadedPersister(), key );
- PersistentCollection old = collectionsByKey.put( collectionKey, coll );
+ final CollectionKey collectionKey = new CollectionKey( entry.getLoadedPersister(), key );
+ final PersistentCollection old = collectionsByKey.put( collectionKey, coll );
if ( old != null ) {
if ( old == coll ) {
- throw new AssertionFailure("bug adding collection twice");
+ throw new AssertionFailure( "bug adding collection twice" );
}
// or should it actually throw an exception?
old.unsetSession( session );
@@ -960,69 +833,52 @@ public class StatefulPersistenceContext implements PersistenceContext {
* @param persister The collection persister
*/
private void addCollection(PersistentCollection collection, CollectionPersister persister) {
- CollectionEntry ce = new CollectionEntry( persister, collection );
+ final CollectionEntry ce = new CollectionEntry( persister, collection );
collectionEntries.put( collection, ce );
}
- /**
- * add an (initialized) collection that was created by another session and passed
- * into update() (ie. one with a snapshot and existing state on the database)
- */
@Override
public void addInitializedDetachedCollection(CollectionPersister collectionPersister, PersistentCollection collection)
- throws HibernateException {
+ throws HibernateException {
if ( collection.isUnreferenced() ) {
//treat it just like a new collection
addCollection( collection, collectionPersister );
}
else {
- CollectionEntry ce = new CollectionEntry( collection, session.getFactory() );
+ final CollectionEntry ce = new CollectionEntry( collection, session.getFactory() );
addCollection( collection, ce, collection.getKey() );
}
}
- /**
- * add a collection we just pulled out of the cache (does not need initializing)
- */
@Override
public CollectionEntry addInitializedCollection(CollectionPersister persister, PersistentCollection collection, Serializable id)
- throws HibernateException {
- CollectionEntry ce = new CollectionEntry(collection, persister, id, flushing);
- ce.postInitialize(collection);
- addCollection(collection, ce, id);
+ throws HibernateException {
+ final CollectionEntry ce = new CollectionEntry( collection, persister, id, flushing );
+ ce.postInitialize( collection );
+ addCollection( collection, ce, id );
return ce;
}
- /**
- * Get the collection instance associated with the CollectionKey
- */
@Override
public PersistentCollection getCollection(CollectionKey collectionKey) {
return collectionsByKey.get( collectionKey );
}
- /**
- * Register a collection for non-lazy loading at the end of the
- * two-phase load
- */
@Override
public void addNonLazyCollection(PersistentCollection collection) {
- nonlazyCollections.add(collection);
+ nonlazyCollections.add( collection );
}
- /**
- * Force initialization of all non-lazy collections encountered during
- * the current two-phase load (actually, this is a no-op, unless this
- * is the "outermost" load)
- */
@Override
public void initializeNonLazyCollections() throws HibernateException {
if ( loadCounter == 0 ) {
- if (tracing)
- LOG.trace( "Initializing non-lazy collections" );
+ if ( TRACE_ENABLED ) {
+ LOG.trace( "Initializing non-lazy collections" );
+ }
//do this work only at the very highest level of the load
- loadCounter++; //don't let this method be called recursively
+ //don't let this method be called recursively
+ loadCounter++;
try {
int size;
while ( ( size = nonlazyCollections.size() ) > 0 ) {
@@ -1037,20 +893,11 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
}
-
- /**
- * Get the PersistentCollection object for an array
- */
@Override
public PersistentCollection getCollectionHolder(Object array) {
- return arrayHolders.get(array);
+ return arrayHolders.get( array );
}
- /**
- * Register a PersistentCollection object for an array.
- * Associates a holder with an array - MUST be called after loading
- * array, since the array instance is not created until endLoad().
- */
@Override
public void addCollectionHolder(PersistentCollection holder) {
//TODO:refactor + make this method private
@@ -1059,22 +906,14 @@ public class StatefulPersistenceContext implements PersistenceContext {
@Override
public PersistentCollection removeCollectionHolder(Object array) {
- return arrayHolders.remove(array);
+ return arrayHolders.remove( array );
}
- /**
- * Get the snapshot of the pre-flush collection state
- */
@Override
public Serializable getSnapshot(PersistentCollection coll) {
- return getCollectionEntry(coll).getSnapshot();
+ return getCollectionEntry( coll ).getSnapshot();
}
- /**
- * Get the collection entry for a collection passed to filter,
- * which might be a collection wrapper, an array, or an unwrapped
- * collection. Return null if there is no entry.
- */
@Override
public CollectionEntry getCollectionEntryOrNull(Object collection) {
PersistentCollection coll;
@@ -1083,14 +922,14 @@ public class StatefulPersistenceContext implements PersistenceContext {
//if (collection==null) throw new TransientObjectException("Collection was not yet persistent");
}
else {
- coll = getCollectionHolder(collection);
+ coll = getCollectionHolder( collection );
if ( coll == null ) {
//it might be an unwrapped collection reference!
//try to find a wrapper (slowish)
- Iterator wrappers = collectionEntries.keyIterator();
+ final Iterator wrappers = collectionEntries.keyIterator();
while ( wrappers.hasNext() ) {
- PersistentCollection pc = wrappers.next();
- if ( pc.isWrapper(collection) ) {
+ final PersistentCollection pc = wrappers.next();
+ if ( pc.isWrapper( collection ) ) {
coll = pc;
break;
}
@@ -1098,34 +937,19 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
}
- return (coll == null) ? null : getCollectionEntry(coll);
+ return (coll == null) ? null : getCollectionEntry( coll );
}
- /**
- * Get an existing proxy by key
- */
@Override
public Object getProxy(EntityKey key) {
- return proxiesByKey.get(key);
+ return proxiesByKey.get( key );
}
- /**
- * Add a proxy to the session cache
- */
@Override
public void addProxy(EntityKey key, Object proxy) {
- proxiesByKey.put(key, proxy);
+ proxiesByKey.put( key, proxy );
}
- /**
- * Remove a proxy from the session cache.
- *
- * Additionally, ensure that any load optimization references
- * such as batch or subselect loading get cleaned up as well.
- *
- * @param key The key of the entity proxy to be removed
- * @return The proxy reference.
- */
@Override
public Object removeProxy(EntityKey key) {
if ( batchFetchQueue != null ) {
@@ -1135,9 +959,6 @@ public class StatefulPersistenceContext implements PersistenceContext {
return proxiesByKey.remove( key );
}
- /**
- * Retrieve the set of EntityKeys representing nullifiable references
- */
@Override
public HashSet getNullifiableEntityKeys() {
return nullifiableEntityKeys;
@@ -1222,20 +1043,10 @@ public class StatefulPersistenceContext implements PersistenceContext {
return loadCounter == 0;
}
- /**
- * Returns a string representation of the object.
- *
- * @return a string representation of the object.
- */
@Override
- public String toString() {
- return new StringBuilder()
- .append("PersistenceContext[entityKeys=")
- .append(entitiesByKey.keySet())
- .append(",collectionKeys=")
- .append(collectionsByKey.keySet())
- .append("]")
- .toString();
+ public String toString() {
+ return "PersistenceContext[entityKeys=" + entitiesByKey.keySet()
+ + ",collectionKeys=" + collectionsByKey.keySet() + "]";
}
@Override
@@ -1243,27 +1054,6 @@ public class StatefulPersistenceContext implements PersistenceContext {
return entityEntryContext.reentrantSafeEntityEntries();
}
- /**
- * Search this persistence context for an associated entity instance which is considered the "owner" of
- * the given childEntity, and return that owner's id value. This is performed in the scenario of a
- * uni-directional, non-inverse one-to-many collection (which means that the collection elements do not maintain
- * a direct reference to the owner).
- *
- * As such, the processing here is basically to loop over every entity currently associated with this persistence
- * context and for those of the correct entity (sub) type to extract its collection role property value and see
- * if the child is contained within that collection. If so, we have found the owner; if not, we go on.
- *
- * Also need to account for mergeMap which acts as a local copy cache managed for the duration of a merge
- * operation. It represents a map of the detached entity instances pointing to the corresponding managed instance.
- *
- * @param entityName The entity name for the entity type which would own the child
- * @param propertyName The name of the property on the owning entity type which would name this child association.
- * @param childEntity The child entity instance for which to locate the owner instance id.
- * @param mergeMap A map of non-persistent instances from an on-going merge operation (possibly null).
- *
- * @return The id of the entityName instance which is said to own the child; null if an appropriate owner not
- * located.
- */
@Override
public Serializable getOwnerId(String entityName, String propertyName, Object childEntity, Map mergeMap) {
final String collectionRole = entityName + '.' + propertyName;
@@ -1271,24 +1061,23 @@ public class StatefulPersistenceContext implements PersistenceContext {
final CollectionPersister collectionPersister = session.getFactory().getCollectionPersister( collectionRole );
// try cache lookup first
- Object parent = parentsByChild.get( childEntity );
+ final Object parent = parentsByChild.get( childEntity );
if ( parent != null ) {
final EntityEntry entityEntry = entityEntryContext.getEntityEntry( parent );
-// final EntityEntry entityEntry = entityEntries.get( parent );
//there maybe more than one parent, filter by type
- if ( persister.isSubclassEntityName(entityEntry.getEntityName() )
+ if ( persister.isSubclassEntityName( entityEntry.getEntityName() )
&& isFoundInParent( propertyName, childEntity, persister, collectionPersister, parent ) ) {
return getEntry( parent ).getId();
}
else {
- parentsByChild.remove( childEntity ); // remove wrong entry
+ // remove wrong entry
+ parentsByChild.remove( childEntity );
}
}
//not found in case, proceed
// iterate all the entities currently associated with the persistence context.
for ( Entry me : reentrantSafeEntityEntries() ) {
-// for ( Entry me : IdentityMap.concurrentEntries( entityEntries ) ) {
final EntityEntry entityEntry = me.getValue();
// does this entity entry pertain to the entity persister in which we are interested (owner)?
if ( persister.isSubclassEntityName( entityEntry.getEntityName() ) ) {
@@ -1305,8 +1094,8 @@ public class StatefulPersistenceContext implements PersistenceContext {
if ( !found && mergeMap != null ) {
//check if the detached object being merged is the parent
- Object unmergedInstance = mergeMap.get( entityEntryInstance );
- Object unmergedChild = mergeMap.get( childEntity );
+ final Object unmergedInstance = mergeMap.get( entityEntryInstance );
+ final Object unmergedChild = mergeMap.get( childEntity );
if ( unmergedInstance != null && unmergedChild != null ) {
found = isFoundInParent(
propertyName,
@@ -1367,66 +1156,60 @@ public class StatefulPersistenceContext implements PersistenceContext {
EntityPersister persister,
CollectionPersister collectionPersister,
Object potentialParent) {
- Object collection = persister.getPropertyValue( potentialParent, property );
+ final Object collection = persister.getPropertyValue( potentialParent, property );
return collection != null
&& Hibernate.isInitialized( collection )
&& collectionPersister.getCollectionType().contains( collection, childEntity, session );
}
- /**
- * Search the persistence context for an index of the child object,
- * given a collection role
- */
@Override
public Object getIndexInOwner(String entity, String property, Object childEntity, Map mergeMap) {
-
- EntityPersister persister = session.getFactory()
- .getEntityPersister(entity);
- CollectionPersister cp = session.getFactory()
- .getCollectionPersister(entity + '.' + property);
+ final EntityPersister persister = session.getFactory().getEntityPersister( entity );
+ final CollectionPersister cp = session.getFactory().getCollectionPersister( entity + '.' + property );
// try cache lookup first
- Object parent = parentsByChild.get(childEntity);
- if (parent != null) {
+ final Object parent = parentsByChild.get( childEntity );
+ if ( parent != null ) {
final EntityEntry entityEntry = entityEntryContext.getEntityEntry( parent );
-// final EntityEntry entityEntry = entityEntries.get(parent);
//there maybe more than one parent, filter by type
if ( persister.isSubclassEntityName( entityEntry.getEntityName() ) ) {
- Object index = getIndexInParent(property, childEntity, persister, cp, parent);
+ Object index = getIndexInParent( property, childEntity, persister, cp, parent );
if (index==null && mergeMap!=null) {
- Object unmergedInstance = mergeMap.get(parent);
- Object unmergedChild = mergeMap.get(childEntity);
- if ( unmergedInstance!=null && unmergedChild!=null ) {
- index = getIndexInParent(property, unmergedChild, persister, cp, unmergedInstance);
+ final Object unMergedInstance = mergeMap.get( parent );
+ final Object unMergedChild = mergeMap.get( childEntity );
+ if ( unMergedInstance != null && unMergedChild != null ) {
+ index = getIndexInParent( property, unMergedChild, persister, cp, unMergedInstance );
}
}
- if (index!=null) {
+ if ( index != null ) {
return index;
}
}
else {
- parentsByChild.remove(childEntity); // remove wrong entry
+ // remove wrong entry
+ parentsByChild.remove( childEntity );
}
}
//Not found in cache, proceed
for ( Entry me : reentrantSafeEntityEntries() ) {
- EntityEntry ee = me.getValue();
+ final EntityEntry ee = me.getValue();
if ( persister.isSubclassEntityName( ee.getEntityName() ) ) {
- Object instance = me.getKey();
+ final Object instance = me.getKey();
- Object index = getIndexInParent(property, childEntity, persister, cp, instance);
-
- if (index==null && mergeMap!=null) {
- Object unmergedInstance = mergeMap.get(instance);
- Object unmergedChild = mergeMap.get(childEntity);
- if ( unmergedInstance!=null && unmergedChild!=null ) {
- index = getIndexInParent(property, unmergedChild, persister, cp, unmergedInstance);
+ Object index = getIndexInParent( property, childEntity, persister, cp, instance );
+ if ( index==null && mergeMap!=null ) {
+ final Object unMergedInstance = mergeMap.get( instance );
+ final Object unMergedChild = mergeMap.get( childEntity );
+ if ( unMergedInstance != null && unMergedChild!=null ) {
+ index = getIndexInParent( property, unMergedChild, persister, cp, unMergedInstance );
}
}
- if (index!=null) return index;
+ if ( index != null ) {
+ return index;
+ }
}
}
return null;
@@ -1438,30 +1221,23 @@ public class StatefulPersistenceContext implements PersistenceContext {
EntityPersister persister,
CollectionPersister collectionPersister,
Object potentialParent){
- Object collection = persister.getPropertyValue( potentialParent, property );
- if ( collection!=null && Hibernate.isInitialized(collection) ) {
- return collectionPersister.getCollectionType().indexOf(collection, childEntity);
+ final Object collection = persister.getPropertyValue( potentialParent, property );
+ if ( collection != null && Hibernate.isInitialized( collection ) ) {
+ return collectionPersister.getCollectionType().indexOf( collection, childEntity );
}
else {
return null;
}
}
- /**
- * Record the fact that the association belonging to the keyed
- * entity is null.
- */
@Override
public void addNullProperty(EntityKey ownerKey, String propertyName) {
- nullAssociations.add( new AssociationKey(ownerKey, propertyName) );
+ nullAssociations.add( new AssociationKey( ownerKey, propertyName ) );
}
- /**
- * Is the association property belonging to the keyed entity null?
- */
@Override
public boolean isPropertyNull(EntityKey ownerKey, String propertyName) {
- return nullAssociations.contains( new AssociationKey(ownerKey, propertyName) );
+ return nullAssociations.contains( new AssociationKey( ownerKey, propertyName ) );
}
private void clearNullProperties() {
@@ -1475,10 +1251,10 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
boolean isReadOnly;
if ( entityOrProxy instanceof HibernateProxy ) {
- isReadOnly = ( ( HibernateProxy ) entityOrProxy ).getHibernateLazyInitializer().isReadOnly();
+ isReadOnly = ( (HibernateProxy) entityOrProxy ).getHibernateLazyInitializer().isReadOnly();
}
else {
- EntityEntry ee = getEntry( entityOrProxy );
+ final EntityEntry ee = getEntry( entityOrProxy );
if ( ee == null ) {
throw new TransientObjectException("Instance was not associated with this persistence context" );
}
@@ -1496,7 +1272,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
return;
}
if ( object instanceof HibernateProxy ) {
- HibernateProxy proxy = ( HibernateProxy ) object;
+ final HibernateProxy proxy = (HibernateProxy) object;
setProxyReadOnly( proxy, readOnly );
if ( Hibernate.isInitialized( proxy ) ) {
setEntityReadOnly(
@@ -1509,9 +1285,9 @@ public class StatefulPersistenceContext implements PersistenceContext {
setEntityReadOnly( object, readOnly );
// PersistenceContext.proxyFor( entity ) returns entity if there is no proxy for that entity
// so need to check the return value to be sure it is really a proxy
- Object maybeProxy = getSession().getPersistenceContext().proxyFor( object );
+ final Object maybeProxy = getSession().getPersistenceContext().proxyFor( object );
if ( maybeProxy instanceof HibernateProxy ) {
- setProxyReadOnly( ( HibernateProxy ) maybeProxy, readOnly );
+ setProxyReadOnly( (HibernateProxy) maybeProxy, readOnly );
}
}
}
@@ -1525,11 +1301,11 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
private void setEntityReadOnly(Object entity, boolean readOnly) {
- EntityEntry entry = getEntry(entity);
- if (entry == null) {
- throw new TransientObjectException("Instance was not associated with this persistence context" );
+ final EntityEntry entry = getEntry( entity );
+ if ( entry == null ) {
+ throw new TransientObjectException( "Instance was not associated with this persistence context" );
}
- entry.setReadOnly(readOnly, entity );
+ entry.setReadOnly( readOnly, entity );
hasNonReadOnlyEntities = hasNonReadOnlyEntities || ! readOnly;
}
@@ -1543,16 +1319,16 @@ public class StatefulPersistenceContext implements PersistenceContext {
addEntity( newKey, entity );
addEntry(
entity,
- oldEntry.getStatus(),
- oldEntry.getLoadedState(),
- oldEntry.getRowId(),
- generatedId,
- oldEntry.getVersion(),
- oldEntry.getLockMode(),
- oldEntry.isExistsInDatabase(),
- oldEntry.getPersister(),
- oldEntry.isBeingReplicated(),
- oldEntry.isLoadedWithLazyPropertiesUnfetched()
+ oldEntry.getStatus(),
+ oldEntry.getLoadedState(),
+ oldEntry.getRowId(),
+ generatedId,
+ oldEntry.getVersion(),
+ oldEntry.getLockMode(),
+ oldEntry.isExistsInDatabase(),
+ oldEntry.getPersister(),
+ oldEntry.isBeingReplicated(),
+ oldEntry.isLoadedWithLazyPropertiesUnfetched()
);
}
@@ -1565,97 +1341,106 @@ public class StatefulPersistenceContext implements PersistenceContext {
*/
public void serialize(ObjectOutputStream oos) throws IOException {
final boolean tracing = LOG.isTraceEnabled();
- if ( tracing ) LOG.trace( "Serializing persistent-context" );
+ if ( tracing ) {
+ LOG.trace( "Serializing persistence-context" );
+ }
oos.writeBoolean( defaultReadOnly );
oos.writeBoolean( hasNonReadOnlyEntities );
oos.writeInt( entitiesByKey.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + entitiesByKey.size() + "] entitiesByKey entries");
- Iterator itr = entitiesByKey.entrySet().iterator();
- while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
- ( ( EntityKey ) entry.getKey() ).serialize( oos );
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + entitiesByKey.size() + "] entitiesByKey entries" );
+ }
+ for ( Map.Entry entry : entitiesByKey.entrySet() ) {
+ entry.getKey().serialize( oos );
oos.writeObject( entry.getValue() );
}
oos.writeInt( entitiesByUniqueKey.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + entitiesByUniqueKey.size() + "] entitiesByUniqueKey entries");
- itr = entitiesByUniqueKey.entrySet().iterator();
- while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
- ( ( EntityUniqueKey ) entry.getKey() ).serialize( oos );
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + entitiesByUniqueKey.size() + "] entitiesByUniqueKey entries" );
+ }
+ for ( Map.Entry entry : entitiesByUniqueKey.entrySet() ) {
+ entry.getKey().serialize( oos );
oos.writeObject( entry.getValue() );
}
oos.writeInt( proxiesByKey.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + proxiesByKey.size() + "] proxiesByKey entries");
- itr = proxiesByKey.entrySet().iterator();
- while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
- ( (EntityKey) entry.getKey() ).serialize( oos );
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + proxiesByKey.size() + "] proxiesByKey entries" );
+ }
+ for ( Map.Entry entry : proxiesByKey.entrySet() ) {
+ entry.getKey().serialize( oos );
oos.writeObject( entry.getValue() );
}
oos.writeInt( entitySnapshotsByKey.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + entitySnapshotsByKey.size() + "] entitySnapshotsByKey entries");
- itr = entitySnapshotsByKey.entrySet().iterator();
- while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
- ( ( EntityKey ) entry.getKey() ).serialize( oos );
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + entitySnapshotsByKey.size() + "] entitySnapshotsByKey entries" );
+ }
+ for ( Map.Entry entry : entitySnapshotsByKey.entrySet() ) {
+ entry.getKey().serialize( oos );
oos.writeObject( entry.getValue() );
}
entityEntryContext.serialize( oos );
-// oos.writeInt( entityEntries.size() );
-// if ( tracing ) LOG.trace("Starting serialization of [" + entityEntries.size() + "] entityEntries entries");
-// itr = entityEntries.entrySet().iterator();
-// while ( itr.hasNext() ) {
-// Map.Entry entry = ( Map.Entry ) itr.next();
-// oos.writeObject( entry.getKey() );
-// ( ( EntityEntry ) entry.getValue() ).serialize( oos );
-// }
oos.writeInt( collectionsByKey.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + collectionsByKey.size() + "] collectionsByKey entries");
- itr = collectionsByKey.entrySet().iterator();
- while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
- ( ( CollectionKey ) entry.getKey() ).serialize( oos );
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + collectionsByKey.size() + "] collectionsByKey entries" );
+ }
+ for ( Map.Entry entry : collectionsByKey.entrySet() ) {
+ entry.getKey().serialize( oos );
oos.writeObject( entry.getValue() );
}
oos.writeInt( collectionEntries.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + collectionEntries.size() + "] collectionEntries entries");
- itr = collectionEntries.entrySet().iterator();
- while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + collectionEntries.size() + "] collectionEntries entries" );
+ }
+ for ( Map.Entry entry : collectionEntries.entrySet() ) {
oos.writeObject( entry.getKey() );
- ( ( CollectionEntry ) entry.getValue() ).serialize( oos );
+ entry.getValue().serialize( oos );
}
oos.writeInt( arrayHolders.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + arrayHolders.size() + "] arrayHolders entries");
- itr = arrayHolders.entrySet().iterator();
- while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + arrayHolders.size() + "] arrayHolders entries" );
+ }
+ for ( Map.Entry entry : arrayHolders.entrySet() ) {
oos.writeObject( entry.getKey() );
oos.writeObject( entry.getValue() );
}
oos.writeInt( nullifiableEntityKeys.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + nullifiableEntityKeys.size() + "] nullifiableEntityKey entries");
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + nullifiableEntityKeys.size() + "] nullifiableEntityKey entries" );
+ }
for ( EntityKey entry : nullifiableEntityKeys ) {
entry.serialize( oos );
}
}
+ /**
+ * Used by the owning session to explicitly control deserialization of the persistence context.
+ *
+ * @param ois The stream from which the persistence context should be read
+ * @param session The owning session
+ *
+ * @return The deserialized StatefulPersistenceContext
+ *
+ * @throws IOException deserialization errors.
+ * @throws ClassNotFoundException deserialization errors.
+ */
public static StatefulPersistenceContext deserialize(
ObjectInputStream ois,
SessionImplementor session) throws IOException, ClassNotFoundException {
final boolean tracing = LOG.isTraceEnabled();
- if ( tracing ) LOG.trace("Serializing persistent-context");
- StatefulPersistenceContext rtn = new StatefulPersistenceContext( session );
+ if ( tracing ) {
+ LOG.trace( "Serializing persistent-context" );
+ }
+ final StatefulPersistenceContext rtn = new StatefulPersistenceContext( session );
// during deserialization, we need to reconnect all proxies and
// collections to this session, as well as the EntityEntry and
@@ -1668,21 +1453,27 @@ public class StatefulPersistenceContext implements PersistenceContext {
rtn.hasNonReadOnlyEntities = ois.readBoolean();
int count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] entitiesByKey entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] entitiesByKey entries" );
+ }
rtn.entitiesByKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count );
for ( int i = 0; i < count; i++ ) {
rtn.entitiesByKey.put( EntityKey.deserialize( ois, session ), ois.readObject() );
}
count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] entitiesByUniqueKey entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] entitiesByUniqueKey entries" );
+ }
rtn.entitiesByUniqueKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count );
for ( int i = 0; i < count; i++ ) {
rtn.entitiesByUniqueKey.put( EntityUniqueKey.deserialize( ois, session ), ois.readObject() );
}
count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] proxiesByKey entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] proxiesByKey entries" );
+ }
//noinspection unchecked
rtn.proxiesByKey = new ConcurrentReferenceHashMap(
count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count,
@@ -1693,60 +1484,65 @@ public class StatefulPersistenceContext implements PersistenceContext {
null
);
for ( int i = 0; i < count; i++ ) {
- EntityKey ek = EntityKey.deserialize( ois, session );
- Object proxy = ois.readObject();
+ final EntityKey ek = EntityKey.deserialize( ois, session );
+ final Object proxy = ois.readObject();
if ( proxy instanceof HibernateProxy ) {
- ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().setSession( session );
+ ( (HibernateProxy) proxy ).getHibernateLazyInitializer().setSession( session );
rtn.proxiesByKey.put( ek, proxy );
- } else {
- if ( tracing ) LOG.trace("Encountered prunded proxy");
}
- // otherwise, the proxy was pruned during the serialization process
+ else {
+ // otherwise, the proxy was pruned during the serialization process
+ if ( tracing ) {
+ LOG.trace( "Encountered pruned proxy" );
+ }
+ }
}
count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] entitySnapshotsByKey entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] entitySnapshotsByKey entries" );
+ }
rtn.entitySnapshotsByKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count );
for ( int i = 0; i < count; i++ ) {
rtn.entitySnapshotsByKey.put( EntityKey.deserialize( ois, session ), ois.readObject() );
}
rtn.entityEntryContext = EntityEntryContext.deserialize( ois, rtn );
-// count = ois.readInt();
-// if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] entityEntries entries");
-// rtn.entityEntries = IdentityMap.instantiateSequenced( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count );
-// for ( int i = 0; i < count; i++ ) {
-// Object entity = ois.readObject();
-// EntityEntry entry = EntityEntry.deserialize( ois, rtn );
-// rtn.entityEntries.put( entity, entry );
-// }
count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] collectionsByKey entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] collectionsByKey entries" );
+ }
rtn.collectionsByKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count );
for ( int i = 0; i < count; i++ ) {
rtn.collectionsByKey.put( CollectionKey.deserialize( ois, session ), (PersistentCollection) ois.readObject() );
}
count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] collectionEntries entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] collectionEntries entries" );
+ }
rtn.collectionEntries = IdentityMap.instantiateSequenced( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count );
for ( int i = 0; i < count; i++ ) {
- final PersistentCollection pc = ( PersistentCollection ) ois.readObject();
+ final PersistentCollection pc = (PersistentCollection) ois.readObject();
final CollectionEntry ce = CollectionEntry.deserialize( ois, session );
pc.setCurrentSession( session );
rtn.collectionEntries.put( pc, ce );
}
count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] arrayHolders entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] arrayHolders entries" );
+ }
rtn.arrayHolders = new IdentityHashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count );
for ( int i = 0; i < count; i++ ) {
rtn.arrayHolders.put( ois.readObject(), (PersistentCollection) ois.readObject() );
}
count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] nullifiableEntityKey entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] nullifiableEntityKey entries" );
+ }
rtn.nullifiableEntityKeys = new HashSet();
for ( int i = 0; i < count; i++ ) {
rtn.nullifiableEntityKeys.add( EntityKey.deserialize( ois, session ) );
@@ -1762,12 +1558,12 @@ public class StatefulPersistenceContext implements PersistenceContext {
@Override
public void addChildParent(Object child, Object parent) {
- parentsByChild.put(child, parent);
+ parentsByChild.put( child, parent );
}
@Override
public void removeChildParent(Object child) {
- parentsByChild.remove(child);
+ parentsByChild.remove( child );
}
@@ -1797,7 +1593,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
// again, we only really care if the entity is cached
if ( persister.hasCache() ) {
if ( insertedKeysMap != null ) {
- List insertedEntityIds = insertedKeysMap.get( persister.getRootEntityName() );
+ final List insertedEntityIds = insertedKeysMap.get( persister.getRootEntityName() );
if ( insertedEntityIds != null ) {
return insertedEntityIds.contains( id );
}
@@ -1835,7 +1631,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
// from a single load event. The first put journal would come from the natural id resolution;
// the second comes from the entity loading. In this condition, we want to avoid the multiple
// 'put' stats incrementing.
- boolean justAddedLocally = naturalIdXrefDelegate.cacheNaturalIdCrossReference( persister, id, naturalIdValues );
+ final boolean justAddedLocally = naturalIdXrefDelegate.cacheNaturalIdCrossReference( persister, id, naturalIdValues );
if ( justAddedLocally && persister.hasNaturalIdCache() ) {
managedSharedCacheEntries( persister, id, naturalIdValues, null, CachedNaturalIdValueSource.LOAD );
@@ -1898,8 +1694,9 @@ public class StatefulPersistenceContext implements PersistenceContext {
switch ( source ) {
case LOAD: {
- if (naturalIdCacheAccessStrategy.get(naturalIdCacheKey, session.getTimestamp()) != null) {
- return; // prevent identical re-cachings
+ if ( naturalIdCacheAccessStrategy.get( naturalIdCacheKey, session.getTimestamp() ) != null ) {
+ // prevent identical re-cachings
+ return;
}
final boolean put = naturalIdCacheAccessStrategy.putFromLoad(
naturalIdCacheKey,
@@ -1937,7 +1734,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
}
else {
- naturalIdCacheAccessStrategy.remove(naturalIdCacheKey);
+ naturalIdCacheAccessStrategy.remove( naturalIdCacheKey );
}
}
}
@@ -1947,8 +1744,9 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
case UPDATE: {
final NaturalIdCacheKey previousCacheKey = new NaturalIdCacheKey( previousNaturalIdValues, persister, session );
- if (naturalIdCacheKey.equals(previousCacheKey)) {
- return; // prevent identical re-caching, solves HHH-7309
+ if ( naturalIdCacheKey.equals( previousCacheKey ) ) {
+ // prevent identical re-caching, solves HHH-7309
+ return;
}
final SoftLock removalLock = naturalIdCacheAccessStrategy.lockItem( previousCacheKey, null );
naturalIdCacheAccessStrategy.remove( previousCacheKey );
@@ -1982,6 +1780,9 @@ public class StatefulPersistenceContext implements PersistenceContext {
break;
}
+ default: {
+ LOG.debug( "Unexpected CachedNaturalIdValueSource [" + source + "]" );
+ }
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/TwoPhaseLoad.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/TwoPhaseLoad.java
index 2cdf7f9c88..e8d2c6ca38 100755
--- a/hibernate-core/src/main/java/org/hibernate/engine/internal/TwoPhaseLoad.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/TwoPhaseLoad.java
@@ -56,17 +56,19 @@ import org.hibernate.type.Type;
import org.hibernate.type.TypeHelper;
/**
- * Functionality relating to Hibernate's two-phase loading process,
- * that may be reused by persisters that do not use the Loader
- * framework
+ * Functionality relating to the Hibernate two-phase loading process, that may be reused by persisters
+ * that do not use the Loader framework
*
* @author Gavin King
*/
public final class TwoPhaseLoad {
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ TwoPhaseLoad.class.getName()
+ );
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, TwoPhaseLoad.class.getName() );
-
- private TwoPhaseLoad() {}
+ private TwoPhaseLoad() {
+ }
/**
* Register the "hydrated" state of an entity instance, after the first step of 2-phase loading.
@@ -74,19 +76,26 @@ public final class TwoPhaseLoad {
* Add the "hydrated state" (an array) of an uninitialized entity to the session. We don't try
* to resolve any associations yet, because there might be other entities waiting to be
* read from the JDBC result set we are currently processing
+ *
+ * @param persister The persister for the hydrated entity
+ * @param id The entity identifier
+ * @param values The entity values
+ * @param rowId The rowId for the entity
+ * @param object An optional instance for the entity being loaded
+ * @param lockMode The lock mode
+ * @param lazyPropertiesAreUnFetched Whether properties defined as lazy are yet un-fetched
+ * @param session The Session
*/
public static void postHydrate(
- final EntityPersister persister,
- final Serializable id,
- final Object[] values,
- final Object rowId,
- final Object object,
- final LockMode lockMode,
- final boolean lazyPropertiesAreUnfetched,
- final SessionImplementor session)
- throws HibernateException {
-
- Object version = Versioning.getVersion( values, persister );
+ final EntityPersister persister,
+ final Serializable id,
+ final Object[] values,
+ final Object rowId,
+ final Object object,
+ final LockMode lockMode,
+ final boolean lazyPropertiesAreUnFetched,
+ final SessionImplementor session) throws HibernateException {
+ final Object version = Versioning.getVersion( values, persister );
session.getPersistenceContext().addEntry(
object,
Status.LOADING,
@@ -98,47 +107,41 @@ public final class TwoPhaseLoad {
true,
persister,
false,
- lazyPropertiesAreUnfetched
+ lazyPropertiesAreUnFetched
);
if ( version != null && LOG.isTraceEnabled() ) {
- String versionStr = persister.isVersioned()
+ final String versionStr = persister.isVersioned()
? persister.getVersionType().toLoggableString( version, session.getFactory() )
: "null";
- LOG.tracev( "Version: {0}", versionStr );
+ LOG.tracef( "Version: %s", versionStr );
}
-
}
/**
* Perform the second step of 2-phase load. Fully initialize the entity
* instance.
- *
+ *
* After processing a JDBC result set, we "resolve" all the associations
* between the entities which were instantiated and had their state
* "hydrated" into an array
+ *
+ * @param entity The entity being loaded
+ * @param readOnly Is the entity being loaded as read-only
+ * @param session The Session
+ * @param preLoadEvent The (re-used) pre-load event
*/
public static void initializeEntity(
final Object entity,
final boolean readOnly,
final SessionImplementor session,
- final PreLoadEvent preLoadEvent,
- final PostLoadEvent postLoadEvent) throws HibernateException {
+ final PreLoadEvent preLoadEvent) {
final PersistenceContext persistenceContext = session.getPersistenceContext();
- final EntityEntry entityEntry = persistenceContext.getEntry(entity);
+ final EntityEntry entityEntry = persistenceContext.getEntry( entity );
if ( entityEntry == null ) {
throw new AssertionFailure( "possible non-threadsafe access to the session" );
}
- final EntityPersister persister = entityEntry.getPersister();
- final Serializable id = entityEntry.getId();
-
-// persistenceContext.getNaturalIdHelper().startingLoad( persister, id );
-// try {
- doInitializeEntity( entity, entityEntry, readOnly, session, preLoadEvent, postLoadEvent );
-// }
-// finally {
-// persistenceContext.getNaturalIdHelper().endingLoad( persister, id );
-// }
+ doInitializeEntity( entity, entityEntry, readOnly, session, preLoadEvent );
}
private static void doInitializeEntity(
@@ -146,12 +149,11 @@ public final class TwoPhaseLoad {
final EntityEntry entityEntry,
final boolean readOnly,
final SessionImplementor session,
- final PreLoadEvent preLoadEvent,
- final PostLoadEvent postLoadEvent) throws HibernateException {
+ final PreLoadEvent preLoadEvent) throws HibernateException {
final PersistenceContext persistenceContext = session.getPersistenceContext();
- EntityPersister persister = entityEntry.getPersister();
- Serializable id = entityEntry.getId();
- Object[] hydratedState = entityEntry.getLoadedState();
+ final EntityPersister persister = entityEntry.getPersister();
+ final Serializable id = entityEntry.getId();
+ final Object[] hydratedState = entityEntry.getLoadedState();
final boolean debugEnabled = LOG.isDebugEnabled();
if ( debugEnabled ) {
@@ -161,7 +163,7 @@ public final class TwoPhaseLoad {
);
}
- Type[] types = persister.getPropertyTypes();
+ final Type[] types = persister.getPropertyTypes();
for ( int i = 0; i < hydratedState.length; i++ ) {
final Object value = hydratedState[i];
if ( value!=LazyPropertyInitializer.UNFETCHED_PROPERTY && value!=BackrefPropertyAccessor.UNKNOWN ) {
@@ -195,9 +197,9 @@ public final class TwoPhaseLoad {
);
}
- Object version = Versioning.getVersion(hydratedState, persister);
- CacheEntry entry = persister.buildCacheEntry( entity, hydratedState, version, session );
- CacheKey cacheKey = session.generateCacheKey( id, persister.getIdentifierType(), persister.getRootEntityName() );
+ final Object version = Versioning.getVersion( hydratedState, persister );
+ final CacheEntry entry = persister.buildCacheEntry( entity, hydratedState, version, session );
+ final CacheKey cacheKey = session.generateCacheKey( id, persister.getIdentifierType(), persister.getRootEntityName() );
// explicit handling of caching for rows just inserted and then somehow forced to be read
// from the database *within the same transaction*. usually this is done by
@@ -214,7 +216,7 @@ public final class TwoPhaseLoad {
);
}
else {
- boolean put = persister.getCacheAccessStrategy().putFromLoad(
+ final boolean put = persister.getCacheAccessStrategy().putFromLoad(
cacheKey,
persister.getCacheEntryStructure().structure( entry ),
session.getTimestamp(),
@@ -241,11 +243,11 @@ public final class TwoPhaseLoad {
isReallyReadOnly = true;
}
else {
- Object proxy = persistenceContext.getProxy( entityEntry.getEntityKey() );
+ final Object proxy = persistenceContext.getProxy( entityEntry.getEntityKey() );
if ( proxy != null ) {
// there is already a proxy for this impl
// only set the status to read-only if the proxy is read-only
- isReallyReadOnly = ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().isReadOnly();
+ isReallyReadOnly = ( (HibernateProxy) proxy ).getHibernateLazyInitializer().isReadOnly();
}
}
if ( isReallyReadOnly ) {
@@ -253,7 +255,7 @@ public final class TwoPhaseLoad {
//performance optimization, but not really
//important, except for entities with huge
//mutable property values
- persistenceContext.setEntryStatus(entityEntry, Status.READ_ONLY);
+ persistenceContext.setEntryStatus( entityEntry, Status.READ_ONLY );
}
else {
//take a snapshot
@@ -261,10 +263,11 @@ public final class TwoPhaseLoad {
hydratedState,
persister.getPropertyTypes(),
persister.getPropertyUpdateability(),
- hydratedState, //after setting values to object, entityMode
+ //after setting values to object
+ hydratedState,
session
);
- persistenceContext.setEntryStatus(entityEntry, Status.MANAGED);
+ persistenceContext.setEntryStatus( entityEntry, Status.MANAGED );
}
persister.afterInitialize(
@@ -290,13 +293,12 @@ public final class TwoPhaseLoad {
* the Set collections are added to the persistence context by Loader.
* Without the split, LazyInitializationExceptions can occur in the Entity's
* postLoad if it acts upon the collection.
- *
- *
+ *
* HHH-6043
*
- * @param entity
- * @param session
- * @param postLoadEvent
+ * @param entity The entity
+ * @param session The Session
+ * @param postLoadEvent The (re-used) post-load event
*/
public static void postLoad(
final Object entity,
@@ -306,15 +308,11 @@ public final class TwoPhaseLoad {
if ( session.isEventSource() ) {
final PersistenceContext persistenceContext
= session.getPersistenceContext();
- final EntityEntry entityEntry = persistenceContext.getEntry(entity);
- final Serializable id = entityEntry.getId();
-
- postLoadEvent.setEntity( entity ).setId( entityEntry.getId() )
- .setPersister( entityEntry.getPersister() );
+ final EntityEntry entityEntry = persistenceContext.getEntry( entity );
- final EventListenerGroup listenerGroup
- = session
- .getFactory()
+ postLoadEvent.setEntity( entity ).setId( entityEntry.getId() ).setPersister( entityEntry.getPersister() );
+
+ final EventListenerGroup listenerGroup = session.getFactory()
.getServiceRegistry()
.getService( EventListenerRegistry.class )
.getEventListenerGroup( EventType.POST_LOAD );
@@ -325,11 +323,11 @@ public final class TwoPhaseLoad {
}
private static boolean useMinimalPuts(SessionImplementor session, EntityEntry entityEntry) {
- return ( session.getFactory().getSettings().isMinimalPutsEnabled() &&
- session.getCacheMode()!=CacheMode.REFRESH ) ||
- ( entityEntry.getPersister().hasLazyProperties() &&
- entityEntry.isLoadedWithLazyPropertiesUnfetched() &&
- entityEntry.getPersister().isLazyPropertiesCacheable() );
+ return ( session.getFactory().getSettings().isMinimalPutsEnabled()
+ && session.getCacheMode()!=CacheMode.REFRESH )
+ || ( entityEntry.getPersister().hasLazyProperties()
+ && entityEntry.isLoadedWithLazyPropertiesUnfetched()
+ && entityEntry.getPersister().isLazyPropertiesCacheable() );
}
/**
@@ -338,15 +336,21 @@ public final class TwoPhaseLoad {
*
* Create a "temporary" entry for a newly instantiated entity. The entity is uninitialized,
* but we need the mapping from id to instance in order to guarantee uniqueness.
+ *
+ * @param key The entity key
+ * @param object The entity instance
+ * @param persister The entity persister
+ * @param lockMode The lock mode
+ * @param lazyPropertiesAreUnFetched Are lazy properties still un-fetched?
+ * @param session The Session
*/
public static void addUninitializedEntity(
final EntityKey key,
final Object object,
final EntityPersister persister,
final LockMode lockMode,
- final boolean lazyPropertiesAreUnfetched,
- final SessionImplementor session
- ) {
+ final boolean lazyPropertiesAreUnFetched,
+ final SessionImplementor session) {
session.getPersistenceContext().addEntity(
object,
Status.LOADING,
@@ -357,19 +361,29 @@ public final class TwoPhaseLoad {
true,
persister,
false,
- lazyPropertiesAreUnfetched
- );
+ lazyPropertiesAreUnFetched
+ );
}
+ /**
+ * Same as {@link #addUninitializedEntity}, but here for an entity from the second level cache
+ *
+ * @param key The entity key
+ * @param object The entity instance
+ * @param persister The entity persister
+ * @param lockMode The lock mode
+ * @param lazyPropertiesAreUnFetched Are lazy properties still un-fetched?
+ * @param version The version
+ * @param session The Session
+ */
public static void addUninitializedCachedEntity(
final EntityKey key,
final Object object,
final EntityPersister persister,
final LockMode lockMode,
- final boolean lazyPropertiesAreUnfetched,
+ final boolean lazyPropertiesAreUnFetched,
final Object version,
- final SessionImplementor session
- ) {
+ final SessionImplementor session) {
session.getPersistenceContext().addEntity(
object,
Status.LOADING,
@@ -380,7 +394,7 @@ public final class TwoPhaseLoad {
true,
persister,
false,
- lazyPropertiesAreUnfetched
+ lazyPropertiesAreUnFetched
);
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/UnsavedValueFactory.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/UnsavedValueFactory.java
index 23d8e5c517..e7a9f9c727 100755
--- a/hibernate-core/src/main/java/org/hibernate/engine/internal/UnsavedValueFactory.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/UnsavedValueFactory.java
@@ -37,13 +37,24 @@ import org.hibernate.type.Type;
import org.hibernate.type.VersionType;
/**
+ * Helper for dealing with unsaved value handling
+ *
* @author Gavin King
*/
public class UnsavedValueFactory {
-
+
+ /**
+ * Instantiate a class using the provided Constructor
+ *
+ * @param constructor The constructor
+ *
+ * @return The instantiated object
+ *
+ * @throws InstantiationException if something went wrong
+ */
private static Object instantiate(Constructor constructor) {
try {
- return constructor.newInstance( (Object[]) null );
+ return constructor.newInstance();
}
catch (Exception e) {
throw new InstantiationException( "could not instantiate test object", constructor.getDeclaringClass(), e );
@@ -54,22 +65,28 @@ public class UnsavedValueFactory {
* Return an IdentifierValue for the specified unsaved-value. If none is specified,
* guess the unsaved value by instantiating a test instance of the class and
* reading it's id property, or if that is not possible, using the java default
- * value for the type
+ * value for the type
+ *
+ * @param unsavedValue The mapping defined unsaved value
+ * @param identifierGetter The getter for the entity identifier attribute
+ * @param identifierType The mapping type for the identifier
+ * @param constructor The constructor for the entity
+ *
+ * @return The appropriate IdentifierValue
*/
public static IdentifierValue getUnsavedIdentifierValue(
- String unsavedValue,
+ String unsavedValue,
Getter identifierGetter,
Type identifierType,
Constructor constructor) {
-
if ( unsavedValue == null ) {
- if ( identifierGetter!=null && constructor!=null ) {
+ if ( identifierGetter != null && constructor != null ) {
// use the id value of a newly instantiated instance as the unsaved-value
- Serializable defaultValue = (Serializable) identifierGetter.get( instantiate(constructor) );
+ final Serializable defaultValue = (Serializable) identifierGetter.get( instantiate(constructor) );
return new IdentifierValue( defaultValue );
}
else if ( identifierGetter != null && (identifierType instanceof PrimitiveType) ) {
- Serializable defaultValue = ( ( PrimitiveType ) identifierType ).getDefaultValue();
+ final Serializable defaultValue = ( (PrimitiveType) identifierType ).getDefaultValue();
return new IdentifierValue( defaultValue );
}
else {
@@ -90,7 +107,7 @@ public class UnsavedValueFactory {
}
else {
try {
- return new IdentifierValue( ( Serializable ) ( ( IdentifierType ) identifierType ).stringToObject( unsavedValue ) );
+ return new IdentifierValue( (Serializable) ( (IdentifierType) identifierType ).stringToObject( unsavedValue ) );
}
catch ( ClassCastException cce ) {
throw new MappingException( "Bad identifier type: " + identifierType.getName() );
@@ -101,6 +118,19 @@ public class UnsavedValueFactory {
}
}
+ /**
+ * Return an IdentifierValue for the specified unsaved-value. If none is specified,
+ * guess the unsaved value by instantiating a test instance of the class and
+ * reading it's version property value, or if that is not possible, using the java default
+ * value for the type
+ *
+ * @param versionUnsavedValue The mapping defined unsaved value
+ * @param versionGetter The version attribute getter
+ * @param versionType The mapping type for the version
+ * @param constructor The constructor for the entity
+ *
+ * @return The appropriate VersionValue
+ */
public static VersionValue getUnsavedVersionValue(
String versionUnsavedValue,
Getter versionGetter,
@@ -109,12 +139,12 @@ public class UnsavedValueFactory {
if ( versionUnsavedValue == null ) {
if ( constructor!=null ) {
- Object defaultValue = versionGetter.get( instantiate(constructor) );
+ final Object defaultValue = versionGetter.get( instantiate( constructor ) );
// if the version of a newly instantiated object is not the same
// as the version seed value, use that as the unsaved-value
- return versionType.isEqual( versionType.seed( null ), defaultValue ) ?
- VersionValue.UNDEFINED :
- new VersionValue( defaultValue );
+ return versionType.isEqual( versionType.seed( null ), defaultValue )
+ ? VersionValue.UNDEFINED
+ : new VersionValue( defaultValue );
}
else {
return VersionValue.UNDEFINED;
@@ -133,7 +163,8 @@ public class UnsavedValueFactory {
// this should not happen since the DTD prevents it
throw new MappingException( "Could not parse version unsaved-value: " + versionUnsavedValue );
}
-
}
+ private UnsavedValueFactory() {
+ }
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/Versioning.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/Versioning.java
index 5cf6fdcd51..dd72581fea 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/internal/Versioning.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/Versioning.java
@@ -36,38 +36,16 @@ import org.hibernate.type.VersionType;
* @author Gavin King
*/
public final class Versioning {
-
- // todo : replace these constants with references to org.hibernate.annotations.OptimisticLockType enum
-
- /**
- * Apply no optimistic locking
- */
- public static final int OPTIMISTIC_LOCK_NONE = -1;
-
- /**
- * Apply optimistic locking based on the defined version or timestamp
- * property.
- */
- public static final int OPTIMISTIC_LOCK_VERSION = 0;
-
- /**
- * Apply optimistic locking based on the a current vs. snapshot comparison
- * of all properties.
- */
- public static final int OPTIMISTIC_LOCK_ALL = 2;
-
- /**
- * Apply optimistic locking based on the a current vs. snapshot comparison
- * of dirty properties.
- */
- public static final int OPTIMISTIC_LOCK_DIRTY = 1;
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, Versioning.class.getName() );
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ Versioning.class.getName()
+ );
/**
* Private constructor disallowing instantiation.
*/
- private Versioning() {}
+ private Versioning() {
+ }
/**
* Create an initial optimistic locking value according the {@link VersionType}
@@ -78,8 +56,8 @@ public final class Versioning {
* @return The initial optimistic locking value
*/
private static Object seed(VersionType versionType, SessionImplementor session) {
- Object seed = versionType.seed( session );
- LOG.tracev( "Seeding: {0}", seed );
+ final Object seed = versionType.seed( session );
+ LOG.tracef( "Seeding: %s", seed );
return seed;
}
@@ -96,11 +74,11 @@ public final class Versioning {
* otherwise.
*/
public static boolean seedVersion(
- Object[] fields,
- int versionProperty,
- VersionType versionType,
- SessionImplementor session) {
- Object initialVersion = fields[versionProperty];
+ Object[] fields,
+ int versionProperty,
+ VersionType versionType,
+ SessionImplementor session) {
+ final Object initialVersion = fields[versionProperty];
if (
initialVersion==null ||
// This next bit is to allow for both unsaved-value="negative"
@@ -126,11 +104,15 @@ public final class Versioning {
* @param session The originating session
* @return The incremented optimistic locking value.
*/
+ @SuppressWarnings("unchecked")
public static Object increment(Object version, VersionType versionType, SessionImplementor session) {
- Object next = versionType.next( version, session );
+ final Object next = versionType.next( version, session );
if ( LOG.isTraceEnabled() ) {
- LOG.tracev( "Incrementing: {0} to {1}", versionType.toLoggableString( version, session.getFactory() ),
- versionType.toLoggableString( next, session.getFactory() ) );
+ LOG.tracef(
+ "Incrementing: %s to %s",
+ versionType.toLoggableString( version, session.getFactory() ),
+ versionType.toLoggableString( next, session.getFactory() )
+ );
}
return next;
}
@@ -178,8 +160,8 @@ public final class Versioning {
if ( hasDirtyCollections ) {
return true;
}
- for ( int i = 0; i < dirtyProperties.length; i++ ) {
- if ( propertyVersionability[ dirtyProperties[i] ] ) {
+ for ( int dirtyProperty : dirtyProperties ) {
+ if ( propertyVersionability[dirtyProperty] ) {
return true;
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java
index 1ac0388104..9b87aa8960 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java
@@ -33,6 +33,7 @@ import org.hibernate.LockMode;
import org.hibernate.MappingException;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.loading.internal.LoadContexts;
+import org.hibernate.internal.util.MarkerObject;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
@@ -52,7 +53,11 @@ import org.hibernate.persister.entity.EntityPersister;
*/
@SuppressWarnings( {"JavaDoc"})
public interface PersistenceContext {
-
+ /**
+ * Marker object used to indicate (via reference checking) that no row was returned.
+ */
+ public static final Object NO_ROW = new MarkerObject( "NO_ROW" );
+
@SuppressWarnings( {"UnusedDeclaration"})
public boolean isStateless();
@@ -135,11 +140,15 @@ public interface PersistenceContext {
public Object[] getDatabaseSnapshot(Serializable id, EntityPersister persister);
/**
- * Get the current database state of the entity, using the cached state snapshot if one is available.
- *
- * @param key The entity key
- *
- * @return The entity's (non-cached) snapshot
+ * Retrieve the cached database snapshot for the requested entity key.
+ *
+ * This differs from {@link #getDatabaseSnapshot} is two important respects:
+ * - no snapshot is obtained from the database if not already cached
+ * - an entry of {@link #NO_ROW} here is interpretet as an exception
+ *
+ * @param key The entity key for which to retrieve the cached snapshot
+ * @return The cached snapshot
+ * @throws IllegalStateException if the cached snapshot was == {@link #NO_ROW}.
*/
public Object[] getCachedDatabaseSnapshot(EntityKey key);
@@ -316,7 +325,9 @@ public interface PersistenceContext {
/**
* Attempts to check whether the given key represents an entity already loaded within the
* current session.
+ *
* @param object The entity reference against which to perform the uniqueness check.
+ *
* @throws HibernateException
*/
public void checkUniqueness(EntityKey key, Object object) throws HibernateException;
@@ -467,7 +478,13 @@ public interface PersistenceContext {
public void addProxy(EntityKey key, Object proxy);
/**
- * Remove a proxy from the session cache
+ * Remove a proxy from the session cache.
+ *
+ * Additionally, ensure that any load optimization references
+ * such as batch or subselect loading get cleaned up as well.
+ *
+ * @param key The key of the entity proxy to be removed
+ * @return The proxy reference.
*/
public Object removeProxy(EntityKey key);
@@ -559,10 +576,27 @@ public interface PersistenceContext {
public String toString();
/**
- * Search the persistence context for an owner for the child object,
- * given a collection role
+ * Search this persistence context for an associated entity instance which is considered the "owner" of
+ * the given childEntity, and return that owner's id value. This is performed in the scenario of a
+ * uni-directional, non-inverse one-to-many collection (which means that the collection elements do not maintain
+ * a direct reference to the owner).
+ *
+ * As such, the processing here is basically to loop over every entity currently associated with this persistence
+ * context and for those of the correct entity (sub) type to extract its collection role property value and see
+ * if the child is contained within that collection. If so, we have found the owner; if not, we go on.
+ *
+ * Also need to account for mergeMap which acts as a local copy cache managed for the duration of a merge
+ * operation. It represents a map of the detached entity instances pointing to the corresponding managed instance.
+ *
+ * @param entityName The entity name for the entity type which would own the child
+ * @param propertyName The name of the property on the owning entity type which would name this child association.
+ * @param childEntity The child entity instance for which to locate the owner instance id.
+ * @param mergeMap A map of non-persistent instances from an on-going merge operation (possibly null).
+ *
+ * @return The id of the entityName instance which is said to own the child; null if an appropriate owner not
+ * located.
*/
- public Serializable getOwnerId(String entity, String property, Object childObject, Map mergeMap);
+ public Serializable getOwnerId(String entityName, String propertyName, Object childEntity, Map mergeMap);
/**
* Search the persistence context for an index of the child object,
diff --git a/hibernate-core/src/main/java/org/hibernate/loader/Loader.java b/hibernate-core/src/main/java/org/hibernate/loader/Loader.java
index 0b78c1bd63..784559c18d 100644
--- a/hibernate-core/src/main/java/org/hibernate/loader/Loader.java
+++ b/hibernate-core/src/main/java/org/hibernate/loader/Loader.java
@@ -1099,7 +1099,7 @@ public abstract class Loader {
if ( LOG.isTraceEnabled() )
LOG.tracev( "Total objects hydrated: {0}", hydratedObjectsSize );
for ( int i = 0; i < hydratedObjectsSize; i++ ) {
- TwoPhaseLoad.initializeEntity( hydratedObjects.get(i), readOnly, session, pre, post );
+ TwoPhaseLoad.initializeEntity( hydratedObjects.get(i), readOnly, session, pre );
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/loader/internal/ResultSetProcessingContextImpl.java b/hibernate-core/src/main/java/org/hibernate/loader/internal/ResultSetProcessingContextImpl.java
index 49e51a4dfd..940dab925d 100644
--- a/hibernate-core/src/main/java/org/hibernate/loader/internal/ResultSetProcessingContextImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/loader/internal/ResultSetProcessingContextImpl.java
@@ -664,7 +664,7 @@ public class ResultSetProcessingContextImpl implements ResultSetProcessingContex
}
// now finish loading the entities (2-phase load)
- performTwoPhaseLoad( preLoadEvent, postLoadEvent );
+ performTwoPhaseLoad( preLoadEvent );
// now we can finalize loading collections
finishLoadingCollections();
@@ -699,7 +699,7 @@ public class ResultSetProcessingContextImpl implements ResultSetProcessingContex
);
}
- private void performTwoPhaseLoad(PreLoadEvent preLoadEvent, PostLoadEvent postLoadEvent) {
+ private void performTwoPhaseLoad(PreLoadEvent preLoadEvent) {
final int numberOfHydratedObjects = hydratedEntityRegistrationList == null
? 0
: hydratedEntityRegistrationList.size();
@@ -710,7 +710,7 @@ public class ResultSetProcessingContextImpl implements ResultSetProcessingContex
}
for ( HydratedEntityRegistration registration : hydratedEntityRegistrationList ) {
- TwoPhaseLoad.initializeEntity( registration.instance, readOnly, session, preLoadEvent, postLoadEvent );
+ TwoPhaseLoad.initializeEntity( registration.instance, readOnly, session, preLoadEvent );
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java b/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java
index e8a299dd48..41f1bb2346 100644
--- a/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java
+++ b/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java
@@ -33,6 +33,8 @@ import java.util.StringTokenizer;
import org.hibernate.EntityMode;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.lock.OptimisticLockingStrategy;
+import org.hibernate.engine.OptimisticLockStyle;
import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.internal.FilterConfiguration;
@@ -100,9 +102,9 @@ public abstract class PersistentClass implements Serializable, Filterable, MetaA
private java.util.Map tuplizerImpls;
- protected int optimisticLockMode;
private MappedSuperclass superMappedSuperclass;
private Component declaredIdentifierMapper;
+ private OptimisticLockStyle optimisticLockStyle;
public String getClassName() {
return className;
@@ -456,10 +458,22 @@ public abstract class PersistentClass implements Serializable, Filterable, MetaA
}
}
- abstract public int getOptimisticLockMode();
+ @Deprecated
+ public int getOptimisticLockMode() {
+ return getOptimisticLockStyle().getOldCode();
+ }
+ @Deprecated
public void setOptimisticLockMode(int optimisticLockMode) {
- this.optimisticLockMode = optimisticLockMode;
+ setOptimisticLockStyle( OptimisticLockStyle.interpretOldCode( optimisticLockMode ) );
+ }
+
+ public OptimisticLockStyle getOptimisticLockStyle() {
+ return optimisticLockStyle;
+ }
+
+ public void setOptimisticLockStyle(OptimisticLockStyle optimisticLockStyle) {
+ this.optimisticLockStyle = optimisticLockStyle;
}
public void validate(Mapping mapping) throws MappingException {
diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java b/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java
index 59c5775cad..774aa95e5a 100644
--- a/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java
+++ b/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java
@@ -31,6 +31,7 @@ import java.util.Set;
import org.jboss.logging.Logger;
import org.hibernate.MappingException;
+import org.hibernate.engine.OptimisticLockStyle;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.ReflectHelper;
@@ -351,10 +352,4 @@ public class RootClass extends PersistentClass implements TableOwner {
public Object accept(PersistentClassVisitor mv) {
return mv.accept(this);
}
-
- @Override
- public int getOptimisticLockMode() {
- return optimisticLockMode;
- }
-
}
diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java b/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java
index c45d4cee16..1133d500bb 100644
--- a/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java
+++ b/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java
@@ -30,6 +30,7 @@ import java.util.Map;
import org.hibernate.AssertionFailure;
import org.hibernate.EntityMode;
+import org.hibernate.engine.OptimisticLockStyle;
import org.hibernate.internal.util.collections.JoinedIterator;
import org.hibernate.internal.util.collections.SingletonIterator;
@@ -295,9 +296,9 @@ public class Subclass extends PersistentClass {
public Component getIdentifierMapper() {
return superclass.getIdentifierMapper();
}
-
- public int getOptimisticLockMode() {
- return superclass.getOptimisticLockMode();
- }
+ @Override
+ public OptimisticLockStyle getOptimisticLockStyle() {
+ return superclass.getOptimisticLockStyle();
+ }
}
diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java b/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java
index 7d0b2717fe..16e5701076 100644
--- a/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java
+++ b/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java
@@ -325,7 +325,7 @@ public class EntityMetamodel implements Serializable {
null;
hasSubclasses = persistentClass.hasSubclasses();
- optimisticLockStyle = interpretOptLockMode( persistentClass.getOptimisticLockMode() );
+ optimisticLockStyle = persistentClass.getOptimisticLockStyle();
final boolean isAllOrDirty =
optimisticLockStyle == OptimisticLockStyle.ALL
|| optimisticLockStyle == OptimisticLockStyle.DIRTY;
@@ -365,23 +365,6 @@ public class EntityMetamodel implements Serializable {
}
}
- private OptimisticLockStyle interpretOptLockMode(int optimisticLockMode) {
- switch ( optimisticLockMode ) {
- case Versioning.OPTIMISTIC_LOCK_NONE: {
- return OptimisticLockStyle.NONE;
- }
- case Versioning.OPTIMISTIC_LOCK_DIRTY: {
- return OptimisticLockStyle.DIRTY;
- }
- case Versioning.OPTIMISTIC_LOCK_ALL: {
- return OptimisticLockStyle.ALL;
- }
- default: {
- return OptimisticLockStyle.VERSION;
- }
- }
- }
-
public EntityMetamodel(
EntityBinding entityBinding,
AbstractEntityPersister persister,
diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/entity/NewCustomEntityMappingAnnotationsTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/entity/NewCustomEntityMappingAnnotationsTest.java
index 64d6c831e4..5e81af1c68 100644
--- a/hibernate-core/src/test/java/org/hibernate/test/annotations/entity/NewCustomEntityMappingAnnotationsTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/entity/NewCustomEntityMappingAnnotationsTest.java
@@ -52,7 +52,7 @@ public class NewCustomEntityMappingAnnotationsTest extends BaseCoreFunctionalTes
assertEquals( forest.useDynamicInsert(), forest2.useDynamicInsert() );
assertEquals( forest.useDynamicUpdate(), forest2.useDynamicUpdate() );
assertEquals( forest.hasSelectBeforeUpdate(), forest2.hasSelectBeforeUpdate() );
- assertEquals( forest.getOptimisticLockMode(), forest2.getOptimisticLockMode() );
+ assertEquals( forest.getOptimisticLockStyle(), forest2.getOptimisticLockStyle() );
assertEquals( forest.isExplicitPolymorphism(), forest2.isExplicitPolymorphism() );
}
}
diff --git a/hibernate-core/src/test/java/org/hibernate/test/legacy/CustomPersister.java b/hibernate-core/src/test/java/org/hibernate/test/legacy/CustomPersister.java
index a4b56b0193..64553579b4 100644
--- a/hibernate-core/src/test/java/org/hibernate/test/legacy/CustomPersister.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/legacy/CustomPersister.java
@@ -309,7 +309,7 @@ public class CustomPersister implements EntityPersister {
LockMode.NONE,
false,
session
- );
+ );
TwoPhaseLoad.postHydrate(
this, id,
new String[] { obj.getName() },
@@ -318,14 +318,14 @@ public class CustomPersister implements EntityPersister {
LockMode.NONE,
false,
session
- );
+ );
TwoPhaseLoad.initializeEntity(
clone,
false,
session,
- new PreLoadEvent( (EventSource) session ),
- new PostLoadEvent( (EventSource) session )
- );
+ new PreLoadEvent( (EventSource) session )
+ );
+ TwoPhaseLoad.postLoad( clone, session, new PostLoadEvent( (EventSource) session ) );
}
return clone;
}
From 194cd5e4bdc369fe258e37e4303d1cd6d3af5363 Mon Sep 17 00:00:00 2001
From: Steve Ebersole
Date: Mon, 29 Apr 2013 09:55:39 -0500
Subject: [PATCH 22/57] HHH-8159 - Apply fixups indicated by analysis tools
---
.../test/java/org/hibernate/jpa/test/EntityManagerTest.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java
index 70f60b1a9b..bf3be224c3 100755
--- a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java
+++ b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java
@@ -279,8 +279,8 @@ public class EntityManagerTest extends BaseEntityManagerFunctionalTestCase {
IllegalArgumentException deserializedException = ( IllegalArgumentException ) in.readObject();
in.close();
byteIn.close();
- assertNull( deserializedException.getCause().getCause().getCause() );
- assertNull( e.getCause().getCause().getCause() );
+ assertNull( deserializedException.getCause().getCause() );
+ assertNull( e.getCause().getCause() );
}
em.getTransaction().rollback();
em.close();
From 398000517f6fa1d7ef29f4b3ca827440af2f3a56 Mon Sep 17 00:00:00 2001
From: Brett Meyer
Date: Fri, 26 Apr 2013 12:39:54 -0400
Subject: [PATCH 23/57] HHH-7943 Reworked "Availability" concepts into
"strategy registration providers". Updated proxool and c3p0 to use strategy
selection.
---
.../internal/C3P0ConnectionProvider.java | 2 +-
.../internal/C3P0MessageLogger.java | 2 +-
.../StrategyRegistrationProviderImpl.java | 57 +++++++++++++
...stry.selector.StrategyRegistrationProvider | 1 +
.../test/c3p0/C3P0ConnectionProviderTest.java | 2 +-
.../BootstrapServiceRegistryBuilder.java | 14 +--
...va => SimpleStrategyRegistrationImpl.java} | 12 +--
...ability.java => StrategyRegistration.java} | 10 +--
...java => StrategyRegistrationProvider.java} | 12 ++-
.../internal/StrategySelectorBuilder.java | 50 +++++------
.../internal/ConnectionProviderInitiator.java | 85 ++++++++-----------
... => StrategyRegistrationProviderImpl.java} | 22 ++---
...ot.registry.selector.AvailabilityAnnouncer | 1 -
...stry.selector.StrategyRegistrationProvider | 1 +
... => StrategyRegistrationProviderImpl.java} | 22 ++---
.../internal/ProxoolConnectionProvider.java | 2 +-
.../internal/ProxoolMessageLogger.java | 2 +-
.../StrategyRegistrationProviderImpl.java | 57 +++++++++++++
...stry.selector.StrategyRegistrationProvider | 1 +
.../ProxoolConnectionProviderTest.java | 3 +-
20 files changed, 229 insertions(+), 129 deletions(-)
rename hibernate-c3p0/src/main/java/org/hibernate/{service/jdbc/connections => c3p0}/internal/C3P0ConnectionProvider.java (99%)
rename hibernate-c3p0/src/main/java/org/hibernate/{service/jdbc/connections => c3p0}/internal/C3P0MessageLogger.java (98%)
create mode 100644 hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java
create mode 100644 hibernate-c3p0/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider
rename hibernate-core/src/main/java/org/hibernate/boot/registry/selector/{SimpleAvailabilityImpl.java => SimpleStrategyRegistrationImpl.java} (88%)
rename hibernate-core/src/main/java/org/hibernate/boot/registry/selector/{Availability.java => StrategyRegistration.java} (89%)
rename hibernate-core/src/main/java/org/hibernate/boot/registry/selector/{AvailabilityAnnouncer.java => StrategyRegistrationProvider.java} (82%)
rename hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/{AvailabilityAnnouncerImpl.java => StrategyRegistrationProviderImpl.java} (74%)
delete mode 100644 hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.AvailabilityAnnouncer
create mode 100644 hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider
rename hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/{AvailabilityAnnouncerImpl.java => StrategyRegistrationProviderImpl.java} (72%)
rename hibernate-proxool/src/main/java/org/hibernate/{service/jdbc/connections => proxool}/internal/ProxoolConnectionProvider.java (99%)
rename hibernate-proxool/src/main/java/org/hibernate/{service/jdbc/connections => proxool}/internal/ProxoolMessageLogger.java (98%)
create mode 100644 hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java
create mode 100644 hibernate-proxool/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider
rename hibernate-proxool/src/test/java/org/hibernate/{service/jdbc/connections/internal => test/proxool}/ProxoolConnectionProviderTest.java (96%)
diff --git a/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0ConnectionProvider.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java
similarity index 99%
rename from hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0ConnectionProvider.java
rename to hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java
index 61238d83f5..f3b3498586 100644
--- a/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0ConnectionProvider.java
+++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java
@@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.service.jdbc.connections.internal;
+package org.hibernate.c3p0.internal;
import java.sql.Connection;
import java.sql.SQLException;
diff --git a/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0MessageLogger.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java
similarity index 98%
rename from hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0MessageLogger.java
rename to hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java
index 434af89276..0f37a41e29 100644
--- a/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0MessageLogger.java
+++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java
@@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.service.jdbc.connections.internal;
+package org.hibernate.c3p0.internal;
import java.sql.SQLException;
diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java
new file mode 100644
index 0000000000..4237221181
--- /dev/null
+++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java
@@ -0,0 +1,57 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2012, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.c3p0.internal;
+
+import java.util.Collections;
+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.engine.jdbc.connections.spi.ConnectionProvider;
+
+/**
+ * Provides the {@link C3P0ConnectionProvider} to the
+ * {@link org.hibernate.boot.registry.selector.spi.StrategySelector} service.
+ *
+ * @author Brett Meyer
+ */
+public class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider {
+
+ private static final List REGISTRATIONS = Collections.singletonList(
+ (StrategyRegistration) new SimpleStrategyRegistrationImpl(
+ ConnectionProvider.class,
+ C3P0ConnectionProvider.class,
+ "c3p0",
+ C3P0ConnectionProvider.class.getSimpleName(),
+ "org.hibernate.connection.C3P0ConnectionProvider", // legacy
+ "org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" // legacy
+ ) );
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public Iterable getStrategyRegistrations() {
+ return REGISTRATIONS;
+ }
+}
diff --git a/hibernate-c3p0/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider b/hibernate-c3p0/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider
new file mode 100644
index 0000000000..cde2be1446
--- /dev/null
+++ b/hibernate-c3p0/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider
@@ -0,0 +1 @@
+org.hibernate.c3p0.internal.StrategyRegistrationProviderImpl
diff --git a/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/C3P0ConnectionProviderTest.java b/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/C3P0ConnectionProviderTest.java
index 2175f15193..03e3c4fb33 100644
--- a/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/C3P0ConnectionProviderTest.java
+++ b/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/C3P0ConnectionProviderTest.java
@@ -30,8 +30,8 @@ import javax.management.ObjectName;
import org.junit.Test;
+import org.hibernate.c3p0.internal.C3P0ConnectionProvider;
import org.hibernate.engine.jdbc.spi.JdbcServices;
-import org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/BootstrapServiceRegistryBuilder.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/BootstrapServiceRegistryBuilder.java
index 775ea0f4cf..ce59202409 100644
--- a/hibernate-core/src/main/java/org/hibernate/boot/registry/BootstrapServiceRegistryBuilder.java
+++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/BootstrapServiceRegistryBuilder.java
@@ -32,8 +32,8 @@ import java.util.Set;
import org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.registry.internal.BootstrapServiceRegistryImpl;
-import org.hibernate.boot.registry.selector.Availability;
-import org.hibernate.boot.registry.selector.AvailabilityAnnouncer;
+import org.hibernate.boot.registry.selector.StrategyRegistration;
+import org.hibernate.boot.registry.selector.StrategyRegistrationProvider;
import org.hibernate.boot.registry.selector.internal.StrategySelectorBuilder;
import org.hibernate.integrator.internal.IntegratorServiceImpl;
import org.hibernate.integrator.spi.Integrator;
@@ -169,23 +169,23 @@ public class BootstrapServiceRegistryBuilder {
*/
@SuppressWarnings( {"UnusedDeclaration"})
public BootstrapServiceRegistryBuilder withStrategySelector(Class strategy, String name, Class extends T> implementation) {
- this.strategySelectorBuilder.addExplicitAvailability( strategy, implementation, name );
+ this.strategySelectorBuilder.addExplicitStrategyRegistration( strategy, implementation, name );
return this;
}
/**
* Applies one or more strategy selectors announced as available by the passed announcer.
*
- * @param availabilityAnnouncer An announcer for one or more available selectors
+ * @param strategyRegistrationProvider An provider for one or more available selectors
*
* @return {@code this}, for method chaining
*
* @see org.hibernate.boot.registry.selector.spi.StrategySelector#registerStrategyImplementor(Class, String, Class)
*/
@SuppressWarnings( {"UnusedDeclaration"})
- public BootstrapServiceRegistryBuilder withStrategySelectors(AvailabilityAnnouncer availabilityAnnouncer) {
- for ( Availability availability : availabilityAnnouncer.getAvailabilities() ) {
- this.strategySelectorBuilder.addExplicitAvailability( availability );
+ public BootstrapServiceRegistryBuilder withStrategySelectors(StrategyRegistrationProvider strategyRegistrationProvider) {
+ for ( StrategyRegistration strategyRegistration : strategyRegistrationProvider.getStrategyRegistrations() ) {
+ this.strategySelectorBuilder.addExplicitStrategyRegistration( strategyRegistration );
}
return this;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleAvailabilityImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleStrategyRegistrationImpl.java
similarity index 88%
rename from hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleAvailabilityImpl.java
rename to hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleStrategyRegistrationImpl.java
index ff536956ab..725b526ef7 100644
--- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleAvailabilityImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleStrategyRegistrationImpl.java
@@ -26,25 +26,25 @@ package org.hibernate.boot.registry.selector;
import java.util.Arrays;
/**
- * A simple implementation of Availability.
+ * A simple implementation of StrategyRegistration.
*
* @param The strategy type.
*
* @author Steve Ebersole
*/
-public class SimpleAvailabilityImpl implements Availability {
+public class SimpleStrategyRegistrationImpl implements StrategyRegistration {
private final Class strategyRole;
private final Class extends T> strategyImplementation;
private final Iterable selectorNames;
/**
- * Constructs a SimpleAvailabilityImpl.
+ * Constructs a SimpleStrategyRegistrationImpl.
*
* @param strategyRole The strategy contract
* @param strategyImplementation The strategy implementation class
* @param selectorNames The selection/registration names for this implementation
*/
- public SimpleAvailabilityImpl(
+ public SimpleStrategyRegistrationImpl(
Class strategyRole,
Class extends T> strategyImplementation,
Iterable selectorNames) {
@@ -54,13 +54,13 @@ public class SimpleAvailabilityImpl implements Availability {
}
/**
- * Constructs a SimpleAvailabilityImpl.
+ * Constructs a SimpleStrategyRegistrationImpl.
*
* @param strategyRole The strategy contract
* @param strategyImplementation The strategy implementation class
* @param selectorNames The selection/registration names for this implementation
*/
- public SimpleAvailabilityImpl(
+ public SimpleStrategyRegistrationImpl(
Class strategyRole,
Class extends T> strategyImplementation,
String... selectorNames) {
diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/Availability.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistration.java
similarity index 89%
rename from hibernate-core/src/main/java/org/hibernate/boot/registry/selector/Availability.java
rename to hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistration.java
index 20de189f6f..5b1fd1b78a 100644
--- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/Availability.java
+++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistration.java
@@ -24,16 +24,14 @@
package org.hibernate.boot.registry.selector;
/**
- * Describes the availability of a named strategy implementation. A strategy + selector name should resolve
+ * Describes the registration of a named strategy implementation. A strategy + selector name should resolve
* to a single implementation.
*
- * todo : better name?
- *
- * @param The type of the strategy described by this implementation availability.
+ * @param The type of the strategy described by this implementation registration.
*
* @author Steve Ebersole
*/
-public interface Availability {
+public interface StrategyRegistration {
/**
* The strategy role. Best practice says this should be an interface.
*
@@ -42,7 +40,7 @@ public interface Availability {
public Class getStrategyRole();
/**
- * Any registered names for this strategy availability.
+ * Any registered names for this strategy registration.
*
* @return The registered selection names.
*/
diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/AvailabilityAnnouncer.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistrationProvider.java
similarity index 82%
rename from hibernate-core/src/main/java/org/hibernate/boot/registry/selector/AvailabilityAnnouncer.java
rename to hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistrationProvider.java
index bcc365a887..df28691ae2 100644
--- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/AvailabilityAnnouncer.java
+++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistrationProvider.java
@@ -24,18 +24,16 @@
package org.hibernate.boot.registry.selector;
/**
- * Responsible for announcing the availability of strategy selector(s). Can be registered directly with the
+ * Responsible for providing the registrations of strategy selector(s). Can be registered directly with the
* {@link org.hibernate.boot.registry.BootstrapServiceRegistry} or located via discovery.
*
- * todo : better name?
- *
* @author Steve Ebersole
*/
-public interface AvailabilityAnnouncer {
+public interface StrategyRegistrationProvider {
/**
- * Get all availabilities announced by this announcer.
+ * Get all StrategyRegistrations announced by this provider.
*
- * @return All announced availabilities
+ * @return All StrategyRegistrations
*/
- public Iterable getAvailabilities();
+ public Iterable getStrategyRegistrations();
}
diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java
index 47d0962f87..2a9f1c56f7 100644
--- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java
+++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java
@@ -27,9 +27,9 @@ import java.util.ArrayList;
import java.util.List;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
-import org.hibernate.boot.registry.selector.Availability;
-import org.hibernate.boot.registry.selector.AvailabilityAnnouncer;
-import org.hibernate.boot.registry.selector.SimpleAvailabilityImpl;
+import org.hibernate.boot.registry.selector.StrategyRegistration;
+import org.hibernate.boot.registry.selector.StrategyRegistrationProvider;
+import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl;
import org.hibernate.boot.registry.selector.spi.StrategySelectionException;
import org.hibernate.boot.registry.selector.spi.StrategySelector;
import org.hibernate.dialect.CUBRIDDialect;
@@ -105,10 +105,10 @@ import org.jboss.logging.Logger;
public class StrategySelectorBuilder {
private static final Logger log = Logger.getLogger( StrategySelectorBuilder.class );
- private final List explicitAvailabilities = new ArrayList();
+ private final List explicitStrategyRegistrations = new ArrayList();
/**
- * Adds an explicit (as opposed to discovered) strategy availability.
+ * Adds an explicit (as opposed to discovered) strategy registration.
*
* @param strategy The strategy
* @param implementation The strategy implementation
@@ -117,31 +117,31 @@ public class StrategySelectorBuilder {
* compatible.
*/
@SuppressWarnings("unchecked")
- public void addExplicitAvailability(Class strategy, Class extends T> implementation, String name) {
- addExplicitAvailability( new SimpleAvailabilityImpl( strategy, implementation, name ) );
+ public void addExplicitStrategyRegistration(Class strategy, Class extends T> implementation, String name) {
+ addExplicitStrategyRegistration( new SimpleStrategyRegistrationImpl( strategy, implementation, name ) );
}
/**
- * Adds an explicit (as opposed to discovered) strategy availability.
+ * Adds an explicit (as opposed to discovered) strategy registration.
*
- * @param availability The strategy implementation availability.
+ * @param strategyRegistration The strategy implementation registration.
* @param The type of the strategy. Used to make sure that the strategy and implementation are type
* compatible.
*/
- public void addExplicitAvailability(Availability availability) {
- if ( !availability.getStrategyRole().isInterface() ) {
+ public void addExplicitStrategyRegistration(StrategyRegistration strategyRegistration) {
+ if ( !strategyRegistration.getStrategyRole().isInterface() ) {
// not good form...
- log.debug( "Registering non-interface strategy : " + availability.getStrategyRole().getName() );
+ log.debug( "Registering non-interface strategy : " + strategyRegistration.getStrategyRole().getName() );
}
- if ( ! availability.getStrategyRole().isAssignableFrom( availability.getStrategyImplementation() ) ) {
+ if ( ! strategyRegistration.getStrategyRole().isAssignableFrom( strategyRegistration.getStrategyImplementation() ) ) {
throw new StrategySelectionException(
- "Implementation class [" + availability.getStrategyImplementation().getName()
+ "Implementation class [" + strategyRegistration.getStrategyImplementation().getName()
+ "] does not implement strategy interface ["
- + availability.getStrategyRole().getName() + "]"
+ + strategyRegistration.getStrategyRole().getName() + "]"
);
}
- explicitAvailabilities.add( availability );
+ explicitStrategyRegistrations.add( strategyRegistration );
}
/**
@@ -162,27 +162,27 @@ public class StrategySelectorBuilder {
addMultiTableBulkIdStrategies( strategySelector );
// apply auto-discovered registrations
- for ( AvailabilityAnnouncer announcer : classLoaderService.loadJavaServices( AvailabilityAnnouncer.class ) ) {
- for ( Availability discoveredAvailability : announcer.getAvailabilities() ) {
- applyFromAvailability( strategySelector, discoveredAvailability );
+ for ( StrategyRegistrationProvider provider : classLoaderService.loadJavaServices( StrategyRegistrationProvider.class ) ) {
+ for ( StrategyRegistration discoveredStrategyRegistration : provider.getStrategyRegistrations() ) {
+ applyFromStrategyRegistration( strategySelector, discoveredStrategyRegistration );
}
}
// apply customizations
- for ( Availability explicitAvailability : explicitAvailabilities ) {
- applyFromAvailability( strategySelector, explicitAvailability );
+ for ( StrategyRegistration explicitStrategyRegistration : explicitStrategyRegistrations ) {
+ applyFromStrategyRegistration( strategySelector, explicitStrategyRegistration );
}
return strategySelector;
}
@SuppressWarnings("unchecked")
- private void applyFromAvailability(StrategySelectorImpl strategySelector, Availability availability) {
- for ( String name : availability.getSelectorNames() ) {
+ private void applyFromStrategyRegistration(StrategySelectorImpl strategySelector, StrategyRegistration strategyRegistration) {
+ for ( String name : strategyRegistration.getSelectorNames() ) {
strategySelector.registerStrategyImplementor(
- availability.getStrategyRole(),
+ strategyRegistration.getStrategyRole(),
name,
- availability.getStrategyImplementation()
+ strategyRegistration.getStrategyImplementation()
);
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java
index cde05919ce..69438692a1 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java
@@ -32,35 +32,33 @@ import java.util.Map;
import java.util.Properties;
import java.util.Set;
-import org.jboss.logging.Logger;
-
import org.hibernate.HibernateException;
import org.hibernate.MultiTenancyStrategy;
import org.hibernate.boot.registry.StandardServiceInitiator;
+import org.hibernate.boot.registry.selector.spi.StrategySelector;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment;
+import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.beans.BeanInfoHelper;
-import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
-import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.ServiceRegistryImplementor;
+import org.jboss.logging.Logger;
/**
* Instantiates and configures an appropriate {@link ConnectionProvider}.
*
* @author Gavin King
* @author Steve Ebersole
+ * @author Brett Meyer
*/
public class ConnectionProviderInitiator implements StandardServiceInitiator {
public static final ConnectionProviderInitiator INSTANCE = new ConnectionProviderInitiator();
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class,
ConnectionProviderInitiator.class.getName());
- public static final String C3P0_PROVIDER_CLASS_NAME =
- "org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider";
+ public static final String C3P0_STRATEGY = "c3p0";
- public static final String PROXOOL_PROVIDER_CLASS_NAME =
- "org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider";
+ public static final String PROXOOL_STRATEGY = "proxool";
public static final String INJECTION_DATA = "hibernate.connection_provider.injection_data";
@@ -83,14 +81,6 @@ public class ConnectionProviderInitiator implements StandardServiceInitiator getAvailabilities() {
- final List availabilities = new ArrayList();
+ public Iterable getStrategyRegistrations() {
+ final List strategyRegistrations = new ArrayList();
- availabilities.add(
- new SimpleAvailabilityImpl(
+ strategyRegistrations.add(
+ new SimpleStrategyRegistrationImpl(
RegionFactory.class,
EhCacheRegionFactory.class,
"ehcache",
@@ -53,8 +53,8 @@ public class AvailabilityAnnouncerImpl implements AvailabilityAnnouncer {
)
);
- availabilities.add(
- new SimpleAvailabilityImpl(
+ strategyRegistrations.add(
+ new SimpleStrategyRegistrationImpl(
RegionFactory.class,
SingletonEhCacheRegionFactory.class,
"ehcache-singleton",
@@ -63,6 +63,6 @@ public class AvailabilityAnnouncerImpl implements AvailabilityAnnouncer {
)
);
- return availabilities;
+ return strategyRegistrations;
}
}
diff --git a/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.AvailabilityAnnouncer b/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.AvailabilityAnnouncer
deleted file mode 100644
index 4089ec9f31..0000000000
--- a/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.AvailabilityAnnouncer
+++ /dev/null
@@ -1 +0,0 @@
-org.hibernate.cache.ehcache.AvailabilityAnnouncerImpl
\ No newline at end of file
diff --git a/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider b/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider
new file mode 100644
index 0000000000..4f53a53867
--- /dev/null
+++ b/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider
@@ -0,0 +1 @@
+org.hibernate.cache.ehcache.StrategyRegistrationProviderImpl
\ No newline at end of file
diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/AvailabilityAnnouncerImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/StrategyRegistrationProviderImpl.java
similarity index 72%
rename from hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/AvailabilityAnnouncerImpl.java
rename to hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/StrategyRegistrationProviderImpl.java
index fc6ad8eccd..611e0587e5 100644
--- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/AvailabilityAnnouncerImpl.java
+++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/StrategyRegistrationProviderImpl.java
@@ -26,9 +26,9 @@ package org.hibernate.cache.infinispan;
import java.util.ArrayList;
import java.util.List;
-import org.hibernate.boot.registry.selector.Availability;
-import org.hibernate.boot.registry.selector.AvailabilityAnnouncer;
-import org.hibernate.boot.registry.selector.SimpleAvailabilityImpl;
+import org.hibernate.boot.registry.selector.StrategyRegistration;
+import org.hibernate.boot.registry.selector.StrategyRegistrationProvider;
+import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl;
import org.hibernate.cache.spi.RegionFactory;
/**
@@ -37,13 +37,13 @@ import org.hibernate.cache.spi.RegionFactory;
*
* @author Steve Ebersole
*/
-public class AvailabilityAnnouncerImpl implements AvailabilityAnnouncer {
+public class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider {
@Override
- public Iterable getAvailabilities() {
- final List availabilities = new ArrayList();
+ public Iterable getStrategyRegistrations() {
+ final List strategyRegistrations = new ArrayList();
- availabilities.add(
- new SimpleAvailabilityImpl(
+ strategyRegistrations.add(
+ new SimpleStrategyRegistrationImpl(
RegionFactory.class,
InfinispanRegionFactory.class,
"infinispan",
@@ -51,8 +51,8 @@ public class AvailabilityAnnouncerImpl implements AvailabilityAnnouncer {
)
);
- availabilities.add(
- new SimpleAvailabilityImpl(
+ strategyRegistrations.add(
+ new SimpleStrategyRegistrationImpl(
RegionFactory.class,
JndiInfinispanRegionFactory.class,
"infinispan-jndi",
@@ -60,6 +60,6 @@ public class AvailabilityAnnouncerImpl implements AvailabilityAnnouncer {
)
);
- return availabilities;
+ return strategyRegistrations;
}
}
diff --git a/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProvider.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolConnectionProvider.java
similarity index 99%
rename from hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProvider.java
rename to hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolConnectionProvider.java
index 9009ecb62a..b8a8fbd8cd 100644
--- a/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProvider.java
+++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolConnectionProvider.java
@@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.service.jdbc.connections.internal;
+package org.hibernate.proxool.internal;
import java.sql.Connection;
import java.sql.DriverManager;
diff --git a/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolMessageLogger.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolMessageLogger.java
similarity index 98%
rename from hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolMessageLogger.java
rename to hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolMessageLogger.java
index 2ff08badb7..568f4c98e9 100644
--- a/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolMessageLogger.java
+++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolMessageLogger.java
@@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.service.jdbc.connections.internal;
+package org.hibernate.proxool.internal;
import org.jboss.logging.LogMessage;
import org.jboss.logging.Message;
diff --git a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java
new file mode 100644
index 0000000000..7104d50399
--- /dev/null
+++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java
@@ -0,0 +1,57 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2012, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.proxool.internal;
+
+import java.util.Collections;
+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.engine.jdbc.connections.spi.ConnectionProvider;
+
+/**
+ * Provides the {@link ProxoolConnectionProvider} to the
+ * {@link org.hibernate.boot.registry.selector.spi.StrategySelector} service.
+ *
+ * @author Brett Meyer
+ */
+public class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider {
+
+ private static final List REGISTRATIONS = Collections.singletonList(
+ (StrategyRegistration) new SimpleStrategyRegistrationImpl(
+ ConnectionProvider.class,
+ ProxoolConnectionProvider.class,
+ "proxool",
+ ProxoolConnectionProvider.class.getSimpleName(),
+ "org.hibernate.connection.ProxoolConnectionProvider", // legacy
+ "org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider" // legacy
+ ) );
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public Iterable getStrategyRegistrations() {
+ return REGISTRATIONS;
+ }
+}
diff --git a/hibernate-proxool/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider b/hibernate-proxool/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider
new file mode 100644
index 0000000000..c794a929dc
--- /dev/null
+++ b/hibernate-proxool/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider
@@ -0,0 +1 @@
+org.hibernate.proxool.internal.StrategyRegistrationProviderImpl
diff --git a/hibernate-proxool/src/test/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProviderTest.java b/hibernate-proxool/src/test/java/org/hibernate/test/proxool/ProxoolConnectionProviderTest.java
similarity index 96%
rename from hibernate-proxool/src/test/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProviderTest.java
rename to hibernate-proxool/src/test/java/org/hibernate/test/proxool/ProxoolConnectionProviderTest.java
index e0776328a3..6285ba328a 100644
--- a/hibernate-proxool/src/test/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProviderTest.java
+++ b/hibernate-proxool/src/test/java/org/hibernate/test/proxool/ProxoolConnectionProviderTest.java
@@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.service.jdbc.connections.internal;
+package org.hibernate.test.proxool;
import java.util.Arrays;
import java.util.List;
@@ -33,6 +33,7 @@ import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
+import org.hibernate.proxool.internal.ProxoolConnectionProvider;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static org.junit.Assert.assertEquals;
From 30d63bf58fe9b15208340b860787d985f032d11a Mon Sep 17 00:00:00 2001
From: Brett Meyer
Date: Mon, 22 Apr 2013 13:54:40 -0400
Subject: [PATCH 24/57] HHH-7995 Auto-discovery of Hibernate extension points
in OSGi
---
.../hibernate/internal/CoreMessageLogger.java | 4 ++
.../OSGI-INF/blueprint/blueprint.xml | 10 ++++
hibernate-osgi/hibernate-osgi.gradle | 4 +-
.../osgi/HibernateBundleActivator.java | 4 +-
.../osgi/OsgiPersistenceProvider.java | 60 +++++++++++++------
.../osgi/OsgiPersistenceProviderService.java | 9 ++-
.../osgi/OsgiSessionFactoryService.java | 16 ++++-
.../hibernate/osgi/util/OsgiServiceUtil.java | 53 ++++++++++++++++
8 files changed, 135 insertions(+), 25 deletions(-)
create mode 100644 hibernate-envers/src/main/resources/OSGI-INF/blueprint/blueprint.xml
create mode 100644 hibernate-osgi/src/main/java/org/hibernate/osgi/util/OsgiServiceUtil.java
diff --git a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java
index 955c5c0b04..20f6388fb2 100644
--- a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java
+++ b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java
@@ -1623,4 +1623,8 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Exception while loading a class or resource found during scanning", id = 449)
void unableToLoadScannedClassOrResource(@Cause Exception e);
+
+ @LogMessage(level = WARN)
+ @Message(value = "Exception while discovering OSGi service implementations : %s", id = 450)
+ void unableToDiscoverOsgiService(String service, @Cause Exception e);
}
diff --git a/hibernate-envers/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/hibernate-envers/src/main/resources/OSGI-INF/blueprint/blueprint.xml
new file mode 100644
index 0000000000..07c01bfc9f
--- /dev/null
+++ b/hibernate-envers/src/main/resources/OSGI-INF/blueprint/blueprint.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
diff --git a/hibernate-osgi/hibernate-osgi.gradle b/hibernate-osgi/hibernate-osgi.gradle
index 8a01360d3c..cefe0b6449 100644
--- a/hibernate-osgi/hibernate-osgi.gradle
+++ b/hibernate-osgi/hibernate-osgi.gradle
@@ -1,7 +1,9 @@
dependencies {
compile( project( ':hibernate-core' ) )
compile( project( ':hibernate-entitymanager' ) )
- compile( "org.osgi:org.osgi.core:4.3.0" )
+ // MUST use 4.3.1! 4.3.0 was compiled with "-target jsr14".
+ // http://blog.osgi.org/2012/10/43-companion-code-for-java-7.html
+ compile( "org.osgi:org.osgi.core:4.3.1" )
}
def pomName() {
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java
index c1f862fb98..8bd6824e48 100644
--- a/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java
@@ -78,10 +78,10 @@ public class HibernateBundleActivator implements BundleActivator {
// using the legacy provider name.
properties.put( "javax.persistence.provider", HibernatePersistenceProvider.class.getName() );
context.registerService( PersistenceProvider.class.getName(),
- new OsgiPersistenceProviderService( osgiClassLoader, osgiJtaPlatform ), properties );
+ new OsgiPersistenceProviderService( osgiClassLoader, osgiJtaPlatform, context ), properties );
context.registerService( SessionFactory.class.getName(),
- new OsgiSessionFactoryService( osgiClassLoader, osgiJtaPlatform ), new Hashtable());
+ new OsgiSessionFactoryService( osgiClassLoader, osgiJtaPlatform, context ), new Hashtable());
}
@Override
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java
index e90c2cbef4..885533f745 100644
--- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java
@@ -24,14 +24,20 @@
package org.hibernate.osgi;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceUnitInfo;
import org.hibernate.cfg.AvailableSettings;
+import org.hibernate.integrator.spi.Integrator;
import org.hibernate.jpa.HibernatePersistenceProvider;
+import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
+import org.hibernate.jpa.boot.spi.IntegratorProvider;
+import org.hibernate.osgi.util.OsgiServiceUtil;
import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleReference;
/**
@@ -43,45 +49,42 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider {
private OsgiClassLoader osgiClassLoader;
private OsgiJtaPlatform osgiJtaPlatform;
-
+
private Bundle requestingBundle;
-
- public OsgiPersistenceProvider (OsgiClassLoader osgiClassLoader,
- OsgiJtaPlatform osgiJtaPlatform,
- Bundle requestingBundle ) {
+
+ private BundleContext context;
+
+ public OsgiPersistenceProvider(OsgiClassLoader osgiClassLoader, OsgiJtaPlatform osgiJtaPlatform,
+ Bundle requestingBundle, BundleContext context) {
this.osgiClassLoader = osgiClassLoader;
this.osgiJtaPlatform = osgiJtaPlatform;
this.requestingBundle = requestingBundle;
+ this.context = context;
}
-
+
// TODO: Does "hibernate.classloaders" and osgiClassLoader need added to the
// EMFBuilder somehow?
@Override
public EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) {
- if ( properties == null ) {
- properties = new HashMap();
- }
- properties.put( AvailableSettings.JTA_PLATFORM, osgiJtaPlatform );
+ generateProperties( properties );
+
// TODO: This needs tested.
- properties.put( org.hibernate.jpa.AvailableSettings.SCANNER,
- new OsgiScanner( requestingBundle ) );
+ properties.put( org.hibernate.jpa.AvailableSettings.SCANNER, new OsgiScanner( requestingBundle ) );
// TODO: This is temporary -- for PersistenceXmlParser's use of
// ClassLoaderServiceImpl#fromConfigSettings
properties.put( AvailableSettings.ENVIRONMENT_CLASSLOADER, osgiClassLoader );
-
+
osgiClassLoader.addBundle( requestingBundle );
return super.createEntityManagerFactory( persistenceUnitName, properties );
}
-
+
@Override
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
- if ( properties == null ) {
- properties = new HashMap();
- }
- properties.put( AvailableSettings.JTA_PLATFORM, osgiJtaPlatform );
- // OSGi ClassLoaders must implement BundleReference
+ generateProperties( properties );
+
+ // OSGi ClassLoaders must implement BundleReference
properties.put( org.hibernate.jpa.AvailableSettings.SCANNER,
new OsgiScanner( ( (BundleReference) info.getClassLoader() ).getBundle() ) );
@@ -89,4 +92,23 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider {
return super.createContainerEntityManagerFactory( info, properties );
}
+
+ private void generateProperties(Map properties) {
+ if ( properties == null ) {
+ properties = new HashMap();
+ }
+
+ properties.put( AvailableSettings.JTA_PLATFORM, osgiJtaPlatform );
+
+ final List integrators = OsgiServiceUtil.getServiceImpls( Integrator.class, context );
+ IntegratorProvider integratorProvider = new IntegratorProvider() {
+ @Override
+ public List getIntegrators() {
+ return integrators;
+ }
+ };
+ properties.put( EntityManagerFactoryBuilderImpl.INTEGRATOR_PROVIDER, integratorProvider );
+
+ // TODO: other types of services?
+ }
}
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java
index bb9008c33b..5ab228568f 100644
--- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java
@@ -21,6 +21,7 @@
package org.hibernate.osgi;
import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
@@ -37,14 +38,18 @@ public class OsgiPersistenceProviderService implements ServiceFactory {
private OsgiJtaPlatform osgiJtaPlatform;
- public OsgiPersistenceProviderService( OsgiClassLoader osgiClassLoader, OsgiJtaPlatform osgiJtaPlatform ) {
+ private BundleContext context;
+
+ public OsgiPersistenceProviderService( OsgiClassLoader osgiClassLoader,
+ OsgiJtaPlatform osgiJtaPlatform, BundleContext context ) {
this.osgiClassLoader = osgiClassLoader;
this.osgiJtaPlatform = osgiJtaPlatform;
+ this.context = context;
}
@Override
public Object getService(Bundle requestingBundle, ServiceRegistration registration) {
- return new OsgiPersistenceProvider(osgiClassLoader, osgiJtaPlatform, requestingBundle);
+ return new OsgiPersistenceProvider(osgiClassLoader, osgiJtaPlatform, requestingBundle, context);
}
@Override
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java
index db5b75b4cf..8770e55231 100644
--- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java
@@ -20,13 +20,18 @@
*/
package org.hibernate.osgi;
+import java.util.List;
+
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
+import org.hibernate.integrator.spi.Integrator;
+import org.hibernate.osgi.util.OsgiServiceUtil;
import org.hibernate.service.ServiceRegistry;
import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
@@ -54,9 +59,13 @@ public class OsgiSessionFactoryService implements ServiceFactory {
private OsgiJtaPlatform osgiJtaPlatform;
- public OsgiSessionFactoryService( OsgiClassLoader osgiClassLoader, OsgiJtaPlatform osgiJtaPlatform ) {
+ private BundleContext context;
+
+ public OsgiSessionFactoryService( OsgiClassLoader osgiClassLoader, OsgiJtaPlatform osgiJtaPlatform,
+ BundleContext context ) {
this.osgiClassLoader = osgiClassLoader;
this.osgiJtaPlatform = osgiJtaPlatform;
+ this.context = context;
}
@Override
@@ -70,6 +79,11 @@ public class OsgiSessionFactoryService implements ServiceFactory {
BootstrapServiceRegistryBuilder builder = new BootstrapServiceRegistryBuilder();
builder.with( osgiClassLoader );
+ List integrators = OsgiServiceUtil.getServiceImpls( Integrator.class, context );
+ for (Integrator integrator : integrators) {
+ builder.with( integrator );
+ }
+
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder( builder.build() )
.applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/util/OsgiServiceUtil.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/util/OsgiServiceUtil.java
new file mode 100644
index 0000000000..0b9ddc0ed4
--- /dev/null
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/util/OsgiServiceUtil.java
@@ -0,0 +1,53 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * JBoss, Home of Professional Open Source
+ * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors
+ * as indicated by the @authors tag. All rights reserved.
+ * See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This copyrighted material is made available to anyone wishing to use,
+ * modify, copy, or redistribute it subject to the terms and conditions
+ * of the GNU Lesser General Public License, v. 2.1.
+ * This program is distributed in the hope that it will be useful, but WITHOUT A
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+ * You should have received a copy of the GNU Lesser General Public License,
+ * v.2.1 along with this distribution; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ * MA 02110-1301, USA.
+ */
+package org.hibernate.osgi.util;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import org.hibernate.internal.CoreMessageLogger;
+import org.jboss.logging.Logger;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+
+/**
+ * @author Brett Meyer
+ */
+public class OsgiServiceUtil {
+
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class,
+ OsgiServiceUtil.class.getName() );
+
+ public static List getServiceImpls(Class contract, BundleContext context) {
+ List serviceImpls = new ArrayList();
+ try {
+ Collection> serviceRefs = context.getServiceReferences( contract, null );
+ for ( ServiceReference serviceRef : serviceRefs ) {
+ serviceImpls.add( context.getService( serviceRef ) );
+ }
+ }
+ catch ( Exception e ) {
+ LOG.unableToDiscoverOsgiService( contract.getName(), e );
+ }
+ return serviceImpls;
+ }
+}
From 0edd7b75b82b6038dfc3234ef3e3e4cde4a4acc9 Mon Sep 17 00:00:00 2001
From: Brett Meyer
Date: Mon, 29 Apr 2013 11:50:11 -0400
Subject: [PATCH 25/57] HHH-7943 C3P0 and Proxool OSGi support
---
.../OSGI-INF/blueprint/blueprint.xml | 10 +++
.../EntityManagerFactoryBuilderImpl.java | 64 +++++++++++--------
.../spi/StrategyRegistrationProviderList.java | 37 +++++++++++
.../osgi/OsgiPersistenceProvider.java | 21 ++++--
.../osgi/OsgiSessionFactoryService.java | 7 ++
.../OSGI-INF/blueprint/blueprint.xml | 10 +++
6 files changed, 120 insertions(+), 29 deletions(-)
create mode 100644 hibernate-c3p0/src/main/resources/OSGI-INF/blueprint/blueprint.xml
create mode 100644 hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/StrategyRegistrationProviderList.java
create mode 100644 hibernate-proxool/src/main/resources/OSGI-INF/blueprint/blueprint.xml
diff --git a/hibernate-c3p0/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/hibernate-c3p0/src/main/resources/OSGI-INF/blueprint/blueprint.xml
new file mode 100644
index 0000000000..3ade79977f
--- /dev/null
+++ b/hibernate-c3p0/src/main/resources/OSGI-INF/blueprint/blueprint.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java
index 383dfd81f3..433aa11465 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java
@@ -23,12 +23,6 @@
*/
package org.hibernate.jpa.boot.internal;
-import javax.persistence.AttributeConverter;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.EntityNotFoundException;
-import javax.persistence.PersistenceException;
-import javax.persistence.spi.PersistenceUnitTransactionType;
-import javax.sql.DataSource;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
@@ -47,14 +41,12 @@ import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
-import org.jboss.jandex.AnnotationInstance;
-import org.jboss.jandex.ClassInfo;
-import org.jboss.jandex.DotName;
-import org.jboss.jandex.Index;
-import org.jboss.jandex.IndexView;
-import org.jboss.jandex.Indexer;
-
-import org.jboss.logging.Logger;
+import javax.persistence.AttributeConverter;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityNotFoundException;
+import javax.persistence.PersistenceException;
+import javax.persistence.spi.PersistenceUnitTransactionType;
+import javax.sql.DataSource;
import org.hibernate.Interceptor;
import org.hibernate.InvalidMappingException;
@@ -67,6 +59,7 @@ import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
+import org.hibernate.boot.registry.selector.StrategyRegistrationProvider;
import org.hibernate.boot.registry.selector.spi.StrategySelector;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
@@ -81,25 +74,26 @@ import org.hibernate.internal.jaxb.cfg.JaxbHibernateConfiguration;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.ValueHolder;
import org.hibernate.jpa.AvailableSettings;
+import org.hibernate.jpa.boot.scan.internal.StandardScanOptions;
+import org.hibernate.jpa.boot.scan.internal.StandardScanner;
+import org.hibernate.jpa.boot.scan.spi.ScanOptions;
+import org.hibernate.jpa.boot.scan.spi.ScanResult;
+import org.hibernate.jpa.boot.scan.spi.Scanner;
+import org.hibernate.jpa.boot.spi.ClassDescriptor;
import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder;
+import org.hibernate.jpa.boot.spi.InputStreamAccess;
import org.hibernate.jpa.boot.spi.IntegratorProvider;
+import org.hibernate.jpa.boot.spi.MappingFileDescriptor;
+import org.hibernate.jpa.boot.spi.NamedInputStream;
+import org.hibernate.jpa.boot.spi.PackageDescriptor;
import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
+import org.hibernate.jpa.boot.spi.StrategyRegistrationProviderList;
import org.hibernate.jpa.event.spi.JpaIntegrator;
import org.hibernate.jpa.internal.EntityManagerFactoryImpl;
import org.hibernate.jpa.internal.EntityManagerMessageLogger;
import org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator;
import org.hibernate.jpa.internal.util.LogHelper;
import org.hibernate.jpa.internal.util.PersistenceUnitTransactionTypeHelper;
-import org.hibernate.jpa.boot.scan.internal.StandardScanOptions;
-import org.hibernate.jpa.boot.scan.internal.StandardScanner;
-import org.hibernate.jpa.boot.spi.ClassDescriptor;
-import org.hibernate.jpa.boot.spi.InputStreamAccess;
-import org.hibernate.jpa.boot.spi.MappingFileDescriptor;
-import org.hibernate.jpa.boot.spi.NamedInputStream;
-import org.hibernate.jpa.boot.spi.PackageDescriptor;
-import org.hibernate.jpa.boot.scan.spi.ScanOptions;
-import org.hibernate.jpa.boot.scan.spi.ScanResult;
-import org.hibernate.jpa.boot.scan.spi.Scanner;
import org.hibernate.jpa.spi.IdentifierGeneratorStrategyProvider;
import org.hibernate.metamodel.source.annotations.JPADotNames;
import org.hibernate.metamodel.source.annotations.JandexHelper;
@@ -109,6 +103,13 @@ import org.hibernate.secure.spi.JaccService;
import org.hibernate.service.ConfigLoader;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.spi.ServiceRegistryImplementor;
+import org.jboss.jandex.AnnotationInstance;
+import org.jboss.jandex.ClassInfo;
+import org.jboss.jandex.DotName;
+import org.jboss.jandex.Index;
+import org.jboss.jandex.IndexView;
+import org.jboss.jandex.Indexer;
+import org.jboss.logging.Logger;
/**
* @author Steve Ebersole
@@ -129,6 +130,11 @@ public class EntityManagerFactoryBuilderImpl implements EntityManagerFactoryBuil
* Names a {@link IntegratorProvider}
*/
public static final String INTEGRATOR_PROVIDER = "hibernate.integrator_provider";
+
+ /**
+ * Names a {@link StrategyRegistrationProviderList}
+ */
+ public static final String STRATEGY_REGISTRATION_PROVIDERS = "hibernate.strategy_registration_provider";
/**
* Names a Jandex {@link Index} instance to use.
@@ -471,11 +477,19 @@ public class EntityManagerFactoryBuilderImpl implements EntityManagerFactoryBuil
final IntegratorProvider integratorProvider = (IntegratorProvider) integrationSettings.get( INTEGRATOR_PROVIDER );
if ( integratorProvider != null ) {
- integrationSettings.remove( INTEGRATOR_PROVIDER );
for ( Integrator integrator : integratorProvider.getIntegrators() ) {
bootstrapServiceRegistryBuilder.with( integrator );
}
}
+
+ final StrategyRegistrationProviderList strategyRegistrationProviderList
+ = (StrategyRegistrationProviderList) integrationSettings.get( STRATEGY_REGISTRATION_PROVIDERS );
+ if ( strategyRegistrationProviderList != null ) {
+ for ( StrategyRegistrationProvider strategyRegistrationProvider : strategyRegistrationProviderList
+ .getStrategyRegistrationProviders() ) {
+ bootstrapServiceRegistryBuilder.withStrategySelectors( strategyRegistrationProvider );
+ }
+ }
// TODO: If providedClassLoader is present (OSGi, etc.) *and*
// an APP_CLASSLOADER is provided, should throw an exception or
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/StrategyRegistrationProviderList.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/StrategyRegistrationProviderList.java
new file mode 100644
index 0000000000..24ad604705
--- /dev/null
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/StrategyRegistrationProviderList.java
@@ -0,0 +1,37 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2012, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.jpa.boot.spi;
+
+import java.util.List;
+
+import org.hibernate.boot.registry.selector.StrategyRegistrationProvider;
+
+/**
+ * @author Brett Meyer
+ *
+ * TODO: Not a fan of this name or entry point into EMFBuilderImpl
+ */
+public interface StrategyRegistrationProviderList {
+ public List getStrategyRegistrationProviders();
+}
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java
index 885533f745..01ccff48ee 100644
--- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java
@@ -30,11 +30,13 @@ import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceUnitInfo;
+import org.hibernate.boot.registry.selector.StrategyRegistrationProvider;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.integrator.spi.Integrator;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
import org.hibernate.jpa.boot.spi.IntegratorProvider;
+import org.hibernate.jpa.boot.spi.StrategyRegistrationProviderList;
import org.hibernate.osgi.util.OsgiServiceUtil;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
@@ -67,7 +69,7 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider {
@Override
public EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) {
- generateProperties( properties );
+ properties = generateProperties( properties );
// TODO: This needs tested.
properties.put( org.hibernate.jpa.AvailableSettings.SCANNER, new OsgiScanner( requestingBundle ) );
@@ -82,7 +84,7 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider {
@Override
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
- generateProperties( properties );
+ properties = generateProperties( properties );
// OSGi ClassLoaders must implement BundleReference
properties.put( org.hibernate.jpa.AvailableSettings.SCANNER,
@@ -93,7 +95,7 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider {
return super.createContainerEntityManagerFactory( info, properties );
}
- private void generateProperties(Map properties) {
+ private Map generateProperties(Map properties) {
if ( properties == null ) {
properties = new HashMap();
}
@@ -109,6 +111,17 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider {
};
properties.put( EntityManagerFactoryBuilderImpl.INTEGRATOR_PROVIDER, integratorProvider );
- // TODO: other types of services?
+ final List strategyRegistrationProviders = OsgiServiceUtil.getServiceImpls(
+ StrategyRegistrationProvider.class, context );
+ StrategyRegistrationProviderList strategyRegistrationProviderList = new StrategyRegistrationProviderList() {
+ @Override
+ public List getStrategyRegistrationProviders() {
+ return strategyRegistrationProviders;
+ }
+ };
+ properties.put( EntityManagerFactoryBuilderImpl.STRATEGY_REGISTRATION_PROVIDERS,
+ strategyRegistrationProviderList );
+
+ return properties;
}
}
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java
index 8770e55231..c878136711 100644
--- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java
@@ -25,6 +25,7 @@ import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
+import org.hibernate.boot.registry.selector.StrategyRegistrationProvider;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.integrator.spi.Integrator;
@@ -84,6 +85,12 @@ public class OsgiSessionFactoryService implements ServiceFactory {
builder.with( integrator );
}
+ List strategyRegistrationProviders
+ = OsgiServiceUtil.getServiceImpls( StrategyRegistrationProvider.class, context );
+ for (StrategyRegistrationProvider strategyRegistrationProvider : strategyRegistrationProviders) {
+ builder.withStrategySelectors( strategyRegistrationProvider );
+ }
+
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder( builder.build() )
.applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);
diff --git a/hibernate-proxool/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/hibernate-proxool/src/main/resources/OSGI-INF/blueprint/blueprint.xml
new file mode 100644
index 0000000000..b0e0c5c44d
--- /dev/null
+++ b/hibernate-proxool/src/main/resources/OSGI-INF/blueprint/blueprint.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
From 3b8320da7e5b1282e1cad2e90830e2756885b8d8 Mon Sep 17 00:00:00 2001
From: Steve Ebersole
Date: Mon, 29 Apr 2013 18:52:08 -0500
Subject: [PATCH 26/57] HHH-8159 - Apply fixups indicated by analysis tools
---
.../dialect/function/TemplateRenderer.java | 7 ++-
.../hibernate/engine/OptimisticLockStyle.java | 9 +++
.../config/spi/ConfigurationService.java | 55 +++++++++++++++++++
.../hibernate/engine/internal/Cascade.java | 2 +-
.../engine/internal/EntityEntryContext.java | 2 +
.../engine/internal/ForeignKeys.java | 2 +
.../hibernate/engine/internal/JoinHelper.java | 40 +++++++++++---
.../internal/NaturalIdXrefDelegate.java | 2 +-
.../engine/internal/Nullability.java | 2 +-
.../engine/internal/ParameterBinder.java | 2 +-
.../internal/StatefulPersistenceContext.java | 2 +-
.../engine/internal/TwoPhaseLoad.java | 2 +-
.../engine/internal/UnsavedValueFactory.java | 2 +-
.../org/hibernate/engine/jdbc/BlobProxy.java | 25 +++------
.../engine/jdbc/CharacterStream.java | 1 -
.../org/hibernate/engine/jdbc/ClobProxy.java | 27 +++------
.../engine/jdbc/ColumnNameCache.java | 33 ++++++++---
.../engine/jdbc/ContextualLobCreator.java | 28 +++++++---
.../engine/jdbc/LobCreationContext.java | 7 ++-
.../engine/jdbc/NClobImplementer.java | 1 -
.../org/hibernate/engine/jdbc/NClobProxy.java | 18 ++----
.../engine/jdbc/NonContextualLobCreator.java | 3 +
.../engine/jdbc/ReaderInputStream.java | 11 +++-
.../engine/jdbc/ResultSetWrapperProxy.java | 36 ++++++------
.../engine/jdbc/SerializableBlobProxy.java | 13 +++--
.../engine/jdbc/SerializableClobProxy.java | 13 +++--
.../engine/jdbc/SerializableNClobProxy.java | 16 ++++--
.../hibernate/engine/jdbc/StreamUtils.java | 52 +++++++++++++++++-
.../hibernate/engine/jdbc/WrappedNClob.java | 12 ++++
.../batch/internal/AbstractBatchImpl.java | 9 ++-
.../jdbc/batch/internal/BasicBatchKey.java | 23 +++-----
.../jdbc/batch/internal/BatchBuilderImpl.java | 27 ++++++---
.../batch/internal/BatchBuilderInitiator.java | 7 +++
.../jdbc/batch/internal/BatchingBatch.java | 17 ++++--
.../jdbc/batch/internal/NonBatchingBatch.java | 6 +-
.../jdbc/batch/internal/package-info.java | 4 ++
.../engine/jdbc/batch/spi/package-info.java | 4 ++
.../internal/ConnectionProviderInitiator.java | 45 ++++++++++-----
.../DatasourceConnectionProviderImpl.java | 19 ++-----
.../DriverManagerConnectionProviderImpl.java | 45 ++++++++++-----
...ultiTenantConnectionProviderInitiator.java | 9 ++-
.../UserSuppliedConnectionProviderImpl.java | 12 +---
.../connections/internal/package-info.java | 4 ++
.../connections/spi/ConnectionProvider.java | 5 +-
...asedMultiTenantConnectionProviderImpl.java | 7 ++-
.../spi/MultiTenantConnectionProvider.java | 3 +
.../jdbc/connections/spi/package-info.java | 4 ++
.../hibernate/engine/jdbc/package-info.java | 4 ++
shared/config/checkstyle/checkstyle.xml | 3 +
49 files changed, 473 insertions(+), 209 deletions(-)
create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/package-info.java
create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/spi/package-info.java
create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/package-info.java
create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/package-info.java
create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/package-info.java
diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java
index f8a64137c3..b9c7ba7129 100644
--- a/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java
+++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java
@@ -59,7 +59,9 @@ public class TemplateRenderer {
final StringBuilder chunk = new StringBuilder( 10 );
final StringBuilder index = new StringBuilder( 2 );
- for ( int i = 0; i < template.length(); ++i ) {
+ int i = 0;
+ final int len = template.length();
+ while ( i < len ) {
char c = template.charAt( i );
if ( c == '?' ) {
chunkList.add( chunk.toString() );
@@ -82,6 +84,7 @@ public class TemplateRenderer {
else {
chunk.append( c );
}
+ i++;
}
if ( chunk.length() > 0 ) {
@@ -90,7 +93,7 @@ public class TemplateRenderer {
chunks = chunkList.toArray( new String[chunkList.size()] );
paramIndexes = new int[paramList.size()];
- for ( int i = 0; i < paramIndexes.length; ++i ) {
+ for ( i = 0; i < paramIndexes.length; ++i ) {
paramIndexes[i] = paramList.get( i );
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java b/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java
index b0211d708f..510ec68aa7 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java
@@ -56,6 +56,15 @@ public enum OptimisticLockStyle {
return oldCode;
}
+ /**
+ * Given an old code (one of the int constants from Cascade), interpret it as one of the new enums.
+ *
+ * @param oldCode The old int constant code
+ *
+ * @return The interpreted enum value
+ *
+ * @throws IllegalArgumentException If the code did not match any legacy constant.
+ */
public static OptimisticLockStyle interpretOldCode(int oldCode) {
switch ( oldCode ) {
case -1: {
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/config/spi/ConfigurationService.java b/hibernate-core/src/main/java/org/hibernate/engine/config/spi/ConfigurationService.java
index de5a4fb955..98a42ede4f 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/config/spi/ConfigurationService.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/config/spi/ConfigurationService.java
@@ -33,10 +33,47 @@ import org.hibernate.service.Service;
* @author Steve Ebersole
*/
public interface ConfigurationService extends Service {
+ /**
+ * Access to the complete map of config settings. The returned map is immutable
+ *
+ * @return The immutable map of config settings.
+ */
public Map getSettings();
+ /**
+ * Get the named setting, using the specified converter.
+ *
+ * @param name The name of the setting to get.
+ * @param converter The converter to apply
+ * @param The Java type of the conversion
+ *
+ * @return The converted (typed) setting. May return {@code null} (see {@link #getSetting(String, Class, Object)})
+ */
public T getSetting(String name, Converter converter);
+
+ /**
+ * Get the named setting, using the specified converter and default value.
+ *
+ * @param name The name of the setting to get.
+ * @param converter The converter to apply
+ * @param defaultValue If no setting with that name is found, return this default value as the result.
+ * @param The Java type of the conversion
+ *
+ * @return The converted (typed) setting. Will be the defaultValue if no such setting was defined.
+ */
public T getSetting(String name, Converter converter, T defaultValue);
+
+ /**
+ * Get the named setting. Differs from the form taking a Converter in that here we expect to have a simple
+ * cast rather than any involved conversion.
+ *
+ * @param name The name of the setting to get.
+ * @param expected The expected Java type.
+ * @param defaultValue If no setting with that name is found, return this default value as the result.
+ * @param The Java type of the conversion
+ *
+ * @return The converted (typed) setting. Will be the defaultValue if no such setting was defined.
+ */
public T getSetting(String name, Class expected, T defaultValue);
/**
@@ -44,10 +81,28 @@ public interface ConfigurationService extends Service {
*
* @param expected The type of instance expected to return.
* @param candidate The candidate object to be casted.
+ * @param The java type of the expected return
+ *
* @return The instance of expected type or null if this cast fail.
+ *
+ * @deprecated No idea why this is exposed here...
*/
+ @Deprecated
public T cast(Class expected, Object candidate);
+
+ /**
+ * Simple conversion contract for converting an untyped object to a specified type.
+ *
+ * @param The Java type of the converted value
+ */
public static interface Converter {
+ /**
+ * Convert an untyped Object reference to the Converter's type.
+ *
+ * @param value The untyped value
+ *
+ * @return The converted (typed) value.
+ */
public T convert(Object value);
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/Cascade.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/Cascade.java
index 943e0a9db5..2ba334a022 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/internal/Cascade.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/Cascade.java
@@ -258,7 +258,7 @@ public final class Cascade {
final Object[] children = componentType.getPropertyValues( child, eventSource );
final Type[] types = componentType.getSubtypes();
for ( int i=0; i getLength() ) {
throw new SQLException( "Start position [" + start + "] cannot exceed overall CLOB length [" + getLength() + "]" );
}
- int length = (Integer) args[1];
+ final int length = (Integer) args[1];
if ( length < 0 ) {
// java docs specifically say for getBinaryStream(long,int) that the start+length must not exceed the
// total length, however that is at odds with the getBytes(long,int) behavior.
@@ -131,11 +130,11 @@ public class BlobProxy implements InvocationHandler {
}
if ( "getBytes".equals( methodName ) ) {
if ( argCount == 2 ) {
- long start = (Long) args[0];
+ final long start = (Long) args[0];
if ( start < 1 ) {
throw new SQLException( "Start position 1-based; must be 1 or more." );
}
- int length = (Integer) args[1];
+ final int length = (Integer) args[1];
if ( length < 0 ) {
throw new SQLException( "Length must be great-than-or-equal to zero." );
}
@@ -167,11 +166,7 @@ public class BlobProxy implements InvocationHandler {
* @return The generated proxy.
*/
public static Blob generateProxy(byte[] bytes) {
- return ( Blob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new BlobProxy( bytes )
- );
+ return (Blob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new BlobProxy( bytes ) );
}
/**
@@ -183,11 +178,7 @@ public class BlobProxy implements InvocationHandler {
* @return The generated proxy.
*/
public static Blob generateProxy(InputStream stream, long length) {
- return ( Blob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new BlobProxy( stream, length )
- );
+ return (Blob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new BlobProxy( stream, length ) );
}
/**
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/CharacterStream.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/CharacterStream.java
index f90d6c3356..f63c6757f1 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/CharacterStream.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/CharacterStream.java
@@ -23,7 +23,6 @@
*/
package org.hibernate.engine.jdbc;
-import java.io.InputStream;
import java.io.Reader;
/**
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ClobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ClobProxy.java
index f45489f2d9..5faf45cbb5 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ClobProxy.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ClobProxy.java
@@ -26,7 +26,6 @@ package org.hibernate.engine.jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
-import java.io.StringReader;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
@@ -49,7 +48,7 @@ public class ClobProxy implements InvocationHandler {
private static final Class[] PROXY_INTERFACES = new Class[] { Clob.class, ClobImplementer.class };
private final CharacterStream characterStream;
- private boolean needsReset = false;
+ private boolean needsReset;
/**
* Constructor used to build {@link Clob} from string data.
@@ -89,8 +88,8 @@ public class ClobProxy implements InvocationHandler {
protected String getSubString(long start, int length) {
final String string = characterStream.asString();
// semi-naive implementation
- int endIndex = Math.min( ((int)start)+length, string.length() );
- return string.substring( (int)start, endIndex );
+ final int endIndex = Math.min( ( (int) start ) + length, string.length() );
+ return string.substring( (int) start, endIndex );
}
/**
@@ -119,14 +118,14 @@ public class ClobProxy implements InvocationHandler {
return getCharacterStream();
}
else if ( argCount == 2 ) {
- long start = (Long) args[0];
+ final long start = (Long) args[0];
if ( start < 1 ) {
throw new SQLException( "Start position 1-based; must be 1 or more." );
}
if ( start > getLength() ) {
throw new SQLException( "Start position [" + start + "] cannot exceed overall CLOB length [" + getLength() + "]" );
}
- int length = (Integer) args[1];
+ final int length = (Integer) args[1];
if ( length < 0 ) {
// java docs specifically say for getCharacterStream(long,int) that the start+length must not exceed the
// total length, however that is at odds with the getSubString(long,int) behavior.
@@ -136,14 +135,14 @@ public class ClobProxy implements InvocationHandler {
}
}
if ( "getSubString".equals( methodName ) && argCount == 2 ) {
- long start = (Long) args[0];
+ final long start = (Long) args[0];
if ( start < 1 ) {
throw new SQLException( "Start position 1-based; must be 1 or more." );
}
if ( start > getLength() ) {
throw new SQLException( "Start position [" + start + "] cannot exceed overall CLOB length [" + getLength() + "]" );
}
- int length = (Integer) args[1];
+ final int length = (Integer) args[1];
if ( length < 0 ) {
throw new SQLException( "Length must be great-than-or-equal to zero." );
}
@@ -186,11 +185,7 @@ public class ClobProxy implements InvocationHandler {
* @return The generated proxy.
*/
public static Clob generateProxy(String string) {
- return ( Clob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new ClobProxy( string )
- );
+ return (Clob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new ClobProxy( string ) );
}
/**
@@ -202,11 +197,7 @@ public class ClobProxy implements InvocationHandler {
* @return The generated proxy.
*/
public static Clob generateProxy(Reader reader, long length) {
- return ( Clob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new ClobProxy( reader, length )
- );
+ return (Clob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new ClobProxy( reader, length ) );
}
/**
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ColumnNameCache.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ColumnNameCache.java
index 934e2c6c55..c1b006958c 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ColumnNameCache.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ColumnNameCache.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
- * distributed under license by Red Hat Middleware LLC.
+ * distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.engine.jdbc;
+
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
@@ -33,24 +34,42 @@ import java.util.concurrent.ConcurrentHashMap;
* @author Steve Ebersole
*/
public class ColumnNameCache {
- public static final float LOAD_FACTOR = .75f;
+ private static final float LOAD_FACTOR = .75f;
private final Map columnNameToIndexCache;
+ /**
+ * Constructs a ColumnNameCache
+ *
+ * @param columnCount The number of columns to be cached.
+ */
public ColumnNameCache(int columnCount) {
// should *not* need to grow beyond the size of the total number of columns in the rs
- this.columnNameToIndexCache = new ConcurrentHashMap( columnCount + (int)( columnCount * LOAD_FACTOR ) + 1, LOAD_FACTOR );
+ this.columnNameToIndexCache = new ConcurrentHashMap(
+ columnCount + (int)( columnCount * LOAD_FACTOR ) + 1,
+ LOAD_FACTOR
+ );
}
+ /**
+ * Resolve the column name/alias to its index
+ *
+ * @param columnName The name/alias of the column
+ * @param rs The ResultSet
+ *
+ * @return The index
+ *
+ * @throws SQLException INdicates a problems accessing the underlying JDBC ResultSet
+ */
public int getIndexForColumnName(String columnName, ResultSet rs) throws SQLException {
- Integer cached = columnNameToIndexCache.get( columnName );
+ final Integer cached = columnNameToIndexCache.get( columnName );
if ( cached != null ) {
return cached;
}
else {
- int index = rs.findColumn( columnName );
+ final int index = rs.findColumn( columnName );
columnNameToIndexCache.put( columnName, index);
return index;
}
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ContextualLobCreator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ContextualLobCreator.java
index 3ed10eae56..14859aed60 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ContextualLobCreator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ContextualLobCreator.java
@@ -22,18 +22,15 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.engine.jdbc;
-import java.io.IOException;
+
import java.io.InputStream;
-import java.io.OutputStream;
import java.io.Reader;
-import java.io.Writer;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.NClob;
import java.sql.SQLException;
-import org.hibernate.HibernateException;
import org.hibernate.JDBCException;
/**
@@ -46,6 +43,11 @@ import org.hibernate.JDBCException;
public class ContextualLobCreator extends AbstractLobCreator implements LobCreator {
private LobCreationContext lobCreationContext;
+ /**
+ * Constructs a ContextualLobCreator
+ *
+ * @param lobCreationContext The context for performing LOB creation
+ */
public ContextualLobCreator(LobCreationContext lobCreationContext) {
this.lobCreationContext = lobCreationContext;
}
@@ -62,7 +64,7 @@ public class ContextualLobCreator extends AbstractLobCreator implements LobCreat
@Override
public Blob createBlob(byte[] bytes) {
try {
- Blob blob = createBlob();
+ final Blob blob = createBlob();
blob.setBytes( 1, bytes );
return blob;
}
@@ -90,7 +92,7 @@ public class ContextualLobCreator extends AbstractLobCreator implements LobCreat
@Override
public Clob createClob(String string) {
try {
- Clob clob = createClob();
+ final Clob clob = createClob();
clob.setString( 1, string );
return clob;
}
@@ -118,7 +120,7 @@ public class ContextualLobCreator extends AbstractLobCreator implements LobCreat
@Override
public NClob createNClob(String string) {
try {
- NClob nclob = createNClob();
+ final NClob nclob = createNClob();
nclob.setString( 1, string );
return nclob;
}
@@ -134,19 +136,31 @@ public class ContextualLobCreator extends AbstractLobCreator implements LobCreat
return NonContextualLobCreator.INSTANCE.createNClob( reader, length );
}
+ /**
+ * Callback for performing contextual BLOB creation
+ */
public static final LobCreationContext.Callback CREATE_BLOB_CALLBACK = new LobCreationContext.Callback() {
+ @Override
public Blob executeOnConnection(Connection connection) throws SQLException {
return connection.createBlob();
}
};
+ /**
+ * Callback for performing contextual CLOB creation
+ */
public static final LobCreationContext.Callback CREATE_CLOB_CALLBACK = new LobCreationContext.Callback() {
+ @Override
public Clob executeOnConnection(Connection connection) throws SQLException {
return connection.createClob();
}
};
+ /**
+ * Callback for performing contextual NCLOB creation
+ */
public static final LobCreationContext.Callback CREATE_NCLOB_CALLBACK = new LobCreationContext.Callback() {
+ @Override
public NClob executeOnConnection(Connection connection) throws SQLException {
return connection.createNClob();
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/LobCreationContext.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/LobCreationContext.java
index 42a764e7b8..1276676eba 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/LobCreationContext.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/LobCreationContext.java
@@ -39,8 +39,10 @@ public interface LobCreationContext {
* Perform whatever actions are necessary using the provided JDBC {@link Connection}.
*
* @param connection The JDBC {@link Connection}.
+ *
* @return The created LOB.
- * @throws SQLException
+ *
+ * @throws SQLException Indicates trouble accessing the JDBC driver to create the LOB
*/
public T executeOnConnection(Connection connection) throws SQLException;
}
@@ -49,6 +51,9 @@ public interface LobCreationContext {
* Execute the given callback, making sure it has access to a viable JDBC {@link Connection}.
*
* @param callback The callback to execute .
+ * @param The Java type of the type of LOB being created. One of {@link java.sql.Blob},
+ * {@link java.sql.Clob}, {@link java.sql.NClob}
+ *
* @return The LOB created by the callback.
*/
public T execute(Callback callback);
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobImplementer.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobImplementer.java
index f7de45cda4..9676ea2778 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobImplementer.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobImplementer.java
@@ -23,7 +23,6 @@
*/
package org.hibernate.engine.jdbc;
-
/**
* Marker interface for non-contextually created java.sql.NClob instances..
*
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobProxy.java
index 4f9227891d..5f44978694 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobProxy.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobProxy.java
@@ -25,7 +25,6 @@ package org.hibernate.engine.jdbc;
import java.io.Reader;
import java.lang.reflect.Proxy;
-import java.sql.Clob;
import java.sql.NClob;
import org.hibernate.internal.util.ClassLoaderHelper;
@@ -40,6 +39,9 @@ import org.hibernate.internal.util.ClassLoaderHelper;
* @author Steve Ebersole
*/
public class NClobProxy extends ClobProxy {
+ /**
+ * The interfaces used to generate the proxy
+ */
public static final Class[] PROXY_INTERFACES = new Class[] { NClob.class, NClobImplementer.class };
protected NClobProxy(String string) {
@@ -58,15 +60,11 @@ public class NClobProxy extends ClobProxy {
* @return The generated proxy.
*/
public static NClob generateProxy(String string) {
- return ( NClob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new ClobProxy( string )
- );
+ return (NClob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new ClobProxy( string ) );
}
/**
- * Generates a {@link Clob} proxy using a character reader of given length.
+ * Generates a {@link java.sql.NClob} proxy using a character reader of given length.
*
* @param reader The character reader
* @param length The length of the character reader
@@ -74,11 +72,7 @@ public class NClobProxy extends ClobProxy {
* @return The generated proxy.
*/
public static NClob generateProxy(Reader reader, long length) {
- return ( NClob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new ClobProxy( reader, length )
- );
+ return (NClob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new ClobProxy( reader, length ) );
}
/**
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NonContextualLobCreator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NonContextualLobCreator.java
index 93b5ec9db0..886e2493f5 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NonContextualLobCreator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NonContextualLobCreator.java
@@ -37,6 +37,9 @@ import java.sql.NClob;
* @author Gail Badner
*/
public class NonContextualLobCreator extends AbstractLobCreator implements LobCreator {
+ /**
+ * Singleton access
+ */
public static final NonContextualLobCreator INSTANCE = new NonContextualLobCreator();
private NonContextualLobCreator() {
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ReaderInputStream.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ReaderInputStream.java
index 4c2fb9e248..9c6aa52573 100755
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ReaderInputStream.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ReaderInputStream.java
@@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.engine.jdbc;
+
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
@@ -33,11 +34,17 @@ import java.io.Reader;
*/
public class ReaderInputStream extends InputStream {
private Reader reader;
-
+
+ /**
+ * Constructs a ReaderInputStream from a Reader
+ *
+ * @param reader The reader to expose as an InputStream
+ */
public ReaderInputStream(Reader reader) {
this.reader = reader;
}
-
+
+ @Override
public int read() throws IOException {
return reader.read();
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java
index 4b0b21ea3f..addfd6210f 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java
@@ -44,10 +44,12 @@ import org.hibernate.internal.util.ClassLoaderHelper;
* @author Gail Badner
*/
public class ResultSetWrapperProxy implements InvocationHandler {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, ResultSetWrapperProxy.class.getName());
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ ResultSetWrapperProxy.class.getName()
+ );
private static final Class[] PROXY_INTERFACES = new Class[] { ResultSet.class };
- private static final SqlExceptionHelper sqlExceptionHelper = new SqlExceptionHelper();
+ private static final SqlExceptionHelper SQL_EXCEPTION_HELPER = new SqlExceptionHelper();
private final ResultSet rs;
private final ColumnNameCache columnNameCache;
@@ -65,7 +67,7 @@ public class ResultSetWrapperProxy implements InvocationHandler {
* @return The generated proxy.
*/
public static ResultSet generateProxy(ResultSet resultSet, ColumnNameCache columnNameCache) {
- return ( ResultSet ) Proxy.newProxyInstance(
+ return (ResultSet) Proxy.newProxyInstance(
getProxyClassLoader(),
PROXY_INTERFACES,
new ResultSetWrapperProxy( resultSet, columnNameCache )
@@ -90,26 +92,22 @@ public class ResultSetWrapperProxy implements InvocationHandler {
@SuppressWarnings( {"UnnecessaryBoxing"})
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ( "findColumn".equals( method.getName() ) ) {
- return Integer.valueOf( findColumn( ( String ) args[0] ) );
+ return Integer.valueOf( findColumn( (String) args[0] ) );
}
if ( isFirstArgColumnLabel( method, args ) ) {
try {
- int columnIndex = findColumn( ( String ) args[0] );
+ final int columnIndex = findColumn( (String) args[0] );
return invokeMethod(
- locateCorrespondingColumnIndexMethod( method ), buildColumnIndexMethodArgs( args, columnIndex )
+ locateCorrespondingColumnIndexMethod( method ),
+ buildColumnIndexMethodArgs( args, columnIndex )
);
}
catch ( SQLException ex ) {
- StringBuilder buf = new StringBuilder()
- .append( "Exception getting column index for column: [" )
- .append( args[0] )
- .append( "].\nReverting to using: [" )
- .append( args[0] )
- .append( "] as first argument for method: [" )
- .append( method )
- .append( "]" );
- sqlExceptionHelper.logExceptions( ex, buf.toString() );
+ final String msg = "Exception getting column index for column: [" + args[0] +
+ "].\nReverting to using: [" + args[0] +
+ "] as first argument for method: [" + method + "]";
+ SQL_EXCEPTION_HELPER.logExceptions( ex, msg );
}
catch ( NoSuchMethodException ex ) {
LOG.unableToSwitchToMethodUsingColumnIndex( method );
@@ -158,7 +156,7 @@ public class ResultSetWrapperProxy implements InvocationHandler {
* @throws NoSuchMethodException Should never happen, but...
*/
private Method locateCorrespondingColumnIndexMethod(Method columnNameMethod) throws NoSuchMethodException {
- Class actualParameterTypes[] = new Class[columnNameMethod.getParameterTypes().length];
+ final Class[] actualParameterTypes = new Class[columnNameMethod.getParameterTypes().length];
actualParameterTypes[0] = int.class;
System.arraycopy(
columnNameMethod.getParameterTypes(),
@@ -172,13 +170,13 @@ public class ResultSetWrapperProxy implements InvocationHandler {
@SuppressWarnings( {"UnnecessaryBoxing"})
private Object[] buildColumnIndexMethodArgs(Object[] incomingArgs, int columnIndex) {
- Object actualArgs[] = new Object[incomingArgs.length];
+ final Object[] actualArgs = new Object[incomingArgs.length];
actualArgs[0] = Integer.valueOf( columnIndex );
System.arraycopy( incomingArgs, 1, actualArgs, 1, incomingArgs.length - 1 );
return actualArgs;
}
- private Object invokeMethod(Method method, Object args[]) throws Throwable {
+ private Object invokeMethod(Method method, Object[] args) throws Throwable {
try {
return method.invoke( rs, args );
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableBlobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableBlobProxy.java
index 0d8209ef72..37796b530c 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableBlobProxy.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableBlobProxy.java
@@ -43,7 +43,7 @@ import org.hibernate.internal.util.ClassLoaderHelper;
public class SerializableBlobProxy implements InvocationHandler, Serializable {
private static final Class[] PROXY_INTERFACES = new Class[] { Blob.class, WrappedBlob.class, Serializable.class };
- private transient final Blob blob;
+ private final transient Blob blob;
/**
* Builds a serializable {@link Blob} wrapper around the given {@link Blob}.
@@ -55,6 +55,11 @@ public class SerializableBlobProxy implements InvocationHandler, Serializable {
this.blob = blob;
}
+ /**
+ * Access to the wrapped Blob reference
+ *
+ * @return The wrapped Blob reference
+ */
public Blob getWrappedBlob() {
if ( blob == null ) {
throw new IllegalStateException( "Blobs may not be accessed after serialization" );
@@ -88,11 +93,7 @@ public class SerializableBlobProxy implements InvocationHandler, Serializable {
* @return The generated proxy.
*/
public static Blob generateProxy(Blob blob) {
- return ( Blob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new SerializableBlobProxy( blob )
- );
+ return (Blob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new SerializableBlobProxy( blob ) );
}
/**
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableClobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableClobProxy.java
index 8b499e5c25..f5a490ae14 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableClobProxy.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableClobProxy.java
@@ -43,7 +43,7 @@ import org.hibernate.internal.util.ClassLoaderHelper;
public class SerializableClobProxy implements InvocationHandler, Serializable {
private static final Class[] PROXY_INTERFACES = new Class[] { Clob.class, WrappedClob.class, Serializable.class };
- private transient final Clob clob;
+ private final transient Clob clob;
/**
* Builds a serializable {@link java.sql.Clob} wrapper around the given {@link java.sql.Clob}.
@@ -55,6 +55,11 @@ public class SerializableClobProxy implements InvocationHandler, Serializable {
this.clob = clob;
}
+ /**
+ * Access to the wrapped Clob reference
+ *
+ * @return The wrapped Clob reference
+ */
public Clob getWrappedClob() {
if ( clob == null ) {
throw new IllegalStateException( "Clobs may not be accessed after serialization" );
@@ -87,11 +92,7 @@ public class SerializableClobProxy implements InvocationHandler, Serializable {
* @return The generated proxy.
*/
public static Clob generateProxy(Clob clob) {
- return ( Clob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new SerializableClobProxy( clob )
- );
+ return (Clob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new SerializableClobProxy( clob ) );
}
/**
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableNClobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableNClobProxy.java
index cde389cb01..7044058392 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableNClobProxy.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableNClobProxy.java
@@ -35,6 +35,16 @@ import java.sql.NClob;
public class SerializableNClobProxy extends SerializableClobProxy {
private static final Class[] PROXY_INTERFACES = new Class[] { NClob.class, WrappedNClob.class };
+ /**
+ * Deprecated.
+ *
+ * @param clob The possible NClob reference
+ *
+ * @return {@code true} if the the Clob is a NClob as well
+ *
+ * @deprecated ORM baselines on JDK 1.6, so optional support for NClob (JDK 1,6 addition) is no longer needed.
+ */
+ @Deprecated
public static boolean isNClob(Clob clob) {
return NClob.class.isInstance( clob );
}
@@ -57,11 +67,7 @@ public class SerializableNClobProxy extends SerializableClobProxy {
* @return The generated proxy.
*/
public static NClob generateProxy(NClob nclob) {
- return ( NClob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new SerializableNClobProxy( nclob )
- );
+ return (NClob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new SerializableNClobProxy( nclob ) );
}
/**
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/StreamUtils.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/StreamUtils.java
index 205030b03e..fd7f9178fa 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/StreamUtils.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/StreamUtils.java
@@ -35,14 +35,38 @@ import java.io.Writer;
* @author Steve Ebersole
*/
public class StreamUtils {
+ /**
+ * Default size to use for reading buffers.
+ */
public static final int DEFAULT_CHUNK_SIZE = 1024;
+ /**
+ * Copy the inputStream to the outputStream. Uses a buffer of the default size ({@link #DEFAULT_CHUNK_SIZE}).
+ *
+ * @param inputStream The input stream to read
+ * @param outputStream The output stream to write to
+ *
+ * @return The number of bytes read
+ *
+ * @throws IOException If a problem occurred accessing either stream
+ */
public static long copy(InputStream inputStream, OutputStream outputStream) throws IOException {
return copy( inputStream, outputStream, DEFAULT_CHUNK_SIZE );
}
+ /**
+ * Copy the inputStream to the outputStream using a buffer of the specified size
+ *
+ * @param inputStream The input stream to read
+ * @param outputStream The output stream to write to
+ * @param bufferSize The size of the buffer to use for reading
+ *
+ * @return The number of bytes read
+ *
+ * @throws IOException If a problem occurred accessing either stream
+ */
public static long copy(InputStream inputStream, OutputStream outputStream, int bufferSize) throws IOException {
- byte[] buffer = new byte[bufferSize];
+ final byte[] buffer = new byte[bufferSize];
long count = 0;
int n;
while ( -1 != ( n = inputStream.read( buffer ) ) ) {
@@ -50,15 +74,35 @@ public class StreamUtils {
count += n;
}
return count;
-
}
+ /**
+ * Copy the reader to the writer. Uses a buffer of the default size ({@link #DEFAULT_CHUNK_SIZE}).
+ *
+ * @param reader The reader to read from
+ * @param writer The writer to write to
+ *
+ * @return The number of bytes read
+ *
+ * @throws IOException If a problem occurred accessing reader or writer
+ */
public static long copy(Reader reader, Writer writer) throws IOException {
return copy( reader, writer, DEFAULT_CHUNK_SIZE );
}
+ /**
+ * Copy the reader to the writer using a buffer of the specified size
+ *
+ * @param reader The reader to read from
+ * @param writer The writer to write to
+ * @param bufferSize The size of the buffer to use for reading
+ *
+ * @return The number of bytes read
+ *
+ * @throws IOException If a problem occurred accessing either stream
+ */
public static long copy(Reader reader, Writer writer, int bufferSize) throws IOException {
- char[] buffer = new char[bufferSize];
+ final char[] buffer = new char[bufferSize];
long count = 0;
int n;
while ( -1 != ( n = reader.read( buffer ) ) ) {
@@ -66,6 +110,8 @@ public class StreamUtils {
count += n;
}
return count;
+ }
+ private StreamUtils() {
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/WrappedNClob.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/WrappedNClob.java
index 41c801e160..8e7d084a59 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/WrappedNClob.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/WrappedNClob.java
@@ -26,12 +26,24 @@ package org.hibernate.engine.jdbc;
import java.sql.NClob;
/**
+ * Contract for {@link NClob} wrappers.
+ *
* @author Steve Ebersole
*/
public interface WrappedNClob extends WrappedClob {
+ /**
+ * {@inheritDoc}
+ *
+ * @deprecated Use {@link #getWrappedNClob()} instead
+ */
@Override
@Deprecated
public NClob getWrappedClob();
+ /**
+ * Retrieve the wrapped {@link java.sql.Blob} reference
+ *
+ * @return The wrapped {@link java.sql.Blob} reference
+ */
public NClob getWrappedNClob();
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java
index 4d18551cde..bff82b93e0 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java
@@ -45,11 +45,14 @@ import org.hibernate.internal.CoreMessageLogger;
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
public abstract class AbstractBatchImpl implements Batch {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, AbstractBatchImpl.class.getName());
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ AbstractBatchImpl.class.getName()
+ );
private final BatchKey key;
private final JdbcCoordinator jdbcCoordinator;
+
private LinkedHashMap statements = new LinkedHashMap();
private LinkedHashSet observers = new LinkedHashSet();
@@ -191,7 +194,7 @@ public abstract class AbstractBatchImpl implements Batch {
@Override
public void release() {
- if ( getStatements() != null && !getStatements().isEmpty() ) {
+ if ( getStatements() != null && !getStatements().isEmpty() ) {
LOG.batchContainedStatementsOnRelease();
}
releaseStatements();
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java
index 0cff7e330a..1a9ecee23b 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java
@@ -27,6 +27,8 @@ import org.hibernate.engine.jdbc.batch.spi.BatchKey;
import org.hibernate.jdbc.Expectation;
/**
+ * Normal implementation of BatchKey
+ *
* @author Steve Ebersole
*/
public class BasicBatchKey implements BatchKey {
@@ -34,19 +36,12 @@ public class BasicBatchKey implements BatchKey {
private final int statementCount;
private final Expectation expectation;
-// public BasicBatchKey(String comparison, int statementCount, Expectation expectation) {
-// this.comparison = comparison;
-// this.statementCount = statementCount;
-// this.expectations = new Expectation[statementCount];
-// Arrays.fill( this.expectations, expectation );
-// }
-//
-// public BasicBatchKey(String comparison, Expectation... expectations) {
-// this.comparison = comparison;
-// this.statementCount = expectations.length;
-// this.expectations = expectations;
-// }
-
+ /**
+ * Constructs a BasicBatchKey
+ *
+ * @param comparison
+ * @param expectation
+ */
public BasicBatchKey(String comparison, Expectation expectation) {
this.comparison = comparison;
this.statementCount = 1;
@@ -72,7 +67,7 @@ public class BasicBatchKey implements BatchKey {
return false;
}
- BasicBatchKey that = (BasicBatchKey) o;
+ final BasicBatchKey that = (BasicBatchKey) o;
if ( !comparison.equals( that.comparison ) ) {
return false;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java
index 725f090124..ab77258d63 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java
@@ -42,23 +42,32 @@ import org.hibernate.service.spi.Configurable;
* @author Steve Ebersole
*/
public class BatchBuilderImpl implements BatchBuilder, Configurable {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, BatchBuilderImpl.class.getName() );
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ BatchBuilderImpl.class.getName()
+ );
private int size;
+ /**
+ * Constructs a BatchBuilderImpl
+ */
public BatchBuilderImpl() {
}
+ /**
+ * Constructs a BatchBuilderImpl
+ */
+ public BatchBuilderImpl(int size) {
+ this.size = size;
+ }
+
@Override
public void configure(Map configurationValues) {
size = ConfigurationHelper.getInt( Environment.STATEMENT_BATCH_SIZE, configurationValues, size );
}
- public BatchBuilderImpl(int size) {
- this.size = size;
- }
-
+ @SuppressWarnings("UnusedDeclaration")
public void setJdbcBatchSize(int size) {
this.size = size;
}
@@ -73,12 +82,14 @@ public class BatchBuilderImpl implements BatchBuilder, Configurable {
@Override
public String getManagementDomain() {
- return null; // use Hibernate default domain
+ // use Hibernate default domain
+ return null;
}
@Override
public String getManagementServiceType() {
- return null; // use Hibernate default scheme
+ // use Hibernate default scheme
+ return null;
}
@Override
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderInitiator.java
index 374a51edd3..edcb0f4014 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderInitiator.java
@@ -39,7 +39,14 @@ import org.hibernate.service.spi.ServiceRegistryImplementor;
* @author Steve Ebersole
*/
public class BatchBuilderInitiator implements StandardServiceInitiator {
+ /**
+ * Singleton access
+ */
public static final BatchBuilderInitiator INSTANCE = new BatchBuilderInitiator();
+
+ /**
+ * Names the BatchBuilder implementation to use.
+ */
public static final String BUILDER = "hibernate.jdbc.batch.builder";
@Override
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java
index 4af15f8562..dc948c6596 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java
@@ -40,8 +40,10 @@ import org.hibernate.internal.CoreMessageLogger;
* @author Steve Ebersole
*/
public class BatchingBatch extends AbstractBatchImpl {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, BatchingBatch.class.getName() );
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ BatchingBatch.class.getName()
+ );
// IMPL NOTE : Until HHH-5797 is fixed, there will only be 1 statement in a batch
@@ -49,6 +51,13 @@ public class BatchingBatch extends AbstractBatchImpl {
private int batchPosition;
private int statementPosition;
+ /**
+ * Constructs a BatchingBatch
+ *
+ * @param key The batch key
+ * @param jdbcCoordinator The JDBC jdbcCoordinator
+ * @param batchSize The batch size.
+ */
public BatchingBatch(
BatchKey key,
JdbcCoordinator jdbcCoordinator,
@@ -125,7 +134,7 @@ public class BatchingBatch extends AbstractBatchImpl {
}
private void checkRowCounts(int[] rowCounts, PreparedStatement ps) throws SQLException, HibernateException {
- int numberOfRowCounts = rowCounts.length;
+ final int numberOfRowCounts = rowCounts.length;
if ( numberOfRowCounts != batchPosition ) {
LOG.unexpectedRowCounts();
}
@@ -133,4 +142,4 @@ public class BatchingBatch extends AbstractBatchImpl {
getKey().getExpectation().verifyOutcome( rowCounts[i], ps, i );
}
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java
index 04e46a7e44..0531019632 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java
@@ -39,8 +39,10 @@ import org.jboss.logging.Logger;
* @author Steve Ebersole
*/
public class NonBatchingBatch extends AbstractBatchImpl {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, NonBatchingBatch.class.getName() );
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ NonBatchingBatch.class.getName()
+ );
private JdbcCoordinator jdbcCoordinator;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/package-info.java
new file mode 100644
index 0000000000..09bc7430f0
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Internals for JDBC batching support.
+ */
+package org.hibernate.engine.jdbc.batch.internal;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/spi/package-info.java
new file mode 100644
index 0000000000..3719ea4ba8
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/spi/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines contracts for JDBC batching support.
+ */
+package org.hibernate.engine.jdbc.batch.spi;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java
index 69438692a1..9985b19ee6 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java
@@ -52,14 +52,29 @@ import org.jboss.logging.Logger;
* @author Brett Meyer
*/
public class ConnectionProviderInitiator implements StandardServiceInitiator {
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ ConnectionProviderInitiator.class.getName()
+ );
+
+ /**
+ * Singleton access
+ */
public static final ConnectionProviderInitiator INSTANCE = new ConnectionProviderInitiator();
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class,
- ConnectionProviderInitiator.class.getName());
+ /**
+ * The strategy for c3p0 connection pooling
+ */
public static final String C3P0_STRATEGY = "c3p0";
+ /**
+ * The strategy for proxool connection pooling
+ */
public static final String PROXOOL_STRATEGY = "proxool";
+ /**
+ * No idea. Is this even still used?
+ */
public static final String INJECTION_DATA = "hibernate.connection_provider.injection_data";
// mapping from legacy connection provider name to actual
@@ -99,7 +114,7 @@ public class ConnectionProviderInitiator implements StandardServiceInitiator properties) {
- Properties result = new Properties();
+ final Properties result = new Properties();
for ( Map.Entry entry : properties.entrySet() ) {
if ( ! ( String.class.isInstance( entry.getKey() ) ) || ! String.class.isInstance( entry.getValue() ) ) {
continue;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DatasourceConnectionProviderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DatasourceConnectionProviderImpl.java
index 71b6e7f10c..516cc67872 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DatasourceConnectionProviderImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DatasourceConnectionProviderImpl.java
@@ -49,7 +49,6 @@ import org.hibernate.service.spi.Stoppable;
* @author Steve Ebersole
*/
public class DatasourceConnectionProviderImpl implements ConnectionProvider, Configurable, Stoppable {
-
private DataSource dataSource;
private String user;
private String pass;
@@ -67,6 +66,7 @@ public class DatasourceConnectionProviderImpl implements ConnectionProvider, Con
}
@InjectService( required = false )
+ @SuppressWarnings("UnusedDeclaration")
public void setJndiService(JndiService jndiService) {
this.jndiService = jndiService;
}
@@ -93,9 +93,7 @@ public class DatasourceConnectionProviderImpl implements ConnectionProvider, Con
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public void configure(Map configValues) {
if ( this.dataSource == null ) {
final Object dataSource = configValues.get( Environment.DATASOURCE );
@@ -126,14 +124,13 @@ public class DatasourceConnectionProviderImpl implements ConnectionProvider, Con
available = true;
}
+ @Override
public void stop() {
available = false;
dataSource = null;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Connection getConnection() throws SQLException {
if ( !available ) {
throw new HibernateException( "Provider is closed!" );
@@ -141,16 +138,12 @@ public class DatasourceConnectionProviderImpl implements ConnectionProvider, Con
return useCredentials ? dataSource.getConnection( user, pass ) : dataSource.getConnection();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public void closeConnection(Connection connection) throws SQLException {
connection.close();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean supportsAggressiveRelease() {
return true;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DriverManagerConnectionProviderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DriverManagerConnectionProviderImpl.java
index df83684145..8482085edb 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DriverManagerConnectionProviderImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DriverManagerConnectionProviderImpl.java
@@ -95,10 +95,11 @@ public class DriverManagerConnectionProviderImpl
}
}
+ @Override
public void configure(Map configurationValues) {
LOG.usingHibernateBuiltInConnectionPool();
- String driverClassName = (String) configurationValues.get( AvailableSettings.DRIVER );
+ final String driverClassName = (String) configurationValues.get( AvailableSettings.DRIVER );
if ( driverClassName == null ) {
LOG.jdbcDriverNotSpecified( AvailableSettings.DRIVER );
}
@@ -131,19 +132,21 @@ public class DriverManagerConnectionProviderImpl
}
}
- poolSize = ConfigurationHelper.getInt( AvailableSettings.POOL_SIZE, configurationValues, 20 ); // default pool size 20
+ // default pool size 20
+ poolSize = ConfigurationHelper.getInt( AvailableSettings.POOL_SIZE, configurationValues, 20 );
LOG.hibernateConnectionPoolSize( poolSize );
autocommit = ConfigurationHelper.getBoolean( AvailableSettings.AUTOCOMMIT, configurationValues );
LOG.autoCommitMode( autocommit );
isolation = ConfigurationHelper.getInteger( AvailableSettings.ISOLATION, configurationValues );
- if ( isolation != null )
+ if ( isolation != null ) {
LOG.jdbcIsolationLevel( Environment.isolationLevelToString( isolation.intValue() ) );
+ }
url = (String) configurationValues.get( AvailableSettings.URL );
if ( url == null ) {
- String msg = LOG.jdbcUrlNotSpecified( AvailableSettings.URL );
+ final String msg = LOG.jdbcUrlNotSpecified( AvailableSettings.URL );
LOG.error( msg );
throw new HibernateException( msg );
}
@@ -152,12 +155,15 @@ public class DriverManagerConnectionProviderImpl
LOG.usingDriver( driverClassName, url );
// if debug level is enabled, then log the password, otherwise mask it
- if ( LOG.isDebugEnabled() )
+ if ( LOG.isDebugEnabled() ) {
LOG.connectionProperties( connectionProps );
- else
+ }
+ else {
LOG.connectionProperties( ConfigurationHelper.maskOut( connectionProps, "password" ) );
+ }
}
+ @Override
public void stop() {
LOG.cleaningUpConnectionPool( url );
@@ -173,16 +179,21 @@ public class DriverManagerConnectionProviderImpl
stopped = true;
}
+ @Override
public Connection getConnection() throws SQLException {
final boolean traceEnabled = LOG.isTraceEnabled();
- if ( traceEnabled ) LOG.tracev( "Total checked-out connections: {0}", checkedOut.intValue() );
+ if ( traceEnabled ) {
+ LOG.tracev( "Total checked-out connections: {0}", checkedOut.intValue() );
+ }
// essentially, if we have available connections in the pool, use one...
synchronized (pool) {
if ( !pool.isEmpty() ) {
int last = pool.size() - 1;
- if ( traceEnabled ) LOG.tracev( "Using pooled JDBC connection, pool size: {0}", last );
- Connection pooled = pool.remove( last );
+ if ( traceEnabled ) {
+ LOG.tracev( "Using pooled JDBC connection, pool size: {0}", last );
+ }
+ final Connection pooled = pool.remove( last );
if ( isolation != null ) {
pooled.setTransactionIsolation( isolation.intValue() );
}
@@ -196,9 +207,11 @@ public class DriverManagerConnectionProviderImpl
// otherwise we open a new connection...
final boolean debugEnabled = LOG.isDebugEnabled();
- if ( debugEnabled ) LOG.debug( "Opening new JDBC connection" );
+ if ( debugEnabled ) {
+ LOG.debug( "Opening new JDBC connection" );
+ }
- Connection conn;
+ final Connection conn;
if ( driver != null ) {
// If a Driver is available, completely circumvent
// DriverManager#getConnection. It attempts to double check
@@ -215,7 +228,7 @@ public class DriverManagerConnectionProviderImpl
conn.setTransactionIsolation( isolation.intValue() );
}
if ( conn.getAutoCommit() != autocommit ) {
- conn.setAutoCommit(autocommit);
+ conn.setAutoCommit( autocommit );
}
if ( debugEnabled ) {
@@ -226,15 +239,18 @@ public class DriverManagerConnectionProviderImpl
return conn;
}
+ @Override
public void closeConnection(Connection conn) throws SQLException {
checkedOut.decrementAndGet();
final boolean traceEnabled = LOG.isTraceEnabled();
// add to the pool if the max size is not yet reached.
synchronized ( pool ) {
- int currentSize = pool.size();
+ final int currentSize = pool.size();
if ( currentSize < poolSize ) {
- if ( traceEnabled ) LOG.tracev( "Returning connection to pool, pool size: {0}", ( currentSize + 1 ) );
+ if ( traceEnabled ) {
+ LOG.tracev( "Returning connection to pool, pool size: {0}", ( currentSize + 1 ) );
+ }
pool.add( conn );
return;
}
@@ -252,6 +268,7 @@ public class DriverManagerConnectionProviderImpl
super.finalize();
}
+ @Override
public boolean supportsAggressiveRelease() {
return false;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/MultiTenantConnectionProviderInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/MultiTenantConnectionProviderInitiator.java
index deedad18f7..cc8d25ce2b 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/MultiTenantConnectionProviderInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/MultiTenantConnectionProviderInitiator.java
@@ -38,12 +38,18 @@ import org.hibernate.service.spi.ServiceException;
import org.hibernate.service.spi.ServiceRegistryImplementor;
/**
+ * A service initiator for the MultiTenantConnectionProvider service
+ *
* @author Steve Ebersole
*/
public class MultiTenantConnectionProviderInitiator implements StandardServiceInitiator {
- public static final MultiTenantConnectionProviderInitiator INSTANCE = new MultiTenantConnectionProviderInitiator();
private static final Logger log = Logger.getLogger( MultiTenantConnectionProviderInitiator.class );
+ /**
+ * Singleton access
+ */
+ public static final MultiTenantConnectionProviderInitiator INSTANCE = new MultiTenantConnectionProviderInitiator();
+
@Override
public Class getServiceInitiated() {
return MultiTenantConnectionProvider.class;
@@ -55,6 +61,7 @@ public class MultiTenantConnectionProviderInitiator implements StandardServiceIn
final MultiTenancyStrategy strategy = MultiTenancyStrategy.determineMultiTenancyStrategy( configurationValues );
if ( strategy == MultiTenancyStrategy.NONE || strategy == MultiTenancyStrategy.DISCRIMINATOR ) {
// nothing to do, but given the separate hierarchies have to handle this here.
+ return null;
}
final Object configValue = configurationValues.get( AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER );
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/UserSuppliedConnectionProviderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/UserSuppliedConnectionProviderImpl.java
index b7c966ea4b..903491d91b 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/UserSuppliedConnectionProviderImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/UserSuppliedConnectionProviderImpl.java
@@ -55,23 +55,17 @@ public class UserSuppliedConnectionProviderImpl implements ConnectionProvider {
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Connection getConnection() throws SQLException {
throw new UnsupportedOperationException( "The application must supply JDBC connections" );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public void closeConnection(Connection conn) throws SQLException {
throw new UnsupportedOperationException( "The application must supply JDBC connections" );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean supportsAggressiveRelease() {
return false;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/package-info.java
new file mode 100644
index 0000000000..397a72a46f
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Internals for accessing JDBC Connections
+ */
+package org.hibernate.engine.jdbc.connections.internal;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/ConnectionProvider.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/ConnectionProvider.java
index 762d5b4613..ea47422c5e 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/ConnectionProvider.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/ConnectionProvider.java
@@ -25,7 +25,6 @@ package org.hibernate.engine.jdbc.connections.spi;
import java.sql.Connection;
import java.sql.SQLException;
-import org.hibernate.HibernateException;
import org.hibernate.service.Service;
import org.hibernate.service.spi.Wrapped;
@@ -46,7 +45,7 @@ public interface ConnectionProvider extends Service, Wrapped {
* @return The obtained JDBC connection
*
* @throws SQLException Indicates a problem opening a connection
- * @throws HibernateException Indicates a problem otherwise obtaining a connection.
+ * @throws org.hibernate.HibernateException Indicates a problem otherwise obtaining a connection.
*/
public Connection getConnection() throws SQLException;
@@ -56,7 +55,7 @@ public interface ConnectionProvider extends Service, Wrapped {
* @param conn The JDBC connection to release
*
* @throws SQLException Indicates a problem closing the connection
- * @throws HibernateException Indicates a problem otherwise releasing a connection.
+ * @throws org.hibernate.HibernateException Indicates a problem otherwise releasing a connection.
*/
public void closeConnection(Connection conn) throws SQLException;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/DataSourceBasedMultiTenantConnectionProviderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/DataSourceBasedMultiTenantConnectionProviderImpl.java
index cb387f1421..e13325ce77 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/DataSourceBasedMultiTenantConnectionProviderImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/DataSourceBasedMultiTenantConnectionProviderImpl.java
@@ -56,6 +56,9 @@ public class DataSourceBasedMultiTenantConnectionProviderImpl
extends AbstractDataSourceBasedMultiTenantConnectionProviderImpl
implements ServiceRegistryAwareService, Stoppable {
+ /**
+ * Identifies the DataSource name to use for {@link #selectAnyDataSource} handling
+ */
public static final String TENANT_IDENTIFIER_TO_USE_FOR_ANY_KEY = "hibernate.multi_tenant.datasource.identifier_for_any";
private Map dataSourceMap;
@@ -100,13 +103,13 @@ public class DataSourceBasedMultiTenantConnectionProviderImpl
throw new HibernateException( "Could not locate JndiService from DataSourceBasedMultiTenantConnectionProviderImpl" );
}
- Object namedObject = jndiService.locate( jndiName );
+ final Object namedObject = jndiService.locate( jndiName );
if ( namedObject == null ) {
throw new HibernateException( "JNDI name [" + jndiName + "] could not be resolved" );
}
if ( DataSource.class.isInstance( namedObject ) ) {
- int loc = jndiName.lastIndexOf( "/" );
+ final int loc = jndiName.lastIndexOf( "/" );
this.baseJndiNamespace = jndiName.substring( 0, loc );
this.tenantIdentifierForAny = jndiName.substring( loc + 1 );
dataSourceMap().put( tenantIdentifierForAny, (DataSource) namedObject );
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/MultiTenantConnectionProvider.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/MultiTenantConnectionProvider.java
index 860d926c0b..b9fe64dff3 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/MultiTenantConnectionProvider.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/MultiTenantConnectionProvider.java
@@ -30,6 +30,9 @@ import org.hibernate.service.Service;
import org.hibernate.service.spi.Wrapped;
/**
+ * A specialized Connection provider contract used when the application is using multi-tenancy support requiring
+ * tenant aware connections.
+ *
* @author Steve Ebersole
*/
public interface MultiTenantConnectionProvider extends Service, Wrapped {
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/package-info.java
new file mode 100644
index 0000000000..84342f8c58
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines contracts for accessing JDBC Connections
+ */
+package org.hibernate.engine.jdbc.connections.spi;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/package-info.java
new file mode 100644
index 0000000000..acd103dc0b
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Support for various aspects of JDBC interaction
+ */
+package org.hibernate.engine.jdbc;
diff --git a/shared/config/checkstyle/checkstyle.xml b/shared/config/checkstyle/checkstyle.xml
index a595af07b1..35417093de 100644
--- a/shared/config/checkstyle/checkstyle.xml
+++ b/shared/config/checkstyle/checkstyle.xml
@@ -202,7 +202,10 @@
+
From 1c690ca89b433548ec0b8840ce08b649c71664d9 Mon Sep 17 00:00:00 2001
From: Steve Ebersole
Date: Mon, 29 Apr 2013 20:24:54 -0500
Subject: [PATCH 27/57] HHH-8159 - Apply fixups indicated by analysis tools
---
.../engine/internal/ForeignKeys.java | 6 +-
.../org/hibernate/engine/jdbc/BlobProxy.java | 2 +-
.../engine/jdbc/ResultSetWrapperProxy.java | 2 +-
.../jdbc/batch/internal/BasicBatchKey.java | 11 +--
.../jdbc/batch/internal/BatchBuilderImpl.java | 2 +
.../internal/ConnectionProviderInitiator.java | 2 +-
.../DriverManagerConnectionProviderImpl.java | 2 +-
.../internal/RefCursorSupportInitiator.java | 5 ++
.../internal/StandardRefCursorSupport.java | 14 ++++
.../jdbc/cursor/internal/package-info.java | 4 +
.../jdbc/cursor/spi/RefCursorSupport.java | 2 +
.../engine/jdbc/cursor/spi/package-info.java | 4 +
.../internal/BasicDialectResolver.java | 19 ++++-
.../DatabaseInfoDialectResolverInitiator.java | 5 ++
.../DatabaseInfoDialectResolverSet.java | 20 ++++-
.../internal/DialectFactoryInitiator.java | 3 +
.../dialect/internal/DialectResolverSet.java | 28 ++++++-
.../StandardDatabaseInfoDialectResolver.java | 7 +-
...andardDatabaseMetaDataDialectResolver.java | 12 ++-
.../jdbc/dialect/internal/package-info.java | 4 +
...stractDatabaseMetaDataDialectResolver.java | 14 ++--
.../spi/BasicSQLExceptionConverter.java | 3 +-
.../spi/DatabaseInfoDialectResolver.java | 6 ++
.../jdbc/dialect/spi/DialectResolver.java | 5 ++
.../engine/jdbc/dialect/spi/package-info.java | 4 +
.../jdbc/internal/BasicFormatterImpl.java | 37 ++++-----
.../jdbc/internal/BinaryStreamImpl.java | 5 ++
.../jdbc/internal/CharacterStreamImpl.java | 12 ++-
.../jdbc/internal/DDLFormatterImpl.java | 38 +++++-----
.../engine/jdbc/internal/FormatStyle.java | 19 ++++-
.../jdbc/internal/JdbcCoordinatorImpl.java | 76 ++++++++++++++-----
.../jdbc/internal/JdbcServicesImpl.java | 27 ++++---
.../jdbc/internal/JdbcServicesInitiator.java | 5 +-
.../jdbc/internal/LobCreatorBuilder.java | 30 +++++---
.../jdbc/internal/LogicalConnectionImpl.java | 53 ++++++++++---
.../jdbc/internal/ResultSetReturnImpl.java | 33 +++++---
.../jdbc/internal/ResultSetWrapperImpl.java | 10 ++-
.../jdbc/internal/StatementPreparerImpl.java | 23 +++---
.../engine/jdbc/internal/package-info.java | 4 +
.../engine/jdbc/spi/package-info.java | 4 +
40 files changed, 411 insertions(+), 151 deletions(-)
create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/package-info.java
create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/package-info.java
create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/package-info.java
create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/package-info.java
create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/package-info.java
create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/package-info.java
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/ForeignKeys.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/ForeignKeys.java
index 58563f936c..d60257e146 100755
--- a/hibernate-core/src/main/java/org/hibernate/engine/internal/ForeignKeys.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/ForeignKeys.java
@@ -76,8 +76,7 @@ public final class ForeignKeys {
* @param values The entity attribute values
* @param types The entity attribute types
*/
- public void nullifyTransientReferences(final Object[] values, final Type[] types)
- throws HibernateException {
+ public void nullifyTransientReferences(final Object[] values, final Type[] types) {
for ( int i = 0; i < types.length; i++ ) {
values[i] = nullifyTransientReferences( values[i], types[i] );
}
@@ -92,8 +91,7 @@ public final class ForeignKeys {
*
* @return {@code null} if the argument is an unsaved entity; otherwise return the argument.
*/
- private Object nullifyTransientReferences(final Object value, final Type type)
- throws HibernateException {
+ private Object nullifyTransientReferences(final Object value, final Type type) {
if ( value == null ) {
return null;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java
index 92787ba459..fa1c554ac3 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java
@@ -112,7 +112,7 @@ public class BlobProxy implements InvocationHandler {
return getStream();
}
else if ( argCount == 2 ) {
- long start = (Long) args[0];
+ final long start = (Long) args[0];
if ( start < 1 ) {
throw new SQLException( "Start position 1-based; must be 1 or more." );
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java
index addfd6210f..d162fbb2a6 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java
@@ -127,7 +127,7 @@ public class ResultSetWrapperProxy implements InvocationHandler {
return columnNameCache.getIndexForColumnName( columnName, rs );
}
- private boolean isFirstArgColumnLabel(Method method, Object args[]) {
+ private boolean isFirstArgColumnLabel(Method method, Object[] args) {
// method name should start with either get or update
if ( ! ( method.getName().startsWith( "get" ) || method.getName().startsWith( "update" ) ) ) {
return false;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java
index 1a9ecee23b..32e085832c 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java
@@ -39,8 +39,8 @@ public class BasicBatchKey implements BatchKey {
/**
* Constructs a BasicBatchKey
*
- * @param comparison
- * @param expectation
+ * @param comparison A string used to compare batch keys.
+ * @param expectation The expectation for the batch
*/
public BasicBatchKey(String comparison, Expectation expectation) {
this.comparison = comparison;
@@ -68,12 +68,7 @@ public class BasicBatchKey implements BatchKey {
}
final BasicBatchKey that = (BasicBatchKey) o;
-
- if ( !comparison.equals( that.comparison ) ) {
- return false;
- }
-
- return true;
+ return comparison.equals( that.comparison );
}
@Override
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java
index ab77258d63..1c46bb292d 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java
@@ -57,6 +57,8 @@ public class BatchBuilderImpl implements BatchBuilder, Configurable {
/**
* Constructs a BatchBuilderImpl
+ *
+ * @param size The batch size to use.
*/
public BatchBuilderImpl(int size) {
this.size = size;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java
index 9985b19ee6..b458dd2ce3 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java
@@ -202,7 +202,7 @@ public class ConnectionProviderInitiator implements StandardServiceInitiator {
+ /**
+ * Singleton access
+ */
public static final RefCursorSupportInitiator INSTANCE = new RefCursorSupportInitiator();
@Override
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java
index 3e83be53c0..c1c98ac215 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java
@@ -39,6 +39,8 @@ import org.hibernate.engine.jdbc.cursor.spi.RefCursorSupport;
import org.hibernate.service.spi.InjectService;
/**
+ * Standard implementation of RefCursorSupport
+ *
* @author Steve Ebersole
*/
public class StandardRefCursorSupport implements RefCursorSupport {
@@ -46,6 +48,11 @@ public class StandardRefCursorSupport implements RefCursorSupport {
private JdbcServices jdbcServices;
+ /**
+ * Hook for service registry to be able to inject JdbcServices
+ *
+ * @param jdbcServices The JdbcServices service
+ */
@InjectService
@SuppressWarnings("UnusedDeclaration")
public void injectJdbcServices(JdbcServices jdbcServices) {
@@ -160,6 +167,13 @@ public class StandardRefCursorSupport implements RefCursorSupport {
}
}
+ /**
+ * Does this JDBC metadata indicate that the driver defines REF_CURSOR support?
+ *
+ * @param meta The JDBC metadata
+ *
+ * @return {@code true} if the metadata indicates that the driver defines REF_CURSOR support
+ */
@SuppressWarnings("UnnecessaryUnboxing")
public static boolean supportsRefCursors(DatabaseMetaData meta) {
// Standard JDBC REF_CURSOR support was not added until Java 8, so we need to use reflection to attempt to
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/package-info.java
new file mode 100644
index 0000000000..211dbd1302
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Internals for JDBC REF_CURSOR support.
+ */
+package org.hibernate.engine.jdbc.cursor.internal;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/RefCursorSupport.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/RefCursorSupport.java
index 7785f0954f..ad7263e752 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/RefCursorSupport.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/RefCursorSupport.java
@@ -29,6 +29,8 @@ import java.sql.ResultSet;
import org.hibernate.service.Service;
/**
+ * Contract for JDBC REF_CURSOR support.
+ *
* @author Steve Ebersole
*/
public interface RefCursorSupport extends Service {
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/package-info.java
new file mode 100644
index 0000000000..6f9a0e635c
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines contracts for JDBC REF_CURSOR support.
+ */
+package org.hibernate.engine.jdbc.cursor.spi;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/BasicDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/BasicDialectResolver.java
index fb617d72c2..b96c41ee28 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/BasicDialectResolver.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/BasicDialectResolver.java
@@ -40,22 +40,39 @@ import org.hibernate.engine.jdbc.dialect.spi.AbstractDatabaseMetaDataDialectReso
*/
@Deprecated
public class BasicDialectResolver extends AbstractDatabaseMetaDataDialectResolver {
+ /**
+ * Constant indicating no version info was given
+ */
public static final int VERSION_INSENSITIVE_VERSION = -9999;
private final String matchingName;
private final int matchingVersion;
private final Class dialectClass;
+ /**
+ * Constructs a BasicDialectResolver
+ *
+ * @param matchingName The name of the driver to match on
+ * @param dialectClass The Dialect class to use on match
+ */
public BasicDialectResolver(String matchingName, Class dialectClass) {
this( matchingName, VERSION_INSENSITIVE_VERSION, dialectClass );
}
+ /**
+ * Constructs a BasicDialectResolver
+ *
+ * @param matchingName The name of the driver to match on
+ * @param matchingVersion The version of the driver to match on
+ * @param dialectClass The Dialect class to use on match
+ */
public BasicDialectResolver(String matchingName, int matchingVersion, Class dialectClass) {
this.matchingName = matchingName;
this.matchingVersion = matchingVersion;
this.dialectClass = dialectClass;
}
+ @Override
protected final Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException {
final String databaseName = metaData.getDatabaseProductName();
final int databaseMajorVersion = metaData.getDatabaseMajorVersion();
@@ -63,7 +80,7 @@ public class BasicDialectResolver extends AbstractDatabaseMetaDataDialectResolve
if ( matchingName.equalsIgnoreCase( databaseName )
&& ( matchingVersion == VERSION_INSENSITIVE_VERSION || matchingVersion == databaseMajorVersion ) ) {
try {
- return ( Dialect ) dialectClass.newInstance();
+ return (Dialect) dialectClass.newInstance();
}
catch ( HibernateException e ) {
// conceivable that the dialect ctor could throw HibernateExceptions, so don't re-wrap
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverInitiator.java
index 9ad43d9ca2..3fb14158d0 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverInitiator.java
@@ -35,9 +35,14 @@ import org.hibernate.service.spi.ServiceException;
import org.hibernate.service.spi.ServiceRegistryImplementor;
/**
+ * Initiator for the DatabaseInfoDialectResolver service
+ *
* @author Steve Ebersole
*/
public class DatabaseInfoDialectResolverInitiator implements StandardServiceInitiator {
+ /**
+ * Singleton access
+ */
public static final DatabaseInfoDialectResolverInitiator INSTANCE = new DatabaseInfoDialectResolverInitiator();
@Override
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverSet.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverSet.java
index d3816ccd69..d9149a9195 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverSet.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverSet.java
@@ -31,19 +31,36 @@ import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.dialect.spi.DatabaseInfoDialectResolver;
/**
+ * Implements the DatabaseInfoDialectResolver as a chain, allowing multiple delegate DatabaseInfoDialectResolver
+ * implementations to coordinate resolution
+ *
* @author Steve Ebersole
*/
public class DatabaseInfoDialectResolverSet implements DatabaseInfoDialectResolver {
private List delegateResolvers;
+ /**
+ * Constructs a DatabaseInfoDialectResolverSet
+ */
public DatabaseInfoDialectResolverSet() {
this( new ArrayList() );
}
+ /**
+ * Constructs a DatabaseInfoDialectResolverSet
+ *
+ * @param delegateResolvers The set of delegate resolvers
+ */
public DatabaseInfoDialectResolverSet(List delegateResolvers) {
this.delegateResolvers = delegateResolvers;
}
+ /**
+ * Constructs a DatabaseInfoDialectResolverSet
+ *
+ * @param delegateResolvers The set of delegate resolvers
+ */
+ @SuppressWarnings("UnusedDeclaration")
public DatabaseInfoDialectResolverSet(DatabaseInfoDialectResolver... delegateResolvers) {
this( Arrays.asList( delegateResolvers ) );
}
@@ -51,7 +68,7 @@ public class DatabaseInfoDialectResolverSet implements DatabaseInfoDialectResolv
@Override
public Dialect resolve(DatabaseInfo databaseInfo) {
for ( DatabaseInfoDialectResolver resolver : delegateResolvers ) {
- Dialect dialect = resolver.resolve( databaseInfo );
+ final Dialect dialect = resolver.resolve( databaseInfo );
if ( dialect != null ) {
return dialect;
}
@@ -75,6 +92,7 @@ public class DatabaseInfoDialectResolverSet implements DatabaseInfoDialectResolv
*
* @param resolver The resolver to add.
*/
+ @SuppressWarnings("UnusedDeclaration")
public void addResolverAtFirst(DatabaseInfoDialectResolver resolver) {
delegateResolvers.add( 0, resolver );
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectFactoryInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectFactoryInitiator.java
index a207465656..26e67f3bfa 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectFactoryInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectFactoryInitiator.java
@@ -35,6 +35,9 @@ import org.hibernate.service.spi.ServiceRegistryImplementor;
* @author Steve Ebersole
*/
public class DialectFactoryInitiator implements StandardServiceInitiator {
+ /**
+ * Singleton access
+ */
public static final DialectFactoryInitiator INSTANCE = new DialectFactoryInitiator();
@Override
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectResolverSet.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectResolverSet.java
index ed11ab2c5d..2ae9d3ad12 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectResolverSet.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectResolverSet.java
@@ -40,29 +40,51 @@ import org.hibernate.engine.jdbc.dialect.spi.DialectResolver;
*
* @author Tomoto Shimizu Washio
* @author Steve Ebersole
+ *
+ * @deprecated See deprecation on {@link DialectResolver}
*/
+@Deprecated
public class DialectResolverSet implements DialectResolver {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, DialectResolverSet.class.getName());
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ DialectResolverSet.class.getName()
+ );
private List resolvers;
+ /**
+ * Deprecated
+ */
public DialectResolverSet() {
this( new ArrayList() );
+ LOG.debug( "DialectResolverSet is deprecated" );
}
+ /**
+ * Deprecated
+ *
+ * @param resolvers The delegate resolvers
+ */
public DialectResolverSet(List resolvers) {
this.resolvers = resolvers;
+ LOG.debug( "DialectResolverSet is deprecated" );
}
+ /**
+ * Deprecated
+ *
+ * @param resolvers The delegate resolvers
+ */
public DialectResolverSet(DialectResolver... resolvers) {
this( Arrays.asList( resolvers ) );
+ LOG.debug( "DialectResolverSet is deprecated" );
}
+ @Override
public Dialect resolveDialect(DatabaseMetaData metaData) throws JDBCConnectionException {
for ( DialectResolver resolver : resolvers ) {
try {
- Dialect dialect = resolver.resolveDialect( metaData );
+ final Dialect dialect = resolver.resolveDialect( metaData );
if ( dialect != null ) {
return dialect;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseInfoDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseInfoDialectResolver.java
index 814c1dd4b1..6b70e520b3 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseInfoDialectResolver.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseInfoDialectResolver.java
@@ -54,9 +54,14 @@ import org.hibernate.engine.jdbc.dialect.spi.DatabaseInfoDialectResolver;
import org.hibernate.internal.CoreMessageLogger;
/**
+ * The standard DatabaseInfoDialectResolver implementation
+ *
* @author Steve Ebersole
*/
public class StandardDatabaseInfoDialectResolver implements DatabaseInfoDialectResolver {
+ /**
+ * Singleton access
+ */
public static final StandardDatabaseInfoDialectResolver INSTANCE = new StandardDatabaseInfoDialectResolver();
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
@@ -159,7 +164,7 @@ public class StandardDatabaseInfoDialectResolver implements DatabaseInfoDialectR
return new InformixDialect();
}
- if ( databaseName.equals("DB2 UDB for AS/400" ) ) {
+ if ( "DB2 UDB for AS/400".equals( databaseName ) ) {
return new DB2400Dialect();
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java
index c54bfd8ef7..ca2406fe07 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java
@@ -39,14 +39,22 @@ import org.hibernate.engine.jdbc.dialect.spi.DatabaseInfoDialectResolver;
public class StandardDatabaseMetaDataDialectResolver extends AbstractDatabaseMetaDataDialectResolver {
private final DatabaseInfoDialectResolver infoResolver;
+ /**
+ * Constructs a StandardDatabaseMetaDataDialectResolver
+ *
+ * @param infoResolver The delegate resolver
+ */
public StandardDatabaseMetaDataDialectResolver(DatabaseInfoDialectResolver infoResolver) {
this.infoResolver = infoResolver;
}
+ /**
+ * A DatabaseInfo implementation wrapping a JDBC DatabaseMetaData reference
+ */
public static final class DatabaseInfoImpl implements DatabaseInfoDialectResolver.DatabaseInfo {
private final DatabaseMetaData databaseMetaData;
- public DatabaseInfoImpl(DatabaseMetaData databaseMetaData) {
+ protected DatabaseInfoImpl(DatabaseMetaData databaseMetaData) {
this.databaseMetaData = databaseMetaData;
}
@@ -82,7 +90,7 @@ public class StandardDatabaseMetaDataDialectResolver extends AbstractDatabaseMet
}
@Override
- protected Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException {
+ protected Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException {
if ( infoResolver == null ) {
return null;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/package-info.java
new file mode 100644
index 0000000000..dc8bdcc5d5
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Internal support for Dialect resolution (from JDBC metadata) and Dialect building.
+ */
+package org.hibernate.engine.jdbc.dialect.internal;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java
index 65785c5cde..5226dfe8dd 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java
@@ -40,8 +40,7 @@ import org.hibernate.internal.CoreMessageLogger;
* @author Steve Ebersole
*/
public abstract class AbstractDatabaseMetaDataDialectResolver implements DialectResolver {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class,
AbstractDatabaseMetaDataDialectResolver.class.getName()
);
@@ -52,21 +51,22 @@ public abstract class AbstractDatabaseMetaDataDialectResolver implements Dialect
* Here we template the resolution, delegating to {@link #resolveDialectInternal} and handling
* {@link java.sql.SQLException}s properly.
*/
+ @Override
public final Dialect resolveDialect(DatabaseMetaData metaData) {
try {
return resolveDialectInternal( metaData );
}
catch ( SQLException sqlException ) {
- JDBCException jdbcException = BasicSQLExceptionConverter.INSTANCE.convert( sqlException );
- if (jdbcException instanceof JDBCConnectionException) {
+ final JDBCException jdbcException = BasicSQLExceptionConverter.INSTANCE.convert( sqlException );
+ if (jdbcException instanceof JDBCConnectionException) {
throw jdbcException;
}
- LOG.warnf( "%s : %s", BasicSQLExceptionConverter.MSG, sqlException.getMessage() );
- return null;
+ LOG.warnf( "%s : %s", BasicSQLExceptionConverter.MSG, sqlException.getMessage() );
+ return null;
}
catch ( Throwable t ) {
- LOG.unableToExecuteResolver( this, t.getMessage() );
+ LOG.unableToExecuteResolver( this, t.getMessage() );
return null;
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/BasicSQLExceptionConverter.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/BasicSQLExceptionConverter.java
index b0a4bc5ebe..ea554a052d 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/BasicSQLExceptionConverter.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/BasicSQLExceptionConverter.java
@@ -50,7 +50,7 @@ public class BasicSQLExceptionConverter {
public static final BasicSQLExceptionConverter INSTANCE = new BasicSQLExceptionConverter();
/**
- *
+ * Message
*/
public static final String MSG = LOG.unableToQueryDatabaseMetadata();
@@ -70,6 +70,7 @@ public class BasicSQLExceptionConverter {
/**
* {@inheritDoc}
*/
+ @Override
public String extractConstraintName(SQLException sqle) {
return "???";
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DatabaseInfoDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DatabaseInfoDialectResolver.java
index 9eccc26347..a532e35389 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DatabaseInfoDialectResolver.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DatabaseInfoDialectResolver.java
@@ -42,7 +42,13 @@ public interface DatabaseInfoDialectResolver extends Service {
*/
public Dialect resolve(DatabaseInfo databaseInfo);
+ /**
+ * Essentially a "parameter object" for {@link DatabaseInfoDialectResolver#resolve}
+ */
public static interface DatabaseInfo {
+ /**
+ * Constant used to indicate that no version is defined
+ */
public static final int NO_VERSION = -9999;
/**
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DialectResolver.java
index 4cec52fa7b..0fca0dfcc6 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DialectResolver.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DialectResolver.java
@@ -24,8 +24,13 @@
package org.hibernate.engine.jdbc.dialect.spi;
/**
+ * Deprecated
+ *
* @deprecated Deprecated in favor of {@link DatabaseMetaDataDialectResolver} to account for resolving by name versus
* by DatabaseMetaData
+ *
+ * @see DatabaseMetaDataDialectResolver
+ * @see DatabaseInfoDialectResolver
*/
@Deprecated
public interface DialectResolver extends DatabaseMetaDataDialectResolver {
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/package-info.java
new file mode 100644
index 0000000000..53a64d46e9
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Contracts supporting Dialect resolution (from JDBC metadata) and Dialect building.
+ */
+package org.hibernate.engine.jdbc.dialect.spi;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BasicFormatterImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BasicFormatterImpl.java
index 0b2babef47..f0fd816b7b 100755
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BasicFormatterImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BasicFormatterImpl.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
- * distributed under license by Red Hat Middleware LLC.
+ * distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@@ -20,7 +20,6 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
- *
*/
package org.hibernate.engine.jdbc.internal;
@@ -84,23 +83,24 @@ public class BasicFormatterImpl implements Formatter {
MISC.add( "on" );
}
- static final String indentString = " ";
- static final String initial = "\n ";
+ private static final String INDENT_STRING = " ";
+ private static final String INITIAL = "\n ";
+ @Override
public String format(String source) {
return new FormatProcess( source ).perform();
}
private static class FormatProcess {
boolean beginLine = true;
- boolean afterBeginBeforeEnd = false;
- boolean afterByOrSetOrFromOrSelect = false;
- boolean afterValues = false;
- boolean afterOn = false;
- boolean afterBetween = false;
- boolean afterInsert = false;
- int inFunction = 0;
- int parensSinceSelect = 0;
+ boolean afterBeginBeforeEnd;
+ boolean afterByOrSetOrFromOrSelect;
+ boolean afterValues;
+ boolean afterOn;
+ boolean afterBetween;
+ boolean afterInsert;
+ int inFunction;
+ int parensSinceSelect;
private LinkedList parenCounts = new LinkedList();
private LinkedList afterByOrFromOrSelects = new LinkedList();
@@ -122,7 +122,7 @@ public class BasicFormatterImpl implements Formatter {
public String perform() {
- result.append( initial );
+ result.append( INITIAL );
while ( tokens.hasMoreTokens() ) {
token = tokens.nextToken();
@@ -134,7 +134,8 @@ public class BasicFormatterImpl implements Formatter {
t = tokens.nextToken();
token += t;
}
- while ( !"'".equals( t ) && tokens.hasMoreTokens() ); // cannot handle single quotes
+ // cannot handle single quotes
+ while ( !"'".equals( t ) && tokens.hasMoreTokens() );
}
else if ( "\"".equals( token ) ) {
String t;
@@ -384,16 +385,16 @@ public class BasicFormatterImpl implements Formatter {
}
private static boolean isWhitespace(String token) {
- return StringHelper.WHITESPACE.indexOf( token ) >= 0;
+ return StringHelper.WHITESPACE.contains( token );
}
private void newline() {
result.append( "\n" );
for ( int i = 0; i < indent; i++ ) {
- result.append( indentString );
+ result.append( INDENT_STRING );
}
beginLine = true;
}
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BinaryStreamImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BinaryStreamImpl.java
index b687105af4..be56516c4a 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BinaryStreamImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BinaryStreamImpl.java
@@ -37,6 +37,11 @@ import org.hibernate.engine.jdbc.BinaryStream;
public class BinaryStreamImpl extends ByteArrayInputStream implements BinaryStream {
private final int length;
+ /**
+ * Constructs a BinaryStreamImpl
+ *
+ * @param bytes The bytes to use backing the stream
+ */
public BinaryStreamImpl(byte[] bytes) {
super( bytes );
this.length = bytes.length;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/CharacterStreamImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/CharacterStreamImpl.java
index d61e07a4c5..ea13df4e82 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/CharacterStreamImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/CharacterStreamImpl.java
@@ -24,7 +24,6 @@
package org.hibernate.engine.jdbc.internal;
import java.io.IOException;
-import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
@@ -42,11 +41,22 @@ public class CharacterStreamImpl implements CharacterStream {
private Reader reader;
private String string;
+ /**
+ * Constructs a CharacterStreamImpl
+ *
+ * @param chars The String of characters to use backing the CharacterStream
+ */
public CharacterStreamImpl(String chars) {
this.string = chars;
this.length = chars.length();
}
+ /**
+ * Constructs a CharacterStreamImpl
+ *
+ * @param reader The Reader containing the characters to use backing the CharacterStream
+ * @param length The length of the stream
+ */
public CharacterStreamImpl(Reader reader, long length) {
this.reader = reader;
this.length = length;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/DDLFormatterImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/DDLFormatterImpl.java
index 538bbc4a16..4a923559d9 100755
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/DDLFormatterImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/DDLFormatterImpl.java
@@ -34,20 +34,16 @@ import org.hibernate.internal.util.StringHelper;
* @author Steve Ebersole
*/
public class DDLFormatterImpl implements Formatter {
+ /**
+ * Singleton access
+ */
public static final DDLFormatterImpl INSTANCE = new DDLFormatterImpl();
- /**
- * Format an SQL statement using simple rules
- * - Insert newline after each comma
- * - Indent three spaces after each inserted newline
- *
- * If the statement contains single/double quotes return unchanged,
- * it is too complex and could be broken by simple formatting.
- *
- * @param sql The statement to be fornmatted.
- */
+ @Override
public String format(String sql) {
- if ( StringHelper.isEmpty( sql ) ) return sql;
+ if ( StringHelper.isEmpty( sql ) ) {
+ return sql;
+ }
if ( sql.toLowerCase().startsWith( "create table" ) ) {
return formatCreateTable( sql );
}
@@ -63,12 +59,12 @@ public class DDLFormatterImpl implements Formatter {
}
private String formatCommentOn(String sql) {
- StringBuilder result = new StringBuilder( 60 ).append( "\n " );
- StringTokenizer tokens = new StringTokenizer( sql, " '[]\"", true );
+ final StringBuilder result = new StringBuilder( 60 ).append( "\n " );
+ final StringTokenizer tokens = new StringTokenizer( sql, " '[]\"", true );
boolean quoted = false;
while ( tokens.hasMoreTokens() ) {
- String token = tokens.nextToken();
+ final String token = tokens.nextToken();
result.append( token );
if ( isQuote( token ) ) {
quoted = !quoted;
@@ -84,12 +80,12 @@ public class DDLFormatterImpl implements Formatter {
}
private String formatAlterTable(String sql) {
- StringBuilder result = new StringBuilder( 60 ).append( "\n " );
- StringTokenizer tokens = new StringTokenizer( sql, " (,)'[]\"", true );
+ final StringBuilder result = new StringBuilder( 60 ).append( "\n " );
+ final StringTokenizer tokens = new StringTokenizer( sql, " (,)'[]\"", true );
boolean quoted = false;
while ( tokens.hasMoreTokens() ) {
- String token = tokens.nextToken();
+ final String token = tokens.nextToken();
if ( isQuote( token ) ) {
quoted = !quoted;
}
@@ -105,13 +101,13 @@ public class DDLFormatterImpl implements Formatter {
}
private String formatCreateTable(String sql) {
- StringBuilder result = new StringBuilder( 60 ).append( "\n " );
- StringTokenizer tokens = new StringTokenizer( sql, "(,)'[]\"", true );
+ final StringBuilder result = new StringBuilder( 60 ).append( "\n " );
+ final StringTokenizer tokens = new StringTokenizer( sql, "(,)'[]\"", true );
int depth = 0;
boolean quoted = false;
while ( tokens.hasMoreTokens() ) {
- String token = tokens.nextToken();
+ final String token = tokens.nextToken();
if ( isQuote( token ) ) {
quoted = !quoted;
result.append( token );
@@ -158,4 +154,4 @@ public class DDLFormatterImpl implements Formatter {
"'".equals( tok );
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/FormatStyle.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/FormatStyle.java
index 80a3e12f01..b077ede88b 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/FormatStyle.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/FormatStyle.java
@@ -23,16 +23,24 @@
*/
package org.hibernate.engine.jdbc.internal;
-
/**
* Represents the the understood types or styles of formatting.
*
* @author Steve Ebersole
*/
public enum FormatStyle {
+ /**
+ * Formatting for SELECT, INSERT, UPDATE and DELETE statements
+ */
BASIC( "basic", new BasicFormatterImpl() ),
- DDL( "ddl", new DDLFormatterImpl() ),
- NONE( "none", new NoFormatImpl() );
+ /**
+ * Formatting for DDL (CREATE, ALTER, DROP, etc) statements
+ */
+ DDL( "ddl", DDLFormatterImpl.INSTANCE ),
+ /**
+ * No formatting
+ */
+ NONE( "none", NoFormatImpl.INSTANCE );
private final String name;
private final Formatter formatter;
@@ -51,6 +59,11 @@ public enum FormatStyle {
}
private static class NoFormatImpl implements Formatter {
+ /**
+ * Singleton access
+ */
+ public static final NoFormatImpl INSTANCE = new NoFormatImpl();
+
public String format(String source) {
return source;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java
index 04265dff1f..1b2d710344 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java
@@ -68,8 +68,9 @@ import org.jboss.logging.Logger.Level;
* @author Brett Meyer
*/
public class JdbcCoordinatorImpl implements JdbcCoordinator {
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(
- CoreMessageLogger.class, JdbcCoordinatorImpl.class.getName()
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ JdbcCoordinatorImpl.class.getName()
);
private transient TransactionCoordinator transactionCoordinator;
@@ -90,6 +91,12 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
*/
private boolean releasesEnabled = true;
+ /**
+ * Constructs a JdbcCoordinatorImpl
+ *
+ * @param userSuppliedConnection The user supplied connection (may be null)
+ * @param transactionCoordinator The transaction coordinator
+ */
public JdbcCoordinatorImpl(
Connection userSuppliedConnection,
TransactionCoordinator transactionCoordinator) {
@@ -103,6 +110,12 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
this.exceptionHelper = logicalConnection.getJdbcServices().getSqlExceptionHelper();
}
+ /**
+ * Constructs a JdbcCoordinatorImpl
+ *
+ * @param logicalConnection The logical JDBC connection
+ * @param transactionCoordinator The transaction coordinator
+ */
public JdbcCoordinatorImpl(
LogicalConnectionImpl logicalConnection,
TransactionCoordinator transactionCoordinator) {
@@ -138,12 +151,17 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
return sessionFactory().getServiceRegistry().getService( BatchBuilder.class );
}
+ /**
+ * Access to the SqlExceptionHelper
+ *
+ * @return The SqlExceptionHelper
+ */
public SqlExceptionHelper sqlExceptionHelper() {
return transactionEnvironment().getJdbcServices().getSqlExceptionHelper();
}
- private int flushDepth = 0;
+ private int flushDepth;
@Override
public void flushBeginning() {
@@ -196,7 +214,8 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
public void executeBatch() {
if ( currentBatch != null ) {
currentBatch.execute();
- currentBatch.release(); // needed?
+ // needed?
+ currentBatch.release();
}
}
@@ -279,9 +298,9 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
@Override
public T coordinateWork(WorkExecutorVisitable work) {
- Connection connection = getLogicalConnection().getConnection();
+ final Connection connection = getLogicalConnection().getConnection();
try {
- T result = work.accept( new WorkExecutor(), connection );
+ final T result = work.accept( new WorkExecutor(), connection );
afterStatementExecution();
return result;
}
@@ -297,6 +316,13 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
: ! hasRegisteredResources();
}
+ /**
+ * JDK serialization hook
+ *
+ * @param oos The stream into which to write our state
+ *
+ * @throws IOException Trouble accessing the stream
+ */
public void serialize(ObjectOutputStream oos) throws IOException {
if ( ! isReadyForSerialization() ) {
throw new HibernateException( "Cannot serialize Session while connected" );
@@ -304,12 +330,28 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
logicalConnection.serialize( oos );
}
+ /**
+ * JDK deserialization hook
+ *
+ * @param ois The stream into which to write our state
+ * @param transactionContext The transaction context which owns the JdbcCoordinatorImpl to be deserialized.
+ *
+ * @return The deserialized JdbcCoordinatorImpl
+ *
+ * @throws IOException Trouble accessing the stream
+ * @throws ClassNotFoundException Trouble reading the stream
+ */
public static JdbcCoordinatorImpl deserialize(
ObjectInputStream ois,
TransactionContext transactionContext) throws IOException, ClassNotFoundException {
return new JdbcCoordinatorImpl( LogicalConnectionImpl.deserialize( ois, transactionContext ) );
- }
+ }
+ /**
+ * Callback after deserialization from Session is done
+ *
+ * @param transactionCoordinator The transaction coordinator
+ */
public void afterDeserialize(TransactionCoordinatorImpl transactionCoordinator) {
this.transactionCoordinator = transactionCoordinator;
}
@@ -328,7 +370,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
public void registerLastQuery(Statement statement) {
LOG.tracev( "Registering last query statement [{0}]", statement );
if ( statement instanceof JdbcWrapper ) {
- JdbcWrapper wrapper = ( JdbcWrapper ) statement;
+ final JdbcWrapper wrapper = (JdbcWrapper) statement;
registerLastQuery( wrapper.getWrappedObject() );
return;
}
@@ -343,10 +385,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
}
}
catch (SQLException sqle) {
- throw exceptionHelper.convert(
- sqle,
- "Cannot cancel query"
- );
+ throw exceptionHelper.convert( sqle, "Cannot cancel query" );
}
finally {
lastQuery = null;
@@ -356,7 +395,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
@Override
public void release(Statement statement) {
LOG.tracev( "Releasing statement [{0}]", statement );
- Set resultSets = xref.get( statement );
+ final Set resultSets = xref.get( statement );
if ( resultSets != null ) {
for ( ResultSet resultSet : resultSets ) {
close( resultSet );
@@ -411,7 +450,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
if ( LOG.isEnabled( Level.WARN ) && !xref.containsKey( statement ) ) {
LOG.unregisteredStatement();
}
- Set resultSets = xref.get( statement );
+ final Set resultSets = xref.get( statement );
if ( resultSets != null ) {
resultSets.remove( resultSet );
if ( resultSets.isEmpty() ) {
@@ -420,7 +459,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
}
}
else {
- boolean removed = unassociatedResultSets.remove( resultSet );
+ final boolean removed = unassociatedResultSets.remove( resultSet );
if ( !removed ) {
LOG.unregisteredResultSetWithoutStatement();
}
@@ -473,7 +512,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
LOG.tracev( "Closing prepared statement [{0}]", statement );
if ( statement instanceof InvalidatableWrapper ) {
- InvalidatableWrapper wrapper = ( InvalidatableWrapper ) statement;
+ final InvalidatableWrapper wrapper = (InvalidatableWrapper) statement;
close( wrapper.getWrappedObject() );
wrapper.invalidate();
return;
@@ -495,7 +534,8 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
if ( LOG.isDebugEnabled() ) {
LOG.debugf( "Exception clearing maxRows/queryTimeout [%s]", sqle.getMessage() );
}
- return; // EARLY EXIT!!!
+ // EARLY EXIT!!!
+ return;
}
statement.close();
if ( lastQuery == statement ) {
@@ -516,7 +556,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
LOG.tracev( "Closing result set [{0}]", resultSet );
if ( resultSet instanceof InvalidatableWrapper ) {
- InvalidatableWrapper wrapper = (InvalidatableWrapper) resultSet;
+ final InvalidatableWrapper wrapper = (InvalidatableWrapper) resultSet;
close( wrapper.getWrappedObject() );
wrapper.invalidate();
return;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java
index 3ded537eb0..5fc2418861 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java
@@ -69,7 +69,10 @@ import org.hibernate.service.spi.ServiceRegistryImplementor;
* @author Steve Ebersole
*/
public class JdbcServicesImpl implements JdbcServices, ServiceRegistryAwareService, Configurable {
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, JdbcServicesImpl.class.getName());
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ JdbcServicesImpl.class.getName()
+ );
private ServiceRegistryImplementor serviceRegistry;
@@ -105,7 +108,7 @@ public class JdbcServicesImpl implements JdbcServices, ServiceRegistryAwareServi
boolean lobLocatorUpdateCopy = false;
String catalogName = null;
String schemaName = null;
- LinkedHashSet typeInfoSet = new LinkedHashSet();
+ final LinkedHashSet typeInfoSet = new LinkedHashSet();
// 'hibernate.temp.use_jdbc_metadata_defaults' is a temporary magic value.
// The need for it is intended to be alleviated with future development, thus it is
@@ -114,10 +117,10 @@ public class JdbcServicesImpl implements JdbcServices, ServiceRegistryAwareServi
// it is used to control whether we should consult the JDBC metadata to determine
// certain Settings default values; it is useful to *not* do this when the database
// may not be available (mainly in tools usage).
- boolean useJdbcMetadata = ConfigurationHelper.getBoolean( "hibernate.temp.use_jdbc_metadata_defaults", configValues, true );
+ final boolean useJdbcMetadata = ConfigurationHelper.getBoolean( "hibernate.temp.use_jdbc_metadata_defaults", configValues, true );
if ( useJdbcMetadata ) {
try {
- Connection connection = jdbcConnectionAccess.obtainConnection();
+ final Connection connection = jdbcConnectionAccess.obtainConnection();
try {
DatabaseMetaData meta = connection.getMetaData();
if(LOG.isDebugEnabled()) {
@@ -151,7 +154,7 @@ public class JdbcServicesImpl implements JdbcServices, ServiceRegistryAwareServi
dialect = dialectFactory.buildDialect( configValues, connection );
catalogName = connection.getCatalog();
- SchemaNameResolver schemaNameResolver = determineExplicitSchemaNameResolver( configValues );
+ final SchemaNameResolver schemaNameResolver = determineExplicitSchemaNameResolver( configValues );
if ( schemaNameResolver == null ) {
// todo : add dialect method
// schemaNameResolver = dialect.getSchemaNameResolver();
@@ -284,19 +287,23 @@ public class JdbcServicesImpl implements JdbcServices, ServiceRegistryAwareServi
}
- // todo : add to Environment
+ /**
+ * A constant naming the setting used to identify the {@link SchemaNameResolver} to use
+ *
+ * TODO : add to Environment
+ */
public static final String SCHEMA_NAME_RESOLVER = "hibernate.schema_name_resolver";
private SchemaNameResolver determineExplicitSchemaNameResolver(Map configValues) {
- Object setting = configValues.get( SCHEMA_NAME_RESOLVER );
+ final Object setting = configValues.get( SCHEMA_NAME_RESOLVER );
if ( SchemaNameResolver.class.isInstance( setting ) ) {
return (SchemaNameResolver) setting;
}
- String resolverClassName = (String) setting;
+ final String resolverClassName = (String) setting;
if ( resolverClassName != null ) {
try {
- Class resolverClass = ReflectHelper.classForName( resolverClassName, getClass() );
+ final Class resolverClass = ReflectHelper.classForName( resolverClassName, getClass() );
return (SchemaNameResolver) ReflectHelper.getDefaultConstructor( resolverClass ).newInstance();
}
catch ( ClassNotFoundException e ) {
@@ -313,7 +320,7 @@ public class JdbcServicesImpl implements JdbcServices, ServiceRegistryAwareServi
}
private Set parseKeywords(String extraKeywordsString) {
- Set keywordSet = new HashSet();
+ final Set keywordSet = new HashSet();
keywordSet.addAll( Arrays.asList( extraKeywordsString.split( "," ) ) );
return keywordSet;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesInitiator.java
index a1704b075a..e415763bca 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesInitiator.java
@@ -32,11 +32,14 @@ import org.hibernate.service.spi.ServiceRegistryImplementor;
/**
* Standard initiator for the standard {@link JdbcServices} service
*
- * @todo : should this maybe be a SessionFactory service?
+ * TODO : should this maybe be a SessionFactory service?
*
* @author Steve Ebersole
*/
public class JdbcServicesInitiator implements StandardServiceInitiator {
+ /**
+ * Singleton access
+ */
public static final JdbcServicesInitiator INSTANCE = new JdbcServicesInitiator();
@Override
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LobCreatorBuilder.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LobCreatorBuilder.java
index 6cf56a08cb..b25b60cee0 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LobCreatorBuilder.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LobCreatorBuilder.java
@@ -45,15 +45,17 @@ import org.hibernate.internal.util.config.ConfigurationHelper;
* @author Steve Ebersole
*/
public class LobCreatorBuilder {
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ LobCreatorBuilder.class.getName()
+ );
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, LobCreatorBuilder.class.getName());
-
- private boolean useContextualLobCreation;
+ private boolean useContextualLobCreation;
/**
* The public factory method for obtaining the appropriate (according to given JDBC {@link java.sql.Connection}.
*
- *
+ * @param configValues The map of settings
* @param jdbcConnection A JDBC {@link java.sql.Connection} which can be used to gauge the drivers level of support,
* specifically for creating LOB references.
*/
@@ -74,8 +76,9 @@ public class LobCreatorBuilder {
*
* @return True if the connection can be used to create LOBs; false otherwise.
*/
+ @SuppressWarnings("unchecked")
private static boolean useContextualLobCreation(Map configValues, Connection jdbcConnection) {
- boolean isNonContextualLobCreationRequired =
+ final boolean isNonContextualLobCreationRequired =
ConfigurationHelper.getBoolean( Environment.NON_CONTEXTUAL_LOB_CREATION, configValues );
if ( isNonContextualLobCreationRequired ) {
LOG.disablingContextualLOBCreation( Environment.NON_CONTEXTUAL_LOB_CREATION );
@@ -88,7 +91,7 @@ public class LobCreatorBuilder {
try {
try {
- DatabaseMetaData meta = jdbcConnection.getMetaData();
+ final DatabaseMetaData meta = jdbcConnection.getMetaData();
// if the jdbc driver version is less than 4, it shouldn't have createClob
if ( meta.getJDBCMajorVersion() < 4 ) {
LOG.disablingContextualLOBCreationSinceOldJdbcVersion( meta.getJDBCMajorVersion() );
@@ -99,16 +102,16 @@ public class LobCreatorBuilder {
// ignore exception and continue
}
- Class connectionClass = Connection.class;
- Method createClobMethod = connectionClass.getMethod( "createClob", NO_ARG_SIG );
+ final Class connectionClass = Connection.class;
+ final Method createClobMethod = connectionClass.getMethod( "createClob", NO_ARG_SIG );
if ( createClobMethod.getDeclaringClass().equals( Connection.class ) ) {
// If we get here we are running in a jdk 1.6 (jdbc 4) environment...
// Further check to make sure the driver actually implements the LOB creation methods. We
// check against createClob() as indicative of all; should we check against all 3 explicitly?
try {
- Object clob = createClobMethod.invoke( jdbcConnection, NO_ARGS );
+ final Object clob = createClobMethod.invoke( jdbcConnection, NO_ARGS );
try {
- Method freeMethod = clob.getClass().getMethod( "free", NO_ARG_SIG );
+ final Method freeMethod = clob.getClass().getMethod( "free", NO_ARG_SIG );
freeMethod.invoke( clob, NO_ARGS );
}
catch ( Throwable ignore ) {
@@ -127,6 +130,13 @@ public class LobCreatorBuilder {
return false;
}
+ /**
+ * Build a LobCreator using the given context
+ *
+ * @param lobCreationContext The LOB creation context
+ *
+ * @return The LobCreator
+ */
public LobCreator buildLobCreator(LobCreationContext lobCreationContext) {
return useContextualLobCreation
? new ContextualLobCreator( lobCreationContext )
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java
index 7ec86aad5f..d718aeb73b 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java
@@ -54,8 +54,10 @@ import org.jboss.logging.Logger;
* @author Brett Meyer
*/
public class LogicalConnectionImpl implements LogicalConnectionImplementor {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, LogicalConnectionImpl.class.getName() );
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ LogicalConnectionImpl.class.getName()
+ );
private transient Connection physicalConnection;
@@ -68,6 +70,14 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
private boolean isClosed;
+ /**
+ * Constructs a LogicalConnectionImpl
+ *
+ * @param userSuppliedConnection The user-supplied connection
+ * @param connectionReleaseMode The connection release mode to use
+ * @param jdbcServices JdbcServices
+ * @param jdbcConnectionAccess JDBC Connection access
+ */
public LogicalConnectionImpl(
Connection userSuppliedConnection,
ConnectionReleaseMode connectionReleaseMode,
@@ -84,6 +94,9 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
this.physicalConnection = userSuppliedConnection;
}
+ /**
+ * Constructs a LogicalConnectionImpl. This for used from deserialization
+ */
private LogicalConnectionImpl(
ConnectionReleaseMode connectionReleaseMode,
JdbcServices jdbcServices,
@@ -162,7 +175,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
@Override
public Connection close() {
LOG.trace( "Closing logical connection" );
- Connection c = isUserSuppliedConnection ? physicalConnection : null;
+ final Connection c = isUserSuppliedConnection ? physicalConnection : null;
try {
if ( !isUserSuppliedConnection && physicalConnection != null ) {
releaseConnection();
@@ -255,7 +268,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
}
private void releaseNonDurableObservers() {
- Iterator observers = this.observers.iterator();
+ final Iterator observers = this.observers.iterator();
while ( observers.hasNext() ) {
if ( NonDurableConnectionObserver.class.isInstance( observers.next() ) ) {
observers.remove();
@@ -268,7 +281,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
if ( isClosed ) {
throw new IllegalStateException( "cannot manually disconnect because logical connection is already closed" );
}
- Connection c = physicalConnection;
+ final Connection c = physicalConnection;
releaseConnection();
return c;
}
@@ -324,10 +337,17 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
}
}
+ /**
+ * Serialization hook
+ *
+ * @param oos The stream to write out state to
+ *
+ * @throws IOException Problem accessing stream
+ */
public void serialize(ObjectOutputStream oos) throws IOException {
oos.writeBoolean( isUserSuppliedConnection );
oos.writeBoolean( isClosed );
- List durableConnectionObservers = new ArrayList();
+ final List durableConnectionObservers = new ArrayList();
for ( ConnectionObserver observer : observers ) {
if ( ! NonDurableConnectionObserver.class.isInstance( observer ) ) {
durableConnectionObservers.add( observer );
@@ -339,13 +359,24 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
}
}
+ /**
+ * Deserialization hook
+ *
+ * @param ois The stream to read our state from
+ * @param transactionContext The transactionContext which owns this logical connection
+ *
+ * @return The deserialized LogicalConnectionImpl
+ *
+ * @throws IOException Trouble accessing the stream
+ * @throws ClassNotFoundException Trouble reading the stream
+ */
public static LogicalConnectionImpl deserialize(
ObjectInputStream ois,
TransactionContext transactionContext) throws IOException, ClassNotFoundException {
- boolean isUserSuppliedConnection = ois.readBoolean();
- boolean isClosed = ois.readBoolean();
- int observerCount = ois.readInt();
- List observers = CollectionHelper.arrayList( observerCount );
+ final boolean isUserSuppliedConnection = ois.readBoolean();
+ final boolean isClosed = ois.readBoolean();
+ final int observerCount = ois.readInt();
+ final List observers = CollectionHelper.arrayList( observerCount );
for ( int i = 0; i < observerCount; i++ ) {
observers.add( (ConnectionObserver) ois.readObject() );
}
@@ -357,5 +388,5 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
isClosed,
observers
);
- }
+ }
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetReturnImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetReturnImpl.java
index d51e2fd034..36caece313 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetReturnImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetReturnImpl.java
@@ -31,12 +31,18 @@ import org.hibernate.engine.jdbc.spi.ResultSetReturn;
import org.hibernate.engine.jdbc.spi.SqlExceptionHelper;
/**
+ * Standard implementation of the ResultSetReturn contract
+ *
* @author Brett Meyer
*/
public class ResultSetReturnImpl implements ResultSetReturn {
-
private final JdbcCoordinator jdbcCoordinator;
+ /**
+ * Constructs a ResultSetReturnImpl
+ *
+ * @param jdbcCoordinator The JdbcCoordinator
+ */
public ResultSetReturnImpl(JdbcCoordinator jdbcCoordinator) {
this.jdbcCoordinator = jdbcCoordinator;
}
@@ -49,11 +55,11 @@ public class ResultSetReturnImpl implements ResultSetReturn {
// this seems needless, Oracle can return an
// OracleCallableStatementWrapper that finds its way to this method,
// rather than extract(CallableStatement). See HHH-8022.
- CallableStatement callableStatement = (CallableStatement) statement;
+ final CallableStatement callableStatement = (CallableStatement) statement;
return extract( callableStatement );
}
try {
- ResultSet rs = statement.executeQuery();
+ final ResultSet rs = statement.executeQuery();
postExtract( rs, statement );
return rs;
}
@@ -66,8 +72,10 @@ public class ResultSetReturnImpl implements ResultSetReturn {
public ResultSet extract(CallableStatement statement) {
try {
// sql logged by StatementPreparerImpl
- ResultSet rs = jdbcCoordinator.getLogicalConnection().getJdbcServices()
- .getDialect().getResultSet( statement );
+ final ResultSet rs = jdbcCoordinator.getLogicalConnection()
+ .getJdbcServices()
+ .getDialect()
+ .getResultSet( statement );
postExtract( rs, statement );
return rs;
}
@@ -78,10 +86,9 @@ public class ResultSetReturnImpl implements ResultSetReturn {
@Override
public ResultSet extract(Statement statement, String sql) {
- jdbcCoordinator.getLogicalConnection().getJdbcServices()
- .getSqlStatementLogger().logStatement( sql );
+ jdbcCoordinator.getLogicalConnection().getJdbcServices().getSqlStatementLogger().logStatement( sql );
try {
- ResultSet rs = statement.executeQuery( sql );
+ final ResultSet rs = statement.executeQuery( sql );
postExtract( rs, statement );
return rs;
}
@@ -99,7 +106,7 @@ public class ResultSetReturnImpl implements ResultSetReturn {
// do nothing until we hit the resultset
}
}
- ResultSet rs = statement.getResultSet();
+ final ResultSet rs = statement.getResultSet();
postExtract( rs, statement );
return rs;
}
@@ -118,7 +125,7 @@ public class ResultSetReturnImpl implements ResultSetReturn {
// do nothing until we hit the resultset
}
}
- ResultSet rs = statement.getResultSet();
+ final ResultSet rs = statement.getResultSet();
postExtract( rs, statement );
return rs;
}
@@ -149,7 +156,7 @@ public class ResultSetReturnImpl implements ResultSetReturn {
}
}
- private final SqlExceptionHelper sqlExceptionHelper() {
+ private SqlExceptionHelper sqlExceptionHelper() {
return jdbcCoordinator.getTransactionCoordinator()
.getTransactionContext()
.getTransactionEnvironment()
@@ -158,7 +165,9 @@ public class ResultSetReturnImpl implements ResultSetReturn {
}
private void postExtract(ResultSet rs, Statement st) {
- if ( rs != null ) jdbcCoordinator.register( rs, st );
+ if ( rs != null ) {
+ jdbcCoordinator.register( rs, st );
+ }
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java
index b76819aced..11d7ee3d49 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java
@@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.engine.jdbc.internal;
+
import java.sql.ResultSet;
import org.hibernate.engine.jdbc.ColumnNameCache;
@@ -35,15 +36,16 @@ import org.hibernate.engine.jdbc.spi.ResultSetWrapper;
* @author Gail Badner
*/
public class ResultSetWrapperImpl implements ResultSetWrapper {
+ /**
+ * Singleton access
+ */
public static ResultSetWrapper INSTANCE = new ResultSetWrapperImpl();
private ResultSetWrapperImpl() {
}
- /**
- * {@inheritDoc}
- */
+ @Override
public ResultSet wrap(ResultSet resultSet, ColumnNameCache columnNameCache) {
return ResultSetWrapperProxy.generateProxy( resultSet, columnNameCache );
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparerImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparerImpl.java
index ef579209c4..f7ca3a1340 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparerImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparerImpl.java
@@ -37,6 +37,8 @@ import org.hibernate.engine.jdbc.spi.SqlExceptionHelper;
import org.hibernate.engine.jdbc.spi.StatementPreparer;
/**
+ * Standard implementation of StatementPreparer
+ *
* @author Steve Ebersole
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
* @author Brett Meyer
@@ -44,6 +46,11 @@ import org.hibernate.engine.jdbc.spi.StatementPreparer;
class StatementPreparerImpl implements StatementPreparer {
private JdbcCoordinatorImpl jdbcCoordinator;
+ /**
+ * Construct a StatementPreparerImpl
+ *
+ * @param jdbcCoordinator The JdbcCoordinatorImpl
+ */
StatementPreparerImpl(JdbcCoordinatorImpl jdbcCoordinator) {
this.jdbcCoordinator = jdbcCoordinator;
}
@@ -71,7 +78,7 @@ class StatementPreparerImpl implements StatementPreparer {
@Override
public Statement createStatement() {
try {
- Statement statement = connection().createStatement();
+ final Statement statement = connection().createStatement();
jdbcCoordinator.register( statement );
return statement;
}
@@ -141,22 +148,18 @@ class StatementPreparerImpl implements StatementPreparer {
if ( ! settings().isScrollableResultSetsEnabled() ) {
throw new AssertionFailure("scrollable result sets are not enabled");
}
- PreparedStatement ps = new QueryStatementPreparationTemplate( sql ) {
+ final PreparedStatement ps = new QueryStatementPreparationTemplate( sql ) {
public PreparedStatement doPrepare() throws SQLException {
return isCallable
- ? connection().prepareCall(
- sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY
- )
- : connection().prepareStatement(
- sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY
- );
+ ? connection().prepareCall( sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY )
+ : connection().prepareStatement( sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY );
}
}.prepareStatement();
jdbcCoordinator.registerLastQuery( ps );
return ps;
}
else {
- PreparedStatement ps = new QueryStatementPreparationTemplate( sql ) {
+ final PreparedStatement ps = new QueryStatementPreparationTemplate( sql ) {
public PreparedStatement doPrepare() throws SQLException {
return isCallable
? connection().prepareCall( sql )
@@ -179,7 +182,7 @@ class StatementPreparerImpl implements StatementPreparer {
try {
jdbcCoordinator.getLogicalConnection().getJdbcServices().getSqlStatementLogger().logStatement( sql );
- PreparedStatement preparedStatement = doPrepare();
+ final PreparedStatement preparedStatement = doPrepare();
setStatementTimeout( preparedStatement );
postProcess( preparedStatement );
return preparedStatement;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/package-info.java
new file mode 100644
index 0000000000..a83fec0f71
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Internals for supporting various aspects of JDBC interaction
+ */
+package org.hibernate.engine.jdbc.internal;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/package-info.java
new file mode 100644
index 0000000000..c55e445fdc
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * SPI contracts for supporting various aspects of JDBC interaction
+ */
+package org.hibernate.engine.jdbc.spi;
From d2ec51489443672d47690fbaea6ca631335e574f Mon Sep 17 00:00:00 2001
From: Steve Ebersole
Date: Tue, 30 Apr 2013 08:07:24 -0500
Subject: [PATCH 28/57] HHH-8159 - Apply fixups indicated by analysis tools
---
build.gradle | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/build.gradle b/build.gradle
index dcedcdd7db..8b27b237e1 100644
--- a/build.gradle
+++ b/build.gradle
@@ -349,8 +349,12 @@ subprojects { subProject ->
checkstyleMain.exclude '**/org/hibernate/cfg/*'
findbugs {
+ sourceSets = [ subProject.sourceSets.main, subProject.sourceSets.test ]
ignoreFailures = true
}
+ // exclude generated sources
+ findbugsMain.exclude '**/generated-src/**'
+
buildDashboard.dependsOn check
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
From 9b37f2a297ddf264828a52734a0cf597e429327a Mon Sep 17 00:00:00 2001
From: Steve Ebersole
Date: Tue, 30 Apr 2013 08:29:06 -0500
Subject: [PATCH 29/57] HHH-8159 - Apply fixups indicated by analysis tools
---
.../c3p0/internal/C3P0ConnectionProvider.java | 132 ++++++++++--------
.../c3p0/internal/C3P0MessageLogger.java | 63 ++++++---
.../StrategyRegistrationProviderImpl.java | 12 +-
.../hibernate/c3p0/internal/package-info.java | 4 +
4 files changed, 130 insertions(+), 81 deletions(-)
create mode 100644 hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/package-info.java
diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java
index f3b3498586..d1745cc25d 100644
--- a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java
+++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java
@@ -31,6 +31,7 @@ import java.util.Properties;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.DataSources;
+
import org.jboss.logging.Logger;
import org.hibernate.HibernateException;
@@ -53,25 +54,28 @@ import org.hibernate.service.spi.Stoppable;
* @author various people
* @see ConnectionProvider
*/
-public class C3P0ConnectionProvider
+public class C3P0ConnectionProvider
implements ConnectionProvider, Configurable, Stoppable, ServiceRegistryAwareService {
- private static final C3P0MessageLogger LOG = Logger.getMessageLogger(C3P0MessageLogger.class, C3P0ConnectionProvider.class.getName());
+ private static final C3P0MessageLogger LOG = Logger.getMessageLogger(
+ C3P0MessageLogger.class,
+ C3P0ConnectionProvider.class.getName()
+ );
//swaldman 2006-08-28: define c3p0-style configuration parameters for properties with
// hibernate-specific overrides to detect and warn about conflicting
// declarations
- private final static String C3P0_STYLE_MIN_POOL_SIZE = "c3p0.minPoolSize";
- private final static String C3P0_STYLE_MAX_POOL_SIZE = "c3p0.maxPoolSize";
- private final static String C3P0_STYLE_MAX_IDLE_TIME = "c3p0.maxIdleTime";
- private final static String C3P0_STYLE_MAX_STATEMENTS = "c3p0.maxStatements";
- private final static String C3P0_STYLE_ACQUIRE_INCREMENT = "c3p0.acquireIncrement";
- private final static String C3P0_STYLE_IDLE_CONNECTION_TEST_PERIOD = "c3p0.idleConnectionTestPeriod";
+ private static final String C3P0_STYLE_MIN_POOL_SIZE = "c3p0.minPoolSize";
+ private static final String C3P0_STYLE_MAX_POOL_SIZE = "c3p0.maxPoolSize";
+ private static final String C3P0_STYLE_MAX_IDLE_TIME = "c3p0.maxIdleTime";
+ private static final String C3P0_STYLE_MAX_STATEMENTS = "c3p0.maxStatements";
+ private static final String C3P0_STYLE_ACQUIRE_INCREMENT = "c3p0.acquireIncrement";
+ private static final String C3P0_STYLE_IDLE_CONNECTION_TEST_PERIOD = "c3p0.idleConnectionTestPeriod";
//swaldman 2006-08-28: define c3p0-style configuration parameters for initialPoolSize, which
// hibernate sensibly lets default to minPoolSize, but we'll let users
// override it with the c3p0-style property if they want.
- private final static String C3P0_STYLE_INITIAL_POOL_SIZE = "c3p0.initialPoolSize";
+ private static final String C3P0_STYLE_INITIAL_POOL_SIZE = "c3p0.initialPoolSize";
private DataSource ds;
private Integer isolation;
@@ -105,7 +109,7 @@ public class C3P0ConnectionProvider
}
@Override
- @SuppressWarnings( {"unchecked"})
+ @SuppressWarnings({"unchecked"})
public T unwrap(Class unwrapType) {
if ( ConnectionProvider.class.equals( unwrapType ) ||
C3P0ConnectionProvider.class.isAssignableFrom( unwrapType ) ) {
@@ -120,46 +124,46 @@ public class C3P0ConnectionProvider
}
@Override
- @SuppressWarnings( {"unchecked"})
+ @SuppressWarnings({"unchecked"})
public void configure(Map props) {
- String jdbcDriverClass = (String) props.get( Environment.DRIVER );
- String jdbcUrl = (String) props.get( Environment.URL );
- Properties connectionProps = ConnectionProviderInitiator.getConnectionProperties( props );
+ final String jdbcDriverClass = (String) props.get( Environment.DRIVER );
+ final String jdbcUrl = (String) props.get( Environment.URL );
+ final Properties connectionProps = ConnectionProviderInitiator.getConnectionProperties( props );
- LOG.c3p0UsingDriver(jdbcDriverClass, jdbcUrl);
- LOG.connectionProperties(ConfigurationHelper.maskOut(connectionProps, "password"));
+ LOG.c3p0UsingDriver( jdbcDriverClass, jdbcUrl );
+ LOG.connectionProperties( ConfigurationHelper.maskOut( connectionProps, "password" ) );
autocommit = ConfigurationHelper.getBoolean( Environment.AUTOCOMMIT, props );
- LOG.autoCommitMode( autocommit );
+ LOG.autoCommitMode( autocommit );
- if (jdbcDriverClass == null) {
- LOG.jdbcDriverNotSpecified(Environment.DRIVER);
+ if ( jdbcDriverClass == null ) {
+ LOG.jdbcDriverNotSpecified( Environment.DRIVER );
}
else {
try {
serviceRegistry.getService( ClassLoaderService.class ).classForName( jdbcDriverClass );
}
- catch ( ClassLoadingException e ) {
- throw new ClassLoadingException( LOG.jdbcDriverNotFound(jdbcDriverClass), e );
+ catch (ClassLoadingException e) {
+ throw new ClassLoadingException( LOG.jdbcDriverNotFound( jdbcDriverClass ), e );
}
}
try {
//swaldman 2004-02-07: modify to allow null values to signify fall through to c3p0 PoolConfig defaults
- Integer minPoolSize = ConfigurationHelper.getInteger( Environment.C3P0_MIN_SIZE, props );
- Integer maxPoolSize = ConfigurationHelper.getInteger( Environment.C3P0_MAX_SIZE, props );
- Integer maxIdleTime = ConfigurationHelper.getInteger( Environment.C3P0_TIMEOUT, props );
- Integer maxStatements = ConfigurationHelper.getInteger( Environment.C3P0_MAX_STATEMENTS, props );
- Integer acquireIncrement = ConfigurationHelper.getInteger( Environment.C3P0_ACQUIRE_INCREMENT, props );
- Integer idleTestPeriod = ConfigurationHelper.getInteger( Environment.C3P0_IDLE_TEST_PERIOD, props );
+ final Integer minPoolSize = ConfigurationHelper.getInteger( Environment.C3P0_MIN_SIZE, props );
+ final Integer maxPoolSize = ConfigurationHelper.getInteger( Environment.C3P0_MAX_SIZE, props );
+ final Integer maxIdleTime = ConfigurationHelper.getInteger( Environment.C3P0_TIMEOUT, props );
+ final Integer maxStatements = ConfigurationHelper.getInteger( Environment.C3P0_MAX_STATEMENTS, props );
+ final Integer acquireIncrement = ConfigurationHelper.getInteger( Environment.C3P0_ACQUIRE_INCREMENT, props );
+ final Integer idleTestPeriod = ConfigurationHelper.getInteger( Environment.C3P0_IDLE_TEST_PERIOD, props );
- Properties c3props = new Properties();
+ final Properties c3props = new Properties();
// turn hibernate.c3p0.* into c3p0.*, so c3p0
// gets a chance to see all hibernate.c3p0.*
for ( Object o : props.keySet() ) {
- if ( ! String.class.isInstance( o ) ) {
+ if ( !String.class.isInstance( o ) ) {
continue;
}
final String key = (String) o;
@@ -182,63 +186,62 @@ public class C3P0ConnectionProvider
Environment.C3P0_ACQUIRE_INCREMENT, C3P0_STYLE_ACQUIRE_INCREMENT, props, c3props, acquireIncrement
);
setOverwriteProperty(
- Environment.C3P0_IDLE_TEST_PERIOD, C3P0_STYLE_IDLE_CONNECTION_TEST_PERIOD, props, c3props, idleTestPeriod
+ Environment.C3P0_IDLE_TEST_PERIOD,
+ C3P0_STYLE_IDLE_CONNECTION_TEST_PERIOD,
+ props,
+ c3props,
+ idleTestPeriod
);
// revert to traditional hibernate behavior of setting initialPoolSize to minPoolSize
// unless otherwise specified with a c3p0.*-style parameter.
- Integer initialPoolSize = ConfigurationHelper.getInteger( C3P0_STYLE_INITIAL_POOL_SIZE, props );
+ final Integer initialPoolSize = ConfigurationHelper.getInteger( C3P0_STYLE_INITIAL_POOL_SIZE, props );
if ( initialPoolSize == null && minPoolSize != null ) {
c3props.put( C3P0_STYLE_INITIAL_POOL_SIZE, String.valueOf( minPoolSize ).trim() );
}
- /*DataSource unpooled = DataSources.unpooledDataSource(
- jdbcUrl, props.getProperty(Environment.USER), props.getProperty(Environment.PASS)
- );*/
- DataSource unpooled = DataSources.unpooledDataSource( jdbcUrl, connectionProps );
+ final DataSource unpooled = DataSources.unpooledDataSource( jdbcUrl, connectionProps );
- Map allProps = new HashMap();
+ final Map allProps = new HashMap();
allProps.putAll( props );
allProps.putAll( c3props );
ds = DataSources.pooledDataSource( unpooled, allProps );
}
- catch ( Exception e ) {
- LOG.error(LOG.unableToInstantiateC3p0ConnectionPool(), e);
- throw new HibernateException(LOG.unableToInstantiateC3p0ConnectionPool(), e);
+ catch (Exception e) {
+ LOG.error( LOG.unableToInstantiateC3p0ConnectionPool(), e );
+ throw new HibernateException( LOG.unableToInstantiateC3p0ConnectionPool(), e );
}
- String i = (String) props.get( Environment.ISOLATION );
- if (i == null) isolation = null;
+ final String i = (String) props.get( Environment.ISOLATION );
+ if ( i == null ) {
+ isolation = null;
+ }
else {
isolation = Integer.valueOf( i );
- LOG.jdbcIsolationLevel(Environment.isolationLevelToString(isolation));
+ LOG.jdbcIsolationLevel( Environment.isolationLevelToString( isolation ) );
}
}
- public void close() {
- try {
- DataSources.destroy( ds );
- }
- catch ( SQLException sqle ) {
- LOG.unableToDestroyC3p0ConnectionPool(sqle);
- }
- }
-
@Override
public boolean supportsAggressiveRelease() {
return false;
}
- private void setOverwriteProperty(String hibernateStyleKey, String c3p0StyleKey, Map hibp, Properties c3p, Integer value) {
+ private void setOverwriteProperty(
+ String hibernateStyleKey,
+ String c3p0StyleKey,
+ Map hibp,
+ Properties c3p,
+ Integer value) {
if ( value != null ) {
- String peeledC3p0Key = c3p0StyleKey.substring(5);
+ final String peeledC3p0Key = c3p0StyleKey.substring( 5 );
c3p.put( peeledC3p0Key, String.valueOf( value ).trim() );
- if ( hibp.containsKey( c3p0StyleKey ) ) {
+ if ( hibp.containsKey( c3p0StyleKey ) ) {
warnPropertyConflict( hibernateStyleKey, c3p0StyleKey );
}
- String longC3p0StyleKey = "hibernate." + c3p0StyleKey;
+ final String longC3p0StyleKey = "hibernate." + c3p0StyleKey;
if ( hibp.containsKey( longC3p0StyleKey ) ) {
warnPropertyConflict( hibernateStyleKey, longC3p0StyleKey );
}
@@ -246,12 +249,27 @@ public class C3P0ConnectionProvider
}
private void warnPropertyConflict(String hibernateStyle, String c3p0Style) {
- LOG.bothHibernateAndC3p0StylesSet(hibernateStyle, c3p0Style, hibernateStyle, c3p0Style);
+ LOG.bothHibernateAndC3p0StylesSet( hibernateStyle, c3p0Style, hibernateStyle, c3p0Style );
}
@Override
public void stop() {
- close();
+ try {
+ DataSources.destroy( ds );
+ }
+ catch (SQLException sqle) {
+ LOG.unableToDestroyC3p0ConnectionPool( sqle );
+ }
+ }
+
+ /**
+ * Close the provider.
+ *
+ * @deprecated Use {@link #stop} instead
+ */
+ @Deprecated
+ public void close() {
+ stop();
}
@Override
diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java
index 0f37a41e29..5adf334635 100644
--- a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java
+++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java
@@ -41,29 +41,54 @@ import static org.jboss.logging.Logger.Level.WARN;
*
* New messages must be added after the last message defined to ensure message codes are unique.
*/
-@MessageLogger( projectCode = "HHH" )
+@MessageLogger(projectCode = "HHH")
public interface C3P0MessageLogger extends CoreMessageLogger {
- @LogMessage( level = WARN )
- @Message( value = "Both hibernate-style property '%s' and c3p0-style property '%s' have been set in hibernate.properties. "
- + "Hibernate-style property '%s' will be used and c3p0-style property '%s' will be ignored!", id = 10001 )
- void bothHibernateAndC3p0StylesSet( String hibernateStyle,
- String c3p0Style,
- String hibernateStyle2,
- String c3p0Style2 );
+ /**
+ * Log a message (WARN) about conflicting {@code hibernate.c3p0.XYZ} and {@code c3p0.XYZ} settings
+ *
+ * @param hibernateStyle The {@code hibernate.c3p0} prefixed setting
+ * @param c3p0Style The {@code c3p0.} prefixed setting
+ */
+ @LogMessage(level = WARN)
+ @Message(value = "Both hibernate-style property '%1$s' and c3p0-style property '%2$s' have been set in Hibernate "
+ + "properties. Hibernate-style property '%1$s' will be used and c3p0-style property '2$%s' will be ignored!", id = 10001)
+ void bothHibernateAndC3p0StylesSet(String hibernateStyle,String c3p0Style);
- @LogMessage( level = INFO )
- @Message( value = "C3P0 using driver: %s at URL: %s", id = 10002 )
- void c3p0UsingDriver( String jdbcDriverClass,
- String jdbcUrl );
+ /**
+ * Log a message (INFO) about which Driver class is being used.
+ *
+ * @param jdbcDriverClass The JDBC Driver class
+ * @param jdbcUrl The JDBC URL
+ */
+ @LogMessage(level = INFO)
+ @Message(value = "C3P0 using driver: %s at URL: %s", id = 10002)
+ void c3p0UsingDriver(String jdbcDriverClass, String jdbcUrl);
- @Message( value = "JDBC Driver class not found: %s", id = 10003 )
- String jdbcDriverNotFound( String jdbcDriverClass );
+ /**
+ * Build a message about not being able to find the JDBC driver class
+ *
+ * @param jdbcDriverClass The JDBC driver class we could not find
+ *
+ * @return The message
+ */
+ @Message(value = "JDBC Driver class not found: %s", id = 10003)
+ String jdbcDriverNotFound(String jdbcDriverClass);
- @LogMessage( level = WARN )
- @Message( value = "Could not destroy C3P0 connection pool", id = 10004 )
- void unableToDestroyC3p0ConnectionPool( @Cause SQLException e );
+ /**
+ * Log a message (WARN) about not being able to stop the underlying c3p0 pool.
+ *
+ * @param e The exception when we tried to stop pool
+ */
+ @LogMessage(level = WARN)
+ @Message(value = "Could not destroy C3P0 connection pool", id = 10004)
+ void unableToDestroyC3p0ConnectionPool(@Cause SQLException e);
- @Message( value = "Could not instantiate C3P0 connection pool", id = 10005 )
- String unableToInstantiateC3p0ConnectionPool();
+ /**
+ * Build a message about not being able to start the underlying c3p0 pool.
+ *
+ * @return The message
+ */
+ @Message(value = "Could not instantiate C3P0 connection pool", id = 10005)
+ String unableToInstantiateC3p0ConnectionPool();
}
diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java
index 4237221181..b1b98bd9c5 100644
--- a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java
+++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java
@@ -38,16 +38,18 @@ import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
* @author Brett Meyer
*/
public class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider {
-
private static final List REGISTRATIONS = Collections.singletonList(
- (StrategyRegistration) new SimpleStrategyRegistrationImpl(
+ (StrategyRegistration) new SimpleStrategyRegistrationImpl(
ConnectionProvider.class,
C3P0ConnectionProvider.class,
"c3p0",
C3P0ConnectionProvider.class.getSimpleName(),
- "org.hibernate.connection.C3P0ConnectionProvider", // legacy
- "org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" // legacy
- ) );
+ // legacy
+ "org.hibernate.connection.C3P0ConnectionProvider",
+ // legacy
+ "org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider"
+ )
+ );
@Override
@SuppressWarnings("unchecked")
diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/package-info.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/package-info.java
new file mode 100644
index 0000000000..52b4638e53
--- /dev/null
+++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Implementation of ConnectionProvider using the c3p0 Connection pool.
+ */
+package org.hibernate.c3p0.internal;
From bf781d4bf71be743420a62d4aacda2aff665608e Mon Sep 17 00:00:00 2001
From: Steve Ebersole
Date: Tue, 30 Apr 2013 08:36:27 -0500
Subject: [PATCH 30/57] HHH-8159 - Apply fixups indicated by analysis tools
---
.../org/hibernate/c3p0/internal/C3P0ConnectionProvider.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java
index d1745cc25d..207461b1c5 100644
--- a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java
+++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java
@@ -249,7 +249,7 @@ public class C3P0ConnectionProvider
}
private void warnPropertyConflict(String hibernateStyle, String c3p0Style) {
- LOG.bothHibernateAndC3p0StylesSet( hibernateStyle, c3p0Style, hibernateStyle, c3p0Style );
+ LOG.bothHibernateAndC3p0StylesSet( hibernateStyle, c3p0Style );
}
@Override
From fdb30196fcf051616550cb324cfe34c2f9c531db Mon Sep 17 00:00:00 2001
From: Steve Ebersole
Date: Tue, 30 Apr 2013 08:51:04 -0500
Subject: [PATCH 31/57] HHH-8159 - Apply fixups indicated by analysis tools
---
.../java/org/hibernate/c3p0/internal/C3P0MessageLogger.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java
index 5adf334635..7ff9c6eab0 100644
--- a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java
+++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java
@@ -52,7 +52,7 @@ public interface C3P0MessageLogger extends CoreMessageLogger {
*/
@LogMessage(level = WARN)
@Message(value = "Both hibernate-style property '%1$s' and c3p0-style property '%2$s' have been set in Hibernate "
- + "properties. Hibernate-style property '%1$s' will be used and c3p0-style property '2$%s' will be ignored!", id = 10001)
+ + "properties. Hibernate-style property '%1$s' will be used and c3p0-style property '%2$s' will be ignored!", id = 10001)
void bothHibernateAndC3p0StylesSet(String hibernateStyle,String c3p0Style);
/**
From 59d1facfb6bf3d015802bfa7acd86b12a182112b Mon Sep 17 00:00:00 2001
From: Steve Ebersole
Date: Tue, 30 Apr 2013 09:26:55 -0500
Subject: [PATCH 32/57] HHH-8159 - Apply fixups indicated by analysis tools
---
.../internal/ProxoolConnectionProvider.java | 146 +++++++++---------
.../internal/ProxoolMessageLogger.java | 121 +++++++++++----
.../StrategyRegistrationProviderImpl.java | 9 +-
.../proxool/internal/package-info.java | 4 +
4 files changed, 171 insertions(+), 109 deletions(-)
create mode 100644 hibernate-proxool/src/main/java/org/hibernate/proxool/internal/package-info.java
diff --git a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolConnectionProvider.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolConnectionProvider.java
index b8a8fbd8cd..bb47c7a9c4 100644
--- a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolConnectionProvider.java
+++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolConnectionProvider.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2007, 2013, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
- * statements applied by the authors. Â All third-party contributions are
- * distributed under license by Red Hat Middleware LLC.
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@@ -27,32 +27,35 @@ import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;
-import java.util.Properties;
-import org.jboss.logging.Logger;
import org.logicalcobwebs.proxool.ProxoolException;
import org.logicalcobwebs.proxool.ProxoolFacade;
import org.logicalcobwebs.proxool.configuration.JAXPConfigurator;
import org.logicalcobwebs.proxool.configuration.PropertyConfigurator;
+import org.jboss.logging.Logger;
+
import org.hibernate.HibernateException;
import org.hibernate.cfg.Environment;
+import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.internal.util.ConfigHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.service.UnknownUnwrapTypeException;
-import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.Configurable;
import org.hibernate.service.spi.Stoppable;
/**
* A connection provider that uses a Proxool connection pool. Hibernate will use this by
* default if the hibernate.proxool.* properties are set.
+ *
* @see ConnectionProvider
*/
public class ProxoolConnectionProvider implements ConnectionProvider, Configurable, Stoppable {
-
- public static final ProxoolMessageLogger LOG = Logger.getMessageLogger(ProxoolMessageLogger.class, ProxoolConnectionProvider.class.getName());
+ private static final ProxoolMessageLogger LOG = Logger.getMessageLogger(
+ ProxoolMessageLogger.class,
+ ProxoolConnectionProvider.class.getName()
+ );
private static final String PROXOOL_JDBC_STEM = "proxool.";
@@ -67,21 +70,20 @@ public class ProxoolConnectionProvider implements ConnectionProvider, Configurab
private boolean autocommit;
- /**
- * Grab a connection
- * @return a JDBC connection
- * @throws SQLException
- */
@Override
public Connection getConnection() throws SQLException {
- // get a connection from the pool (thru DriverManager, cfr. Proxool doc)
- Connection c = DriverManager.getConnection(proxoolAlias);
+ // get a connection from the pool (thru DriverManager, cfr. Proxool doc)
+ final Connection c = DriverManager.getConnection( proxoolAlias );
// set the Transaction Isolation if defined
- if (isolation!=null) c.setTransactionIsolation( isolation );
+ if ( isolation != null ) {
+ c.setTransactionIsolation( isolation );
+ }
// toggle autoCommit to false if set
- if ( c.getAutoCommit()!=autocommit ) c.setAutoCommit(autocommit);
+ if ( c.getAutoCommit() != autocommit ) {
+ c.setAutoCommit( autocommit );
+ }
// return the connection
return c;
@@ -94,7 +96,7 @@ public class ProxoolConnectionProvider implements ConnectionProvider, Configurab
}
@Override
- @SuppressWarnings( {"unchecked"})
+ @SuppressWarnings({"unchecked"})
public T unwrap(Class unwrapType) {
if ( ConnectionProvider.class.equals( unwrapType ) ||
ProxoolConnectionProvider.class.isAssignableFrom( unwrapType ) ) {
@@ -105,39 +107,28 @@ public class ProxoolConnectionProvider implements ConnectionProvider, Configurab
}
}
- /**
- * Dispose of a used connection.
- * @param conn a JDBC connection
- * @throws SQLException
- */
@Override
public void closeConnection(Connection conn) throws SQLException {
conn.close();
}
- /**
- * Initialize the connection provider from given properties.
- * @param props SessionFactory properties
- */
@Override
- public void configure(Map props) {
-
+ public void configure(Map props) {
// Get the configurator files (if available)
- String jaxpFile = (String)props.get(Environment.PROXOOL_XML);
- String propFile = (String)props.get(Environment.PROXOOL_PROPERTIES);
- String externalConfig = (String)props.get(Environment.PROXOOL_EXISTING_POOL);
+ final String jaxpFile = (String) props.get( Environment.PROXOOL_XML );
+ final String propFile = (String) props.get( Environment.PROXOOL_PROPERTIES );
+ final String externalConfig = (String) props.get( Environment.PROXOOL_EXISTING_POOL );
// Default the Proxool alias setting
- proxoolAlias = (String)props.get(Environment.PROXOOL_POOL_ALIAS);
+ proxoolAlias = (String) props.get( Environment.PROXOOL_POOL_ALIAS );
// Configured outside of Hibernate (i.e. Servlet container, or Java Bean Container
// already has Proxool pools running, and this provider is to just borrow one of these
- if ( "true".equals(externalConfig) ) {
-
+ if ( "true".equals( externalConfig ) ) {
// Validate that an alias name was provided to determine which pool to use
if ( !StringHelper.isNotEmpty( proxoolAlias ) ) {
- String msg = LOG.unableToConfigureProxoolProviderToUseExistingInMemoryPool(Environment.PROXOOL_POOL_ALIAS);
- LOG.error(msg);
+ final String msg = LOG.unableToConfigureProxoolProviderToUseExistingInMemoryPool( Environment.PROXOOL_POOL_ALIAS );
+ LOG.error( msg );
throw new HibernateException( msg );
}
// Append the stem to the proxool pool alias
@@ -146,77 +137,79 @@ public class ProxoolConnectionProvider implements ConnectionProvider, Configurab
// Set the existing pool flag to true
existingPool = true;
- LOG.configuringProxoolProviderUsingExistingPool(proxoolAlias);
+ LOG.configuringProxoolProviderUsingExistingPool( proxoolAlias );
// Configured using the JAXP Configurator
}
else if ( StringHelper.isNotEmpty( jaxpFile ) ) {
-
- LOG.configuringProxoolProviderUsingJaxpConfigurator(jaxpFile);
+ LOG.configuringProxoolProviderUsingJaxpConfigurator( jaxpFile );
// Validate that an alias name was provided to determine which pool to use
if ( !StringHelper.isNotEmpty( proxoolAlias ) ) {
- String msg = LOG.unableToConfigureProxoolProviderToUseJaxp(Environment.PROXOOL_POOL_ALIAS);
- LOG.error(msg);
+ final String msg = LOG.unableToConfigureProxoolProviderToUseJaxp( Environment.PROXOOL_POOL_ALIAS );
+ LOG.error( msg );
throw new HibernateException( msg );
}
try {
JAXPConfigurator.configure( ConfigHelper.getConfigStreamReader( jaxpFile ), false );
}
- catch ( ProxoolException e ) {
- String msg = LOG.unableToLoadJaxpConfiguratorFile(jaxpFile);
- LOG.error(msg, e);
+ catch (ProxoolException e) {
+ final String msg = LOG.unableToLoadJaxpConfiguratorFile( jaxpFile );
+ LOG.error( msg, e );
throw new HibernateException( msg, e );
}
// Append the stem to the proxool pool alias
proxoolAlias = PROXOOL_JDBC_STEM + proxoolAlias;
- LOG.configuringProxoolProviderToUsePoolAlias(proxoolAlias);
+ LOG.configuringProxoolProviderToUsePoolAlias( proxoolAlias );
// Configured using the Properties File Configurator
}
else if ( StringHelper.isNotEmpty( propFile ) ) {
-
- LOG.configuringProxoolProviderUsingPropertiesFile(propFile);
+ LOG.configuringProxoolProviderUsingPropertiesFile( propFile );
// Validate that an alias name was provided to determine which pool to use
if ( !StringHelper.isNotEmpty( proxoolAlias ) ) {
- String msg = LOG.unableToConfigureProxoolProviderToUsePropertiesFile(Environment.PROXOOL_POOL_ALIAS);
- LOG.error(msg);
+ final String msg = LOG.unableToConfigureProxoolProviderToUsePropertiesFile( Environment.PROXOOL_POOL_ALIAS );
+ LOG.error( msg );
throw new HibernateException( msg );
}
try {
PropertyConfigurator.configure( ConfigHelper.getConfigProperties( propFile ) );
}
- catch ( ProxoolException e ) {
- String msg = LOG.unableToLoadPropertyConfiguratorFile(propFile);
- LOG.error(msg, e);
+ catch (ProxoolException e) {
+ final String msg = LOG.unableToLoadPropertyConfiguratorFile( propFile );
+ LOG.error( msg, e );
throw new HibernateException( msg, e );
}
// Append the stem to the proxool pool alias
proxoolAlias = PROXOOL_JDBC_STEM + proxoolAlias;
- LOG.configuringProxoolProviderToUsePoolAlias(proxoolAlias);
+ LOG.configuringProxoolProviderToUsePoolAlias( proxoolAlias );
}
// Remember Isolation level
- isolation = ConfigurationHelper.getInteger(Environment.ISOLATION, props);
- if (isolation != null) LOG.jdbcIsolationLevel(Environment.isolationLevelToString(isolation.intValue()));
+ isolation = ConfigurationHelper.getInteger( Environment.ISOLATION, props );
+ if ( isolation != null ) {
+ LOG.jdbcIsolationLevel( Environment.isolationLevelToString( isolation.intValue() ) );
+ }
- autocommit = ConfigurationHelper.getBoolean(Environment.AUTOCOMMIT, props);
- LOG.autoCommmitMode(autocommit);
+ autocommit = ConfigurationHelper.getBoolean( Environment.AUTOCOMMIT, props );
+ LOG.autoCommmitMode( autocommit );
}
- /**
- * Release all resources held by this provider. JavaDoc requires a second sentence.
- * @throws HibernateException
- */
- public void close() throws HibernateException {
+ @Override
+ public boolean supportsAggressiveRelease() {
+ return false;
+ }
+
+ @Override
+ public void stop() {
// If the provider was leeching off an existing pool don't close it
- if (existingPool) {
+ if ( existingPool ) {
return;
}
@@ -226,29 +219,28 @@ public class ProxoolConnectionProvider implements ConnectionProvider, Configurab
ProxoolFacade.shutdown( 0 );
}
else {
- ProxoolFacade.removeConnectionPool(proxoolAlias.substring(PROXOOL_JDBC_STEM.length()));
+ ProxoolFacade.removeConnectionPool( proxoolAlias.substring( PROXOOL_JDBC_STEM.length() ) );
}
}
catch (Exception e) {
// If you're closing down the ConnectionProvider chances are an
// is not a real big deal, just warn
- String msg = LOG.exceptionClosingProxoolPool();
- LOG.warn(msg, e);
- throw new HibernateException(msg, e);
+ final String msg = LOG.exceptionClosingProxoolPool();
+ LOG.warn( msg, e );
+ throw new HibernateException( msg, e );
}
}
/**
- * @see ConnectionProvider#supportsAggressiveRelease()
+ * Release all resources held by this provider.
+ *
+ * @throws HibernateException Indicates a problem closing the underlying pool or releasing resources
+ *
+ * @deprecated Use {@link #stop} instead
*/
- @Override
- public boolean supportsAggressiveRelease() {
- return false;
+ @Deprecated
+ public void close() throws HibernateException {
+ stop();
}
-
- @Override
- public void stop() {
- close();
- }
}
diff --git a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolMessageLogger.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolMessageLogger.java
index 568f4c98e9..5229bf66d2 100644
--- a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolMessageLogger.java
+++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolMessageLogger.java
@@ -37,44 +37,109 @@ import static org.jboss.logging.Logger.Level.INFO;
*
* New messages must be added after the last message defined to ensure message codes are unique.
*/
-@MessageLogger( projectCode = "HHH" )
+@MessageLogger(projectCode = "HHH")
public interface ProxoolMessageLogger extends CoreMessageLogger {
- @LogMessage( level = INFO )
- @Message( value = "Autocommit mode: %s", id = 30001 )
- void autoCommmitMode( boolean autocommit );
+ /**
+ * Logs the autocommit mode to be used for pooled connections
+ *
+ * @param autocommit The autocommit mode
+ */
+ @LogMessage(level = INFO)
+ @Message(value = "Autocommit mode: %s", id = 30001)
+ void autoCommmitMode(boolean autocommit);
- @LogMessage( level = INFO )
- @Message( value = "Configuring Proxool Provider to use pool alias: %s", id = 30002 )
- void configuringProxoolProviderToUsePoolAlias( String proxoolAlias );
+ /**
+ * Logs the name of a named pool to be used for configuration information
+ *
+ * @param proxoolAlias The name (alias) of the proxool pool
+ */
+ @LogMessage(level = INFO)
+ @Message(value = "Configuring Proxool Provider to use pool alias: %s", id = 30002)
+ void configuringProxoolProviderToUsePoolAlias(String proxoolAlias);
- @LogMessage( level = INFO )
- @Message( value = "Configuring Proxool Provider using existing pool in memory: %s", id = 30003 )
- void configuringProxoolProviderUsingExistingPool( String proxoolAlias );
+ /**
+ * Logs the name of a named existing pool in memory to be used
+ *
+ * @param proxoolAlias The name (alias) of the proxool pool
+ */
+ @LogMessage(level = INFO)
+ @Message(value = "Configuring Proxool Provider using existing pool in memory: %s", id = 30003)
+ void configuringProxoolProviderUsingExistingPool(String proxoolAlias);
- @LogMessage( level = INFO )
- @Message( value = "Configuring Proxool Provider using JAXPConfigurator: %s", id = 30004 )
- void configuringProxoolProviderUsingJaxpConfigurator( String jaxpFile );
+ /**
+ * Logs a message that the proxool pool will be built using its JAXP (XML) configuration mechanism
+ *
+ * @param jaxpFile The XML configuration file to use
+ */
+ @LogMessage(level = INFO)
+ @Message(value = "Configuring Proxool Provider using JAXPConfigurator: %s", id = 30004)
+ void configuringProxoolProviderUsingJaxpConfigurator(String jaxpFile);
- @LogMessage( level = INFO )
- @Message( value = "Configuring Proxool Provider using Properties File: %s", id = 30005 )
- void configuringProxoolProviderUsingPropertiesFile( String proxoolAlias );
+ /**
+ * Logs a message that the proxool pool will be built using a properties file
+ *
+ * @param propFile The properties file to use
+ */
+ @LogMessage(level = INFO)
+ @Message(value = "Configuring Proxool Provider using Properties File: %s", id = 30005)
+ void configuringProxoolProviderUsingPropertiesFile(String propFile);
- @Message( value = "Exception occured when closing the Proxool pool", id = 30006 )
- String exceptionClosingProxoolPool();
+ /**
+ * Builds a message about not being able to close the underlying proxool pool.
+ *
+ * @return The message
+ */
+ @Message(value = "Exception occured when closing the Proxool pool", id = 30006)
+ String exceptionClosingProxoolPool();
- @Message( value = "Cannot configure Proxool Provider to use an existing in memory pool without the %s property set.", id = 30007 )
- String unableToConfigureProxoolProviderToUseExistingInMemoryPool( String proxoolPoolAlias );
+ /**
+ * Builds a message about invalid configuration
+ *
+ * @param proxoolPoolAlias The name (alias) of the proxool pool
+ *
+ * @return The message
+ */
+ @Message(value = "Cannot configure Proxool Provider to use an existing in memory pool without the %s property set.", id = 30007)
+ String unableToConfigureProxoolProviderToUseExistingInMemoryPool(String proxoolPoolAlias);
- @Message( value = "Cannot configure Proxool Provider to use JAXP without the %s property set.", id = 30008 )
- String unableToConfigureProxoolProviderToUseJaxp( String proxoolPoolAlias );
+ /**
+ * Builds a message about invalid configuration
+ *
+ * @param proxoolPoolAlias The name (alias) of the proxool pool
+ *
+ * @return The message
+ */
+ @Message(value = "Cannot configure Proxool Provider to use JAXP without the %s property set.", id = 30008)
+ String unableToConfigureProxoolProviderToUseJaxp(String proxoolPoolAlias);
- @Message( value = "Cannot configure Proxool Provider to use Properties File without the %s property set.", id = 30009 )
- String unableToConfigureProxoolProviderToUsePropertiesFile( String proxoolPoolAlias );
+ /**
+ * Builds a message about invalid configuration
+ *
+ * @param proxoolPoolAlias The name (alias) of the proxool pool
+ *
+ * @return The message
+ */
+ @Message(value = "Cannot configure Proxool Provider to use Properties File without the %s property set.", id = 30009)
+ String unableToConfigureProxoolProviderToUsePropertiesFile(String proxoolPoolAlias);
- @Message( value = "Proxool Provider unable to load JAXP configurator file: %s", id = 30010 )
- String unableToLoadJaxpConfiguratorFile( String jaxpFile );
+ /**
+ * Builds a message about not being able to find or load the XML configuration file
+ *
+ * @param jaxpFile The XML file
+ *
+ * @return The message
+ */
+ @Message(value = "Proxool Provider unable to load JAXP configurator file: %s", id = 30010)
+ String unableToLoadJaxpConfiguratorFile(String jaxpFile);
- @Message( value = "Proxool Provider unable to load Property configurator file: %s", id = 30011 )
- String unableToLoadPropertyConfiguratorFile( String propFile );
+ /**
+ * Builds a message about not being able to find or load the properties configuration file
+ *
+ * @param propFile The properties file
+ *
+ * @return The message
+ */
+ @Message(value = "Proxool Provider unable to load Property configurator file: %s", id = 30011)
+ String unableToLoadPropertyConfiguratorFile(String propFile);
}
diff --git a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java
index 7104d50399..c5c5c720cf 100644
--- a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java
+++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java
@@ -38,15 +38,16 @@ import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
* @author Brett Meyer
*/
public class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider {
-
private static final List REGISTRATIONS = Collections.singletonList(
- (StrategyRegistration) new SimpleStrategyRegistrationImpl(
+ (StrategyRegistration) new SimpleStrategyRegistrationImpl(
ConnectionProvider.class,
ProxoolConnectionProvider.class,
"proxool",
ProxoolConnectionProvider.class.getSimpleName(),
- "org.hibernate.connection.ProxoolConnectionProvider", // legacy
- "org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider" // legacy
+ // legacy
+ "org.hibernate.connection.ProxoolConnectionProvider",
+ // legacy
+ "org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider"
) );
@Override
diff --git a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/package-info.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/package-info.java
new file mode 100644
index 0000000000..bc3b68bf9e
--- /dev/null
+++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Implementation of ConnectionProvider using the proxool Connection pool.
+ */
+package org.hibernate.proxool.internal;
From 09a54fdc5457c5a2e0c1d3af0472f332063829c6 Mon Sep 17 00:00:00 2001
From: Steve Ebersole
Date: Tue, 30 Apr 2013 09:30:04 -0500
Subject: [PATCH 33/57] HHH-8159 - Apply fixups indicated by analysis tools
---
.../proxool/internal/StrategyRegistrationProviderImpl.java | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java
index c5c5c720cf..841a7c985d 100644
--- a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java
+++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java
@@ -48,7 +48,8 @@ public class StrategyRegistrationProviderImpl implements StrategyRegistrationPro
"org.hibernate.connection.ProxoolConnectionProvider",
// legacy
"org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider"
- ) );
+ )
+ );
@Override
@SuppressWarnings("unchecked")
From 97e28200f0eb61d6b59bf782e8fb60559679c7a2 Mon Sep 17 00:00:00 2001
From: Steve Ebersole
Date: Tue, 30 Apr 2013 13:27:38 -0500
Subject: [PATCH 34/57] HHH-8159 - Apply fixups indicated by analysis tools
---
.../ehcache/AbstractEhcacheRegionFactory.java | 302 ++++----
.../cache/ehcache/EhCacheMessageLogger.java | 116 +++-
.../cache/ehcache/EhCacheRegionFactory.java | 154 +++--
.../SingletonEhCacheRegionFactory.java | 140 ++--
.../StrategyRegistrationProviderImpl.java | 8 +-
...HibernateNonstopCacheExceptionHandler.java | 105 +--
.../nonstop/NonstopAccessStrategyFactory.java | 84 +--
...opAwareCollectionRegionAccessStrategy.java | 105 +--
...onstopAwareEntityRegionAccessStrategy.java | 141 +---
...topAwareNaturalIdRegionAccessStrategy.java | 115 +---
.../internal/nonstop/package-info.java | 5 +
.../regions/EhcacheCollectionRegion.java | 40 +-
.../internal/regions/EhcacheDataRegion.java | 304 ++++----
.../internal/regions/EhcacheEntityRegion.java | 40 +-
.../regions/EhcacheGeneralDataRegion.java | 219 +++---
.../regions/EhcacheNaturalIdRegion.java | 32 +-
.../regions/EhcacheQueryResultsRegion.java | 12 +-
.../regions/EhcacheTimestampsRegion.java | 14 +-
.../EhcacheTransactionalDataRegion.java | 92 ++-
.../internal/regions/package-info.java | 4 +
.../AbstractEhcacheAccessStrategy.java | 34 +-
...bstractReadWriteEhcacheAccessStrategy.java | 649 +++++++++---------
.../EhcacheAccessStrategyFactory.java | 44 +-
.../EhcacheAccessStrategyFactoryImpl.java | 198 +++---
...EhcacheCollectionRegionAccessStrategy.java | 36 +-
...riteEhcacheEntityRegionAccessStrategy.java | 49 +-
...eEhcacheNaturalIdRegionAccessStrategy.java | 75 +-
...EhcacheCollectionRegionAccessStrategy.java | 27 +-
...OnlyEhcacheEntityRegionAccessStrategy.java | 19 +-
...yEhcacheNaturalIdRegionAccessStrategy.java | 56 +-
...EhcacheCollectionRegionAccessStrategy.java | 11 +-
...riteEhcacheEntityRegionAccessStrategy.java | 33 +-
...eEhcacheNaturalIdRegionAccessStrategy.java | 44 +-
...EhcacheCollectionRegionAccessStrategy.java | 47 +-
...onalEhcacheEntityRegionAccessStrategy.java | 73 +-
...lEhcacheNaturalIdRegionAccessStrategy.java | 73 +-
.../internal/strategy/package-info.java | 4 +
.../internal/util/HibernateEhcacheUtils.java | 129 ++++
.../ehcache/internal/util/HibernateUtil.java | 116 ----
.../ehcache/internal/util/package-info.java | 4 +
...tterBean.java => AbstractEmitterBean.java} | 87 +--
.../ehcache/management/impl/BeanUtils.java | 43 +-
.../management/impl/CacheRegionStats.java | 93 +--
.../management/impl/CacheRegionUtils.java | 35 +-
.../management/impl/CollectionStats.java | 107 ++-
.../management/impl/EhcacheHibernate.java | 14 +-
...EhcacheHibernateMBeanRegistrationImpl.java | 237 +++----
.../management/impl/EhcacheStatsImpl.java | 24 +-
.../ehcache/management/impl/EntityStats.java | 18 +-
.../management/impl/HibernateStatsImpl.java | 14 +-
.../impl/ProviderMBeanRegistrationHelper.java | 260 +++----
.../ehcache/management/impl/QueryStats.java | 18 +-
.../ehcache/management/impl/package-info.java | 4 +
.../hibernate/cache/ehcache/package-info.java | 4 +
54 files changed, 2312 insertions(+), 2399 deletions(-)
create mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/package-info.java
create mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/package-info.java
create mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/package-info.java
create mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateEhcacheUtils.java
delete mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateUtil.java
create mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/package-info.java
rename hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/{BaseEmitterBean.java => AbstractEmitterBean.java} (69%)
create mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/package-info.java
create mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/package-info.java
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java
index 9b9a28c2ec..b12a88e188 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java
@@ -29,8 +29,10 @@ import java.util.Properties;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.util.ClassLoaderUtil;
+
import org.jboss.logging.Logger;
+import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.nonstop.NonstopAccessStrategyFactory;
import org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion;
@@ -40,7 +42,7 @@ import org.hibernate.cache.ehcache.internal.regions.EhcacheQueryResultsRegion;
import org.hibernate.cache.ehcache.internal.regions.EhcacheTimestampsRegion;
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory;
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactoryImpl;
-import org.hibernate.cache.ehcache.internal.util.HibernateUtil;
+import org.hibernate.cache.ehcache.internal.util.HibernateEhcacheUtils;
import org.hibernate.cache.ehcache.management.impl.ProviderMBeanRegistrationHelper;
import org.hibernate.cache.spi.CacheDataDescription;
import org.hibernate.cache.spi.CollectionRegion;
@@ -51,7 +53,6 @@ import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.TimestampsRegion;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.Settings;
-import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.service.spi.InjectService;
/**
@@ -65,172 +66,169 @@ import org.hibernate.service.spi.InjectService;
*/
abstract class AbstractEhcacheRegionFactory implements RegionFactory {
- /**
- * The Hibernate system property specifying the location of the ehcache configuration file name.
- *
- * If not set, ehcache.xml will be looked for in the root of the classpath.
- *
- * If set to say ehcache-1.xml, ehcache-1.xml will be looked for in the root of the classpath.
- */
- public static final String NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME = "net.sf.ehcache.configurationResourceName";
+ /**
+ * The Hibernate system property specifying the location of the ehcache configuration file name.
+ *
+ * If not set, ehcache.xml will be looked for in the root of the classpath.
+ *
+ * If set to say ehcache-1.xml, ehcache-1.xml will be looked for in the root of the classpath.
+ */
+ public static final String NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME = "net.sf.ehcache.configurationResourceName";
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- AbstractEhcacheRegionFactory.class.getName()
- );
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ AbstractEhcacheRegionFactory.class.getName()
+ );
- /**
- * MBean registration helper class instance for Ehcache Hibernate MBeans.
- */
- protected final ProviderMBeanRegistrationHelper mbeanRegistrationHelper = new ProviderMBeanRegistrationHelper();
+ /**
+ * MBean registration helper class instance for Ehcache Hibernate MBeans.
+ */
+ protected final ProviderMBeanRegistrationHelper mbeanRegistrationHelper = new ProviderMBeanRegistrationHelper();
- /**
- * Ehcache CacheManager that supplied Ehcache instances for this Hibernate RegionFactory.
- */
- protected volatile CacheManager manager;
+ /**
+ * Ehcache CacheManager that supplied Ehcache instances for this Hibernate RegionFactory.
+ */
+ protected volatile CacheManager manager;
- /**
- * Settings object for the Hibernate persistence unit.
- */
- protected Settings settings;
+ /**
+ * Settings object for the Hibernate persistence unit.
+ */
+ protected Settings settings;
- /**
- * {@link EhcacheAccessStrategyFactory} for creating various access strategies
- */
- protected final EhcacheAccessStrategyFactory accessStrategyFactory =
- new NonstopAccessStrategyFactory( new EhcacheAccessStrategyFactoryImpl() );
+ /**
+ * {@link EhcacheAccessStrategyFactory} for creating various access strategies
+ */
+ protected final EhcacheAccessStrategyFactory accessStrategyFactory =
+ new NonstopAccessStrategyFactory( new EhcacheAccessStrategyFactoryImpl() );
- /**
- * Whether to optimize for minimals puts or minimal gets.
- *
- * Indicates whether when operating in non-strict read/write or read-only mode
- * Hibernate should optimize the access patterns for minimal puts or minimal gets.
- * In Ehcache we default to minimal puts since this should have minimal to no
- * affect on unclustered users, and has great benefit for clustered users.
- *
- * This setting can be overridden by setting the "hibernate.cache.use_minimal_puts"
- * property in the Hibernate configuration.
- *
- * @return true, optimize for minimal puts
- */
- public boolean isMinimalPutsEnabledByDefault() {
- return true;
- }
+ /**
+ * {@inheritDoc}
+ *
+ * In Ehcache we default to minimal puts since this should have minimal to no
+ * affect on unclustered users, and has great benefit for clustered users.
+ *
+ * @return true, optimize for minimal puts
+ */
+ @Override
+ public boolean isMinimalPutsEnabledByDefault() {
- /**
- * {@inheritDoc}
- */
- public long nextTimestamp() {
- return net.sf.ehcache.util.Timestamper.next();
- }
+ return true;
+ }
- /**
- * {@inheritDoc}
- */
- public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata)
- throws CacheException {
- return new EhcacheEntityRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties );
- }
-
- @Override
- public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata)
- throws CacheException {
- return new EhcacheNaturalIdRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties );
- }
+ @Override
+ public long nextTimestamp() {
+ return net.sf.ehcache.util.Timestamper.next();
+ }
- /**
- * {@inheritDoc}
- */
- public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata)
- throws CacheException {
- return new EhcacheCollectionRegion(
- accessStrategyFactory,
- getCache( regionName ),
- settings,
- metadata,
- properties
- );
- }
+ @Override
+ public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata)
+ throws CacheException {
+ return new EhcacheEntityRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties );
+ }
- /**
- * {@inheritDoc}
- */
- public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException {
- return new EhcacheQueryResultsRegion( accessStrategyFactory, getCache( regionName ), properties );
- }
+ @Override
+ public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata)
+ throws CacheException {
+ return new EhcacheNaturalIdRegion(
+ accessStrategyFactory,
+ getCache( regionName ),
+ settings,
+ metadata,
+ properties
+ );
+ }
- @InjectService
- public void setClassLoaderService(ClassLoaderService classLoaderService) {
- this.classLoaderService = classLoaderService;
- }
+ @Override
+ public CollectionRegion buildCollectionRegion(
+ String regionName,
+ Properties properties,
+ CacheDataDescription metadata)
+ throws CacheException {
+ return new EhcacheCollectionRegion(
+ accessStrategyFactory,
+ getCache( regionName ),
+ settings,
+ metadata,
+ properties
+ );
+ }
- private ClassLoaderService classLoaderService;
+ @Override
+ public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException {
+ return new EhcacheQueryResultsRegion( accessStrategyFactory, getCache( regionName ), properties );
+ }
- /**
- * {@inheritDoc}
- */
- public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException {
- return new EhcacheTimestampsRegion( accessStrategyFactory, getCache( regionName ), properties );
- }
+ @InjectService
+ @SuppressWarnings("UnusedDeclaration")
+ public void setClassLoaderService(ClassLoaderService classLoaderService) {
+ this.classLoaderService = classLoaderService;
+ }
- private Ehcache getCache(String name) throws CacheException {
- try {
- Ehcache cache = manager.getEhcache( name );
- if ( cache == null ) {
- LOG.unableToFindEhCacheConfiguration( name );
- manager.addCache( name );
- cache = manager.getEhcache( name );
- LOG.debug( "started EHCache region: " + name );
- }
- HibernateUtil.validateEhcache( cache );
- return cache;
- }
- catch ( net.sf.ehcache.CacheException e ) {
- throw new CacheException( e );
- }
+ private ClassLoaderService classLoaderService;
- }
+ @Override
+ public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException {
+ return new EhcacheTimestampsRegion( accessStrategyFactory, getCache( regionName ), properties );
+ }
- /**
- * Load a resource from the classpath.
- */
- protected URL loadResource(String configurationResourceName) {
- URL url = null;
- if ( classLoaderService != null ) {
- url = classLoaderService.locateResource( configurationResourceName );
- }
- if ( url == null ) {
- ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();
- if ( standardClassloader != null ) {
- url = standardClassloader.getResource( configurationResourceName );
- }
- if ( url == null ) {
- url = AbstractEhcacheRegionFactory.class.getResource( configurationResourceName );
- }
- }
- if ( LOG.isDebugEnabled() ) {
- LOG.debugf(
- "Creating EhCacheRegionFactory from a specified resource: %s. Resolved to URL: %s",
- configurationResourceName,
- url
- );
- }
- if ( url == null ) {
+ private Ehcache getCache(String name) throws CacheException {
+ try {
+ Ehcache cache = manager.getEhcache( name );
+ if ( cache == null ) {
+ LOG.unableToFindEhCacheConfiguration( name );
+ manager.addCache( name );
+ cache = manager.getEhcache( name );
+ LOG.debug( "started EHCache region: " + name );
+ }
+ HibernateEhcacheUtils.validateEhcache( cache );
+ return cache;
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ throw new CacheException( e );
+ }
- LOG.unableToLoadConfiguration( configurationResourceName );
- }
- return url;
- }
+ }
- /**
- * Default access-type used when the configured using JPA 2.0 config. JPA 2.0 allows @Cacheable(true)
to be attached to an
- * entity without any access type or usage qualification.
- *
- * We are conservative here in specifying {@link AccessType#READ_WRITE} so as to follow the mantra of "do no harm".
- *
- * This is a Hibernate 3.5 method.
- */
- public AccessType getDefaultAccessType() {
- return AccessType.READ_WRITE;
- }
+ /**
+ * Load a resource from the classpath.
+ */
+ protected URL loadResource(String configurationResourceName) {
+ URL url = null;
+ if ( classLoaderService != null ) {
+ url = classLoaderService.locateResource( configurationResourceName );
+ }
+ if ( url == null ) {
+ final ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();
+ if ( standardClassloader != null ) {
+ url = standardClassloader.getResource( configurationResourceName );
+ }
+ if ( url == null ) {
+ url = AbstractEhcacheRegionFactory.class.getResource( configurationResourceName );
+ }
+ }
+ if ( LOG.isDebugEnabled() ) {
+ LOG.debugf(
+ "Creating EhCacheRegionFactory from a specified resource: %s. Resolved to URL: %s",
+ configurationResourceName,
+ url
+ );
+ }
+ if ( url == null ) {
+
+ LOG.unableToLoadConfiguration( configurationResourceName );
+ }
+ return url;
+ }
+
+ /**
+ * Default access-type used when the configured using JPA 2.0 config. JPA 2.0 allows @Cacheable(true)
to be attached to an
+ * entity without any access type or usage qualification.
+ *
+ * We are conservative here in specifying {@link AccessType#READ_WRITE} so as to follow the mantra of "do no harm".
+ *
+ * This is a Hibernate 3.5 method.
+ */
+ public AccessType getDefaultAccessType() {
+ return AccessType.READ_WRITE;
+ }
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheMessageLogger.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheMessageLogger.java
index c7fdc74ea2..dcceea5bfd 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheMessageLogger.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheMessageLogger.java
@@ -37,45 +37,99 @@ import static org.jboss.logging.Logger.Level.WARN;
*
* New messages must be added after the last message defined to ensure message codes are unique.
*/
-@MessageLogger( projectCode = "HHH" )
+@MessageLogger(projectCode = "HHH")
public interface EhCacheMessageLogger extends CoreMessageLogger {
- @LogMessage( level = WARN )
- @Message( value = "Attempt to restart an already started EhCacheProvider. Use sessionFactory.close() between repeated calls to "
- + "buildSessionFactory. Using previously created EhCacheProvider. If this behaviour is required, consider "
- + "using net.sf.ehcache.hibernate.SingletonEhCacheProvider.", id = 20001 )
- void attemptToRestartAlreadyStartedEhCacheProvider();
+ /**
+ * Log a message (WARN) about attempt to start an already started Ehcache region factory
+ */
+ @LogMessage(level = WARN)
+ @Message(
+ value = "Attempt to restart an already started EhCacheRegionFactory. Use sessionFactory.close() between " +
+ "repeated calls to buildSessionFactory. Using previously created EhCacheRegionFactory. If this " +
+ "behaviour is required, consider using org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory.",
+ id = 20001
+ )
+ void attemptToRestartAlreadyStartedEhCacheProvider();
- @LogMessage( level = WARN )
- @Message( value = "Could not find configuration [%s]; using defaults.", id = 20002 )
- void unableToFindConfiguration( String name );
+ /**
+ * Log a message (WARN) about inability to find configuration file
+ *
+ * @param name The name of the configuration file
+ */
+ @LogMessage(level = WARN)
+ @Message(value = "Could not find configuration [%s]; using defaults.", id = 20002)
+ void unableToFindConfiguration(String name);
- @LogMessage( level = WARN )
- @Message( value = "Could not find a specific ehcache configuration for cache named [%s]; using defaults.", id = 20003 )
- void unableToFindEhCacheConfiguration( String name );
+ /**
+ * Log a message (WARN) about inability to find named cache configuration
+ *
+ * @param name The name of the cache configuration
+ */
+ @LogMessage(level = WARN)
+ @Message(value = "Could not find a specific ehcache configuration for cache named [%s]; using defaults.", id = 20003)
+ void unableToFindEhCacheConfiguration(String name);
- @LogMessage( level = WARN )
- @Message( value = "A configurationResourceName was set to %s but the resource could not be loaded from the classpath. Ehcache will configure itself using defaults.", id = 20004 )
- void unableToLoadConfiguration( String configurationResourceName );
+ /**
+ * Logs a message about not being able to resolve the configuration by resource name.
+ *
+ * @param configurationResourceName The resource name we attempted to resolve
+ */
+ @LogMessage(level = WARN)
+ @Message(
+ value = "A configurationResourceName was set to %s but the resource could not be loaded from the classpath. " +
+ "Ehcache will configure itself using defaults.",
+ id = 20004
+ )
+ void unableToLoadConfiguration(String configurationResourceName);
- @LogMessage( level = WARN )
- @Message( value = "The default cache value mode for this Ehcache configuration is \"identity\". This is incompatible with clustered "
- + "Hibernate caching - the value mode has therefore been switched to \"serialization\"", id = 20005 )
- void incompatibleCacheValueMode( );
+ /**
+ * Logs a message (WARN) about attempt to use an incompatible
+ * {@link net.sf.ehcache.config.TerracottaConfiguration.ValueMode}.
+ */
+ @LogMessage(level = WARN)
+ @Message(
+ value = "The default cache value mode for this Ehcache configuration is \"identity\". " +
+ "This is incompatible with clustered Hibernate caching - the value mode has therefore been " +
+ "switched to \"serialization\"",
+ id = 20005
+ )
+ void incompatibleCacheValueMode();
- @LogMessage( level = WARN )
- @Message( value = "The value mode for the cache[%s] is \"identity\". This is incompatible with clustered Hibernate caching - "
- + "the value mode has therefore been switched to \"serialization\"", id = 20006 )
- void incompatibleCacheValueModePerCache( String cacheName );
- @LogMessage( level = WARN )
- @Message( value = "read-only cache configured for mutable entity [%s]", id = 20007 )
- void readOnlyCacheConfiguredForMutableEntity( String entityName );
+ /**
+ * Logs a message (WARN) about attempt to use an incompatible
+ * {@link net.sf.ehcache.config.TerracottaConfiguration.ValueMode}.
+ *
+ * @param cacheName The name of the cache whose config attempted to specify value mode.
+ */
+ @LogMessage(level = WARN)
+ @Message(value = "The value mode for the cache[%s] is \"identity\". This is incompatible with clustered Hibernate caching - "
+ + "the value mode has therefore been switched to \"serialization\"", id = 20006)
+ void incompatibleCacheValueModePerCache(String cacheName);
- @LogMessage( level = WARN )
- @Message( value = "Cache[%s] Key[%s] Lockable[%s]\n"
- + "A soft-locked cache entry was expired by the underlying Ehcache. "
- + "If this happens regularly you should consider increasing the cache timeouts and/or capacity limits", id = 20008 )
- void softLockedCacheExpired( String regionName, Object key, String lock);
+ /**
+ * Log a message (WARN) about an attempt to specify read-only caching for a mutable entity
+ *
+ * @param entityName The name of the entity
+ */
+ @LogMessage(level = WARN)
+ @Message(value = "read-only cache configured for mutable entity [%s]", id = 20007)
+ void readOnlyCacheConfiguredForMutableEntity(String entityName);
+ /**
+ * Log a message (WARN) about expiry of soft-locked region.
+ *
+ * @param regionName The region name
+ * @param key The cache key
+ * @param lock The lock
+ */
+ @LogMessage(level = WARN)
+ @Message(
+ value = "Cache[%s] Key[%s] Lockable[%s]\n" +
+ "A soft-locked cache entry was expired by the underlying Ehcache. If this happens regularly you " +
+ "should consider increasing the cache timeouts and/or capacity limits",
+ id = 20008
+ )
+ void softLockedCacheExpired(String regionName, Object key, String lock);
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java
index 2ec3a9d920..6b28b6ee25 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java
@@ -30,10 +30,11 @@ import java.util.Properties;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.Configuration;
import net.sf.ehcache.config.ConfigurationFactory;
+
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
-import org.hibernate.cache.ehcache.internal.util.HibernateUtil;
+import org.hibernate.cache.ehcache.internal.util.HibernateEhcacheUtils;
import org.hibernate.cfg.Settings;
/**
@@ -47,85 +48,88 @@ import org.hibernate.cfg.Settings;
*/
public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory {
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- EhCacheRegionFactory.class.getName()
- );
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ EhCacheRegionFactory.class.getName()
+ );
- public EhCacheRegionFactory() {
- }
+ /**
+ * Creates a non-singleton EhCacheRegionFactory
+ */
+ @SuppressWarnings("UnusedDeclaration")
+ public EhCacheRegionFactory() {
+ }
- /**
- * Creates a non-singleton EhCacheRegionFactory
- */
- public EhCacheRegionFactory(Properties prop) {
- super();
- }
+ /**
+ * Creates a non-singleton EhCacheRegionFactory
+ *
+ * @param prop Not used
+ */
+ @SuppressWarnings("UnusedDeclaration")
+ public EhCacheRegionFactory(Properties prop) {
+ super();
+ }
- /**
- * {@inheritDoc}
- */
- public void start(Settings settings, Properties properties) throws CacheException {
- this.settings = settings;
- if ( manager != null ) {
- LOG.attemptToRestartAlreadyStartedEhCacheProvider();
- return;
- }
+ @Override
+ public void start(Settings settings, Properties properties) throws CacheException {
+ this.settings = settings;
+ if ( manager != null ) {
+ LOG.attemptToRestartAlreadyStartedEhCacheProvider();
+ return;
+ }
- try {
- String configurationResourceName = null;
- if ( properties != null ) {
- configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME );
- }
- if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
- Configuration configuration = ConfigurationFactory.parseConfiguration();
- manager = new CacheManager( configuration );
- }
- else {
- URL url;
- try {
- url = new URL( configurationResourceName );
- }
- catch ( MalformedURLException e ) {
- url = loadResource( configurationResourceName );
- }
- Configuration configuration = HibernateUtil.loadAndCorrectConfiguration( url );
- manager = new CacheManager( configuration );
- }
- mbeanRegistrationHelper.registerMBean( manager, properties );
- }
- catch ( net.sf.ehcache.CacheException e ) {
- if ( e.getMessage().startsWith(
- "Cannot parseConfiguration CacheManager. Attempt to create a new instance of " +
- "CacheManager using the diskStorePath"
- ) ) {
- throw new CacheException(
- "Attempt to restart an already started EhCacheRegionFactory. " +
- "Use sessionFactory.close() between repeated calls to buildSessionFactory. " +
- "Consider using SingletonEhCacheRegionFactory. Error from ehcache was: " + e.getMessage()
- );
- }
- else {
- throw new CacheException( e );
- }
- }
- }
+ try {
+ String configurationResourceName = null;
+ if ( properties != null ) {
+ configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME );
+ }
+ if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
+ final Configuration configuration = ConfigurationFactory.parseConfiguration();
+ manager = new CacheManager( configuration );
+ }
+ else {
+ URL url;
+ try {
+ url = new URL( configurationResourceName );
+ }
+ catch (MalformedURLException e) {
+ url = loadResource( configurationResourceName );
+ }
+ final Configuration configuration = HibernateEhcacheUtils.loadAndCorrectConfiguration( url );
+ manager = new CacheManager( configuration );
+ }
+ mbeanRegistrationHelper.registerMBean( manager, properties );
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ if ( e.getMessage().startsWith(
+ "Cannot parseConfiguration CacheManager. Attempt to create a new instance of " +
+ "CacheManager using the diskStorePath"
+ ) ) {
+ throw new CacheException(
+ "Attempt to restart an already started EhCacheRegionFactory. " +
+ "Use sessionFactory.close() between repeated calls to buildSessionFactory. " +
+ "Consider using SingletonEhCacheRegionFactory. Error from ehcache was: " + e.getMessage()
+ );
+ }
+ else {
+ throw new CacheException( e );
+ }
+ }
+ }
- /**
- * {@inheritDoc}
- */
- public void stop() {
- try {
- if ( manager != null ) {
- mbeanRegistrationHelper.unregisterMBean();
- manager.shutdown();
- manager = null;
- }
- }
- catch ( net.sf.ehcache.CacheException e ) {
- throw new CacheException( e );
- }
- }
+ @Override
+ public void stop() {
+ try {
+ if ( manager != null ) {
+ mbeanRegistrationHelper.unregisterMBean();
+ manager.shutdown();
+ manager = null;
+ }
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ throw new CacheException( e );
+ }
+ }
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/SingletonEhCacheRegionFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/SingletonEhCacheRegionFactory.java
index fdf533cec8..d51774d263 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/SingletonEhCacheRegionFactory.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/SingletonEhCacheRegionFactory.java
@@ -30,10 +30,11 @@ import java.util.concurrent.atomic.AtomicInteger;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.Configuration;
+
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
-import org.hibernate.cache.ehcache.internal.util.HibernateUtil;
+import org.hibernate.cache.ehcache.internal.util.HibernateEhcacheUtils;
import org.hibernate.cfg.Settings;
/**
@@ -45,75 +46,80 @@ import org.hibernate.cfg.Settings;
* @author Alex Snaps
*/
public class SingletonEhCacheRegionFactory extends AbstractEhcacheRegionFactory {
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ SingletonEhCacheRegionFactory.class.getName()
+ );
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- SingletonEhCacheRegionFactory.class.getName()
- );
- private static final AtomicInteger REFERENCE_COUNT = new AtomicInteger();
+ private static final AtomicInteger REFERENCE_COUNT = new AtomicInteger();
- /**
- * Returns a representation of the singleton EhCacheRegionFactory
- */
- public SingletonEhCacheRegionFactory(Properties prop) {
- super();
- }
+ /**
+ * Constructs a SingletonEhCacheRegionFactory
+ */
+ @SuppressWarnings("UnusedDeclaration")
+ public SingletonEhCacheRegionFactory() {
+ }
- /**
- * {@inheritDoc}
- */
- public void start(Settings settings, Properties properties) throws CacheException {
- this.settings = settings;
- try {
- String configurationResourceName = null;
- if ( properties != null ) {
- configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME );
- }
- if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
- manager = CacheManager.create();
- REFERENCE_COUNT.incrementAndGet();
- }
- else {
- URL url;
- try {
- url = new URL( configurationResourceName );
- }
- catch ( MalformedURLException e ) {
- if ( !configurationResourceName.startsWith( "/" ) ) {
- configurationResourceName = "/" + configurationResourceName;
- LOG.debugf(
- "prepending / to %s. It should be placed in the root of the classpath rather than in a package.",
- configurationResourceName
- );
- }
- url = loadResource( configurationResourceName );
- }
- Configuration configuration = HibernateUtil.loadAndCorrectConfiguration( url );
- manager = CacheManager.create( configuration );
- REFERENCE_COUNT.incrementAndGet();
- }
- mbeanRegistrationHelper.registerMBean( manager, properties );
- }
- catch ( net.sf.ehcache.CacheException e ) {
- throw new CacheException( e );
- }
- }
+ /**
+ * Constructs a SingletonEhCacheRegionFactory
+ *
+ * @param prop Not used
+ */
+ @SuppressWarnings("UnusedDeclaration")
+ public SingletonEhCacheRegionFactory(Properties prop) {
+ super();
+ }
- /**
- * {@inheritDoc}
- */
- public void stop() {
- try {
- if ( manager != null ) {
- if ( REFERENCE_COUNT.decrementAndGet() == 0 ) {
- manager.shutdown();
- }
- manager = null;
- }
- }
- catch ( net.sf.ehcache.CacheException e ) {
- throw new CacheException( e );
- }
- }
+ @Override
+ public void start(Settings settings, Properties properties) throws CacheException {
+ this.settings = settings;
+ try {
+ String configurationResourceName = null;
+ if ( properties != null ) {
+ configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME );
+ }
+ if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
+ manager = CacheManager.create();
+ REFERENCE_COUNT.incrementAndGet();
+ }
+ else {
+ URL url;
+ try {
+ url = new URL( configurationResourceName );
+ }
+ catch (MalformedURLException e) {
+ if ( !configurationResourceName.startsWith( "/" ) ) {
+ configurationResourceName = "/" + configurationResourceName;
+ LOG.debugf(
+ "prepending / to %s. It should be placed in the root of the classpath rather than in a package.",
+ configurationResourceName
+ );
+ }
+ url = loadResource( configurationResourceName );
+ }
+ final Configuration configuration = HibernateEhcacheUtils.loadAndCorrectConfiguration( url );
+ manager = CacheManager.create( configuration );
+ REFERENCE_COUNT.incrementAndGet();
+ }
+ mbeanRegistrationHelper.registerMBean( manager, properties );
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ throw new CacheException( e );
+ }
+ }
+ @Override
+ public void stop() {
+ try {
+ if ( manager != null ) {
+ if ( REFERENCE_COUNT.decrementAndGet() == 0 ) {
+ manager.shutdown();
+ }
+ manager = null;
+ }
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ throw new CacheException( e );
+ }
+ }
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/StrategyRegistrationProviderImpl.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/StrategyRegistrationProviderImpl.java
index 617fa48472..3cedfe4f0a 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/StrategyRegistrationProviderImpl.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/StrategyRegistrationProviderImpl.java
@@ -26,9 +26,9 @@ package org.hibernate.cache.ehcache;
import java.util.ArrayList;
import java.util.List;
+import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl;
import org.hibernate.boot.registry.selector.StrategyRegistration;
import org.hibernate.boot.registry.selector.StrategyRegistrationProvider;
-import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl;
import org.hibernate.cache.spi.RegionFactory;
/**
@@ -49,7 +49,8 @@ public class StrategyRegistrationProviderImpl implements StrategyRegistrationPro
EhCacheRegionFactory.class,
"ehcache",
EhCacheRegionFactory.class.getSimpleName(),
- "org.hibernate.cache.EhCacheRegionFactory" // legacy impl class name
+ // legacy impl class name
+ "org.hibernate.cache.EhCacheRegionFactory"
)
);
@@ -59,7 +60,8 @@ public class StrategyRegistrationProviderImpl implements StrategyRegistrationPro
SingletonEhCacheRegionFactory.class,
"ehcache-singleton",
SingletonEhCacheRegionFactory.class.getSimpleName(),
- "org.hibernate.cache.SingletonEhCacheRegionFactory" // legacy impl class name
+ // legacy impl class name
+ "org.hibernate.cache.SingletonEhCacheRegionFactory"
)
);
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/HibernateNonstopCacheExceptionHandler.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/HibernateNonstopCacheExceptionHandler.java
index af5b77a2e5..ebdf6da9de 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/HibernateNonstopCacheExceptionHandler.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/HibernateNonstopCacheExceptionHandler.java
@@ -24,6 +24,7 @@
package org.hibernate.cache.ehcache.internal.nonstop;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
+
import org.jboss.logging.Logger;
import org.hibernate.cache.ehcache.EhCacheMessageLogger;
@@ -35,61 +36,61 @@ import org.hibernate.cache.ehcache.EhCacheMessageLogger;
* @author Alex Snaps
*/
public final class HibernateNonstopCacheExceptionHandler {
- /**
- * Property name which set as "true" will throw exceptions on timeout with hibernate
- */
- public static final String HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY = "ehcache.hibernate.propagateNonStopCacheException";
+ /**
+ * Property name which set as "true" will throw exceptions on timeout with hibernate
+ */
+ public static final String HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY = "ehcache.hibernate.propagateNonStopCacheException";
- /**
- * Property name for logging the stack trace of the nonstop cache exception too. False by default
- */
- public static final String HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY = "ehcache.hibernate.logNonStopCacheExceptionStackTrace";
+ /**
+ * Property name for logging the stack trace of the nonstop cache exception too. False by default
+ */
+ public static final String HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY = "ehcache.hibernate.logNonStopCacheExceptionStackTrace";
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- HibernateNonstopCacheExceptionHandler.class.getName()
- );
- private static final HibernateNonstopCacheExceptionHandler INSTANCE = new HibernateNonstopCacheExceptionHandler();
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ HibernateNonstopCacheExceptionHandler.class.getName()
+ );
+ private static final HibernateNonstopCacheExceptionHandler INSTANCE = new HibernateNonstopCacheExceptionHandler();
- /**
- * private constructor
- */
- private HibernateNonstopCacheExceptionHandler() {
- // private
- }
+ /**
+ * private constructor
+ */
+ private HibernateNonstopCacheExceptionHandler() {
+ // private
+ }
- /**
- * Returns the singleton instance
- *
- * @return the singleton instance
- */
- public static HibernateNonstopCacheExceptionHandler getInstance() {
- return INSTANCE;
- }
+ /**
+ * Returns the singleton instance
+ *
+ * @return the singleton instance
+ */
+ public static HibernateNonstopCacheExceptionHandler getInstance() {
+ return INSTANCE;
+ }
- /**
- * Handle {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}.
- * If {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY} system property is set to true,
- * rethrows the {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}, otherwise logs the exception. While logging, if
- * {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY} is set to true, logs the exception stack
- * trace too, otherwise logs the exception message only
- *
- * @param nonStopCacheException
- */
- public void handleNonstopCacheException(NonStopCacheException nonStopCacheException) {
- if ( Boolean.getBoolean( HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY ) ) {
- throw nonStopCacheException;
- }
- else {
- if ( Boolean.getBoolean( HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY ) ) {
- LOG.debug(
- "Ignoring NonstopCacheException - " + nonStopCacheException.getMessage(),
- nonStopCacheException
- );
- }
- else {
- LOG.debug( "Ignoring NonstopCacheException - " + nonStopCacheException.getMessage() );
- }
- }
- }
+ /**
+ * Handle {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}.
+ * If {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY} system property is set to true,
+ * rethrows the {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}, otherwise logs the exception. While logging, if
+ * {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY} is set to true, logs the exception stack
+ * trace too, otherwise logs the exception message only
+ *
+ * @param nonStopCacheException The exception to handle
+ */
+ public void handleNonstopCacheException(NonStopCacheException nonStopCacheException) {
+ if ( Boolean.getBoolean( HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY ) ) {
+ throw nonStopCacheException;
+ }
+ else {
+ if ( Boolean.getBoolean( HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY ) ) {
+ LOG.debug(
+ "Ignoring NonstopCacheException - " + nonStopCacheException.getMessage(),
+ nonStopCacheException
+ );
+ }
+ else {
+ LOG.debug( "Ignoring NonstopCacheException - " + nonStopCacheException.getMessage() );
+ }
+ }
+ }
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAccessStrategyFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAccessStrategyFactory.java
index 93ab9c897c..b379584285 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAccessStrategyFactory.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAccessStrategyFactory.java
@@ -41,49 +41,49 @@ import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy;
*/
public class NonstopAccessStrategyFactory implements EhcacheAccessStrategyFactory {
- private final EhcacheAccessStrategyFactory actualFactory;
-
- /**
- * Constructor accepting the actual factory
- *
- * @param actualFactory
- */
- public NonstopAccessStrategyFactory(EhcacheAccessStrategyFactory actualFactory) {
- this.actualFactory = actualFactory;
- }
-
- /**
- * {@inheritDoc}
- */
- public EntityRegionAccessStrategy createEntityRegionAccessStrategy(EhcacheEntityRegion entityRegion, AccessType accessType) {
- return new NonstopAwareEntityRegionAccessStrategy(
- actualFactory.createEntityRegionAccessStrategy( entityRegion, accessType ),
- HibernateNonstopCacheExceptionHandler.getInstance()
- );
- }
-
- @Override
- public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion naturalIdRegion,
- AccessType accessType) {
- return new NonstopAwareNaturalIdRegionAccessStrategy(
- actualFactory.createNaturalIdRegionAccessStrategy(
- naturalIdRegion,
- accessType
- ), HibernateNonstopCacheExceptionHandler.getInstance()
- );
- }
+ private final EhcacheAccessStrategyFactory actualFactory;
/**
- * {@inheritDoc}
- */
- public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(EhcacheCollectionRegion collectionRegion,
- AccessType accessType) {
- return new NonstopAwareCollectionRegionAccessStrategy(
- actualFactory.createCollectionRegionAccessStrategy(
- collectionRegion,
- accessType
- ), HibernateNonstopCacheExceptionHandler.getInstance()
- );
- }
+ * Constructor accepting the actual factory
+ *
+ * @param actualFactory The wrapped RegionAccessStrategy factory
+ */
+ public NonstopAccessStrategyFactory(EhcacheAccessStrategyFactory actualFactory) {
+ this.actualFactory = actualFactory;
+ }
+
+ @Override
+ public EntityRegionAccessStrategy createEntityRegionAccessStrategy(
+ EhcacheEntityRegion entityRegion,
+ AccessType accessType) {
+ return new NonstopAwareEntityRegionAccessStrategy(
+ actualFactory.createEntityRegionAccessStrategy( entityRegion, accessType ),
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ );
+ }
+
+ @Override
+ public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(
+ EhcacheNaturalIdRegion naturalIdRegion,
+ AccessType accessType) {
+ return new NonstopAwareNaturalIdRegionAccessStrategy(
+ actualFactory.createNaturalIdRegionAccessStrategy(
+ naturalIdRegion,
+ accessType
+ ), HibernateNonstopCacheExceptionHandler.getInstance()
+ );
+ }
+
+ @Override
+ public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(
+ EhcacheCollectionRegion collectionRegion,
+ AccessType accessType) {
+ return new NonstopAwareCollectionRegionAccessStrategy(
+ actualFactory.createCollectionRegionAccessStrategy(
+ collectionRegion,
+ accessType
+ ), HibernateNonstopCacheExceptionHandler.getInstance()
+ );
+ }
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareCollectionRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareCollectionRegionAccessStrategy.java
index 3f1f2cc1db..fdd82bd9cf 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareCollectionRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareCollectionRegionAccessStrategy.java
@@ -38,188 +38,139 @@ import org.hibernate.cache.spi.access.SoftLock;
* @author Alex Snaps
*/
public class NonstopAwareCollectionRegionAccessStrategy implements CollectionRegionAccessStrategy {
-
private final CollectionRegionAccessStrategy actualStrategy;
private final HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler;
/**
* Constructor accepting the actual {@link CollectionRegionAccessStrategy} and the {@link HibernateNonstopCacheExceptionHandler}
*
- * @param actualStrategy
- * @param hibernateNonstopExceptionHandler
+ * @param actualStrategy The wrapped strategy
+ * @param hibernateNonstopExceptionHandler The exception handler
*/
- public NonstopAwareCollectionRegionAccessStrategy(CollectionRegionAccessStrategy actualStrategy,
- HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
+ public NonstopAwareCollectionRegionAccessStrategy(
+ CollectionRegionAccessStrategy actualStrategy,
+ HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
this.actualStrategy = actualStrategy;
this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler;
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#getRegion()
- */
+ @Override
public CollectionRegion getRegion() {
return actualStrategy.getRegion();
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evict(java.lang.Object)
- */
+ @Override
public void evict(Object key) throws CacheException {
try {
actualStrategy.evict( key );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll()
- */
+ @Override
public void evictAll() throws CacheException {
try {
actualStrategy.evictAll();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long)
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
return actualStrategy.get( key, txTimestamp );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
- */
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
try {
return actualStrategy.lockItem( key, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion()
- */
+ @Override
public SoftLock lockRegion() throws CacheException {
try {
return actualStrategy.lockRegion();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object,
- * boolean)
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version, minimalPutOverride );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#remove(java.lang.Object)
- */
+ @Override
public void remove(Object key) throws CacheException {
try {
actualStrategy.remove( key );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll()
- */
+ @Override
public void removeAll() throws CacheException {
try {
actualStrategy.removeAll();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
- */
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
try {
actualStrategy.unlockItem( key, lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockRegion(org.hibernate.cache.spi.access.SoftLock)
- */
+ @Override
public void unlockRegion(SoftLock lock) throws CacheException {
try {
actualStrategy.unlockRegion( lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareEntityRegionAccessStrategy.java
index 45f26270d0..e755bd0f28 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareEntityRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareEntityRegionAccessStrategy.java
@@ -38,253 +38,186 @@ import org.hibernate.cache.spi.access.SoftLock;
* @author Alex Snaps
*/
public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAccessStrategy {
-
private final EntityRegionAccessStrategy actualStrategy;
private final HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler;
/**
* Constructor accepting the actual {@link EntityRegionAccessStrategy} and the {@link HibernateNonstopCacheExceptionHandler}
*
- * @param actualStrategy
- * @param hibernateNonstopExceptionHandler
+ * @param actualStrategy The wrapped EntityRegionAccessStrategy
+ * @param hibernateNonstopExceptionHandler The exception handler
*/
- public NonstopAwareEntityRegionAccessStrategy(EntityRegionAccessStrategy actualStrategy,
- HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
+ public NonstopAwareEntityRegionAccessStrategy(
+ EntityRegionAccessStrategy actualStrategy,
+ HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
this.actualStrategy = actualStrategy;
this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler;
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#getRegion()
- */
+ @Override
public EntityRegion getRegion() {
return actualStrategy.getRegion();
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#afterInsert(java.lang.Object, java.lang.Object, java.lang.Object)
- */
+ @Override
public boolean afterInsert(Object key, Object value, Object version) throws CacheException {
try {
return actualStrategy.afterInsert( key, value, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#afterUpdate(java.lang.Object, java.lang.Object, java.lang.Object,
- * java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
- */
+ @Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock)
throws CacheException {
try {
return actualStrategy.afterUpdate( key, value, currentVersion, previousVersion, lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evict(java.lang.Object)
- */
+ @Override
public void evict(Object key) throws CacheException {
try {
actualStrategy.evict( key );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll()
- */
+ @Override
public void evictAll() throws CacheException {
try {
actualStrategy.evictAll();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long)
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
return actualStrategy.get( key, txTimestamp );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#insert(java.lang.Object, java.lang.Object, java.lang.Object)
- */
+ @Override
public boolean insert(Object key, Object value, Object version) throws CacheException {
try {
return actualStrategy.insert( key, value, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
- */
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
try {
return actualStrategy.lockItem( key, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion()
- */
+ @Override
public SoftLock lockRegion() throws CacheException {
try {
return actualStrategy.lockRegion();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object,
- * boolean)
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version, minimalPutOverride );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#remove(java.lang.Object)
- */
+ @Override
public void remove(Object key) throws CacheException {
try {
actualStrategy.remove( key );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll()
- */
+ @Override
public void removeAll() throws CacheException {
try {
actualStrategy.removeAll();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
- */
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
try {
actualStrategy.unlockItem( key, lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockRegion(org.hibernate.cache.spi.access.SoftLock)
- */
+ @Override
public void unlockRegion(SoftLock lock) throws CacheException {
try {
actualStrategy.unlockRegion( lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#update(java.lang.Object, java.lang.Object, java.lang.Object,
- * java.lang.Object)
- */
+ @Override
public boolean update(Object key, Object value, Object currentVersion, Object previousVersion)
throws CacheException {
try {
return actualStrategy.update( key, value, currentVersion, previousVersion );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareNaturalIdRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareNaturalIdRegionAccessStrategy.java
index 45e8498d5b..b50d6b1e20 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareNaturalIdRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareNaturalIdRegionAccessStrategy.java
@@ -38,28 +38,28 @@ import org.hibernate.cache.spi.access.SoftLock;
* @author Alex Snaps
*/
public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegionAccessStrategy {
-
private final NaturalIdRegionAccessStrategy actualStrategy;
private final HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler;
/**
* Constructor accepting the actual {@link NaturalIdRegionAccessStrategy} and the {@link HibernateNonstopCacheExceptionHandler}
*
- * @param actualStrategy
- * @param hibernateNonstopExceptionHandler
+ * @param actualStrategy The wrapped NaturalIdRegionAccessStrategy
+ * @param hibernateNonstopExceptionHandler The exception handler
*/
- public NonstopAwareNaturalIdRegionAccessStrategy(NaturalIdRegionAccessStrategy actualStrategy,
- HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
+ public NonstopAwareNaturalIdRegionAccessStrategy(
+ NaturalIdRegionAccessStrategy actualStrategy,
+ HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
this.actualStrategy = actualStrategy;
this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler;
}
-
+
@Override
public boolean insert(Object key, Object value) throws CacheException {
try {
return actualStrategy.insert( key, value );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
@@ -70,7 +70,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
try {
return actualStrategy.afterInsert( key, value );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
@@ -81,7 +81,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
try {
return actualStrategy.update( key, value );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
@@ -92,178 +92,129 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
try {
return actualStrategy.afterUpdate( key, value, lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#getRegion()
- */
+ @Override
public NaturalIdRegion getRegion() {
return actualStrategy.getRegion();
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evict(java.lang.Object)
- */
+ @Override
public void evict(Object key) throws CacheException {
try {
actualStrategy.evict( key );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll()
- */
+ @Override
public void evictAll() throws CacheException {
try {
actualStrategy.evictAll();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long)
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
return actualStrategy.get( key, txTimestamp );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
- */
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
try {
return actualStrategy.lockItem( key, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion()
- */
+ @Override
public SoftLock lockRegion() throws CacheException {
try {
return actualStrategy.lockRegion();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object,
- * boolean)
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version, minimalPutOverride );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#remove(java.lang.Object)
- */
+ @Override
public void remove(Object key) throws CacheException {
try {
actualStrategy.remove( key );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll()
- */
+ @Override
public void removeAll() throws CacheException {
try {
actualStrategy.removeAll();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
- */
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
try {
actualStrategy.unlockItem( key, lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockRegion(org.hibernate.cache.spi.access.SoftLock)
- */
+ @Override
public void unlockRegion(SoftLock lock) throws CacheException {
try {
actualStrategy.unlockRegion( lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/package-info.java
new file mode 100644
index 0000000000..1115173682
--- /dev/null
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/package-info.java
@@ -0,0 +1,5 @@
+/**
+ * Support for handling non-stop caches. Really no idea. The Ehcache guys added this and tbh I really do not
+ * understand the intent
+ */
+package org.hibernate.cache.ehcache.internal.nonstop;
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheCollectionRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheCollectionRegion.java
index d1fc60b8cf..e694bbebea 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheCollectionRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheCollectionRegion.java
@@ -47,22 +47,26 @@ import org.hibernate.cfg.Settings;
* @author Alex Snaps
*/
public class EhcacheCollectionRegion extends EhcacheTransactionalDataRegion implements CollectionRegion {
+ /**
+ * Constructs an EhcacheCollectionRegion around the given underlying cache.
+ *
+ * @param accessStrategyFactory The factory for building needed CollectionRegionAccessStrategy instance
+ * @param underlyingCache The ehcache cache instance
+ * @param settings The Hibernate settings
+ * @param metadata Metadata about the data to be cached in this region
+ * @param properties Any additional[ properties
+ */
+ public EhcacheCollectionRegion(
+ EhcacheAccessStrategyFactory accessStrategyFactory,
+ Ehcache underlyingCache,
+ Settings settings,
+ CacheDataDescription metadata,
+ Properties properties) {
+ super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
+ }
-
- /**
- * Constructs an EhcacheCollectionRegion around the given underlying cache.
- *
- * @param accessStrategyFactory
- */
- public EhcacheCollectionRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Settings settings,
- CacheDataDescription metadata, Properties properties) {
- super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
- }
-
- /**
- * {@inheritDoc}
- */
- public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
- return accessStrategyFactory.createCollectionRegionAccessStrategy( this, accessType );
- }
-}
\ No newline at end of file
+ @Override
+ public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
+ return getAccessStrategyFactory().createCollectionRegionAccessStrategy( this, accessType );
+ }
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheDataRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheDataRegion.java
index dfab454bf9..6f86f13ce7 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheDataRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheDataRegion.java
@@ -32,6 +32,7 @@ import java.util.Properties;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
import net.sf.ehcache.util.Timestamper;
+
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
@@ -52,174 +53,163 @@ import org.hibernate.cache.spi.Region;
* @author Alex Snaps
*/
public abstract class EhcacheDataRegion implements Region {
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ EhcacheDataRegion.class.getName()
+ );
+ private static final String CACHE_LOCK_TIMEOUT_PROPERTY = "net.sf.ehcache.hibernate.cache_lock_timeout";
+ private static final int DEFAULT_CACHE_LOCK_TIMEOUT = 60000;
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- EhcacheDataRegion.class.getName()
- );
- private static final String CACHE_LOCK_TIMEOUT_PROPERTY = "net.sf.ehcache.hibernate.cache_lock_timeout";
- private static final int DEFAULT_CACHE_LOCK_TIMEOUT = 60000;
-
- /**
- * Ehcache instance backing this Hibernate data region.
- */
- protected final Ehcache cache;
-
- /**
- * The {@link EhcacheAccessStrategyFactory} used for creating various access strategies
- */
- protected final EhcacheAccessStrategyFactory accessStrategyFactory;
-
- private final int cacheLockTimeout;
+ private final Ehcache cache;
+ private final EhcacheAccessStrategyFactory accessStrategyFactory;
+ private final int cacheLockTimeout;
- /**
- * Create a Hibernate data region backed by the given Ehcache instance.
- */
- EhcacheDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Properties properties) {
- this.accessStrategyFactory = accessStrategyFactory;
- this.cache = cache;
- String timeout = properties.getProperty(
- CACHE_LOCK_TIMEOUT_PROPERTY,
- Integer.toString( DEFAULT_CACHE_LOCK_TIMEOUT )
- );
- this.cacheLockTimeout = Timestamper.ONE_MS * Integer.decode( timeout );
- }
+ /**
+ * Create a Hibernate data region backed by the given Ehcache instance.
+ */
+ EhcacheDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Properties properties) {
+ this.accessStrategyFactory = accessStrategyFactory;
+ this.cache = cache;
+ final String timeout = properties.getProperty(
+ CACHE_LOCK_TIMEOUT_PROPERTY,
+ Integer.toString( DEFAULT_CACHE_LOCK_TIMEOUT )
+ );
+ this.cacheLockTimeout = Timestamper.ONE_MS * Integer.decode( timeout );
+ }
- /**
- * {@inheritDoc}
- */
- public String getName() {
- return cache.getName();
- }
+ /**
+ * Ehcache instance backing this Hibernate data region.
+ */
+ protected Ehcache getCache() {
+ return cache;
+ }
- /**
- * {@inheritDoc}
- */
- public void destroy() throws CacheException {
- try {
- cache.getCacheManager().removeCache( cache.getName() );
- }
- catch ( IllegalStateException e ) {
- //When Spring and Hibernate are both involved this will happen in normal shutdown operation.
- //Do not throw an exception, simply log this one.
- LOG.debug( "This can happen if multiple frameworks both try to shutdown ehcache", e );
- }
- catch ( net.sf.ehcache.CacheException e ) {
- if ( e instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) e );
- }
- else {
- throw new CacheException( e );
- }
- }
- }
+ /**
+ * The {@link org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory} used for creating
+ * various access strategies
+ */
+ protected EhcacheAccessStrategyFactory getAccessStrategyFactory() {
+ return accessStrategyFactory;
+ }
- /**
- * {@inheritDoc}
- */
- public long getSizeInMemory() {
- try {
- return cache.calculateInMemorySize();
- }
- catch ( Throwable t ) {
- if ( t instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) t );
- }
- return -1;
- }
- }
+ /**
+ * Return the Ehcache instance backing this Hibernate data region.
+ *
+ * @return The underlying ehcache cache
+ */
+ public Ehcache getEhcache() {
+ return getCache();
+ }
- /**
- * {@inheritDoc}
- */
- public long getElementCountInMemory() {
- try {
- return cache.getMemoryStoreSize();
- }
- catch ( net.sf.ehcache.CacheException ce ) {
- if ( ce instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) ce );
- return -1;
- }
- else {
- throw new CacheException( ce );
- }
- }
- }
+ @Override
+ public String getName() {
+ return getCache().getName();
+ }
- /**
- * {@inheritDoc}
- */
- public long getElementCountOnDisk() {
- try {
- return cache.getDiskStoreSize();
- }
- catch ( net.sf.ehcache.CacheException ce ) {
- if ( ce instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) ce );
- return -1;
- }
- else {
- throw new CacheException( ce );
- }
- }
- }
+ @Override
+ public void destroy() throws CacheException {
+ try {
+ getCache().getCacheManager().removeCache( getCache().getName() );
+ }
+ catch (IllegalStateException e) {
+ //When Spring and Hibernate are both involved this will happen in normal shutdown operation.
+ //Do not throw an exception, simply log this one.
+ LOG.debug( "This can happen if multiple frameworks both try to shutdown ehcache", e );
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ if ( e instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) e );
+ }
+ else {
+ throw new CacheException( e );
+ }
+ }
+ }
- /**
- * {@inheritDoc}
- */
- public Map toMap() {
- try {
- Map result = new HashMap();
- for ( Object key : cache.getKeys() ) {
- result.put( key, cache.get( key ).getObjectValue() );
- }
- return result;
- }
- catch ( Exception e ) {
- if ( e instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) e );
- return Collections.emptyMap();
- }
- else {
- throw new CacheException( e );
- }
- }
- }
+ @Override
+ public long getSizeInMemory() {
+ try {
+ return getCache().calculateInMemorySize();
+ }
+ catch (Throwable t) {
+ if ( t instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) t );
+ }
+ return -1;
+ }
+ }
- /**
- * {@inheritDoc}
- */
- public long nextTimestamp() {
- return Timestamper.next();
- }
+ @Override
+ public long getElementCountInMemory() {
+ try {
+ return getCache().getMemoryStoreSize();
+ }
+ catch (net.sf.ehcache.CacheException ce) {
+ if ( ce instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) ce );
+ return -1;
+ }
+ else {
+ throw new CacheException( ce );
+ }
+ }
+ }
- /**
- * {@inheritDoc}
- */
- public int getTimeout() {
- return cacheLockTimeout;
- }
+ @Override
+ public long getElementCountOnDisk() {
+ try {
+ return getCache().getDiskStoreSize();
+ }
+ catch (net.sf.ehcache.CacheException ce) {
+ if ( ce instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) ce );
+ return -1;
+ }
+ else {
+ throw new CacheException( ce );
+ }
+ }
+ }
- /**
- * Return the Ehcache instance backing this Hibernate data region.
- */
- public Ehcache getEhcache() {
- return cache;
- }
+ @Override
+ public Map toMap() {
+ try {
+ final Map result = new HashMap();
+ for ( Object key : getCache().getKeys() ) {
+ result.put( key, getCache().get( key ).getObjectValue() );
+ }
+ return result;
+ }
+ catch (Exception e) {
+ if ( e instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) e );
+ return Collections.emptyMap();
+ }
+ else {
+ throw new CacheException( e );
+ }
+ }
+ }
+
+ @Override
+ public long nextTimestamp() {
+ return Timestamper.next();
+ }
+
+ @Override
+ public int getTimeout() {
+ return cacheLockTimeout;
+ }
+
+ @Override
+ public boolean contains(Object key) {
+ return getCache().isKeyInCache( key );
+ }
- /**
- * Returns true
if this region contains data for the given key.
- *
- * This is a Hibernate 3.5 method.
- */
- public boolean contains(Object key) {
- return cache.isKeyInCache( key );
- }
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheEntityRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheEntityRegion.java
index 4092c387ea..5423950d03 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheEntityRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheEntityRegion.java
@@ -46,22 +46,26 @@ import org.hibernate.cfg.Settings;
* @author Alex Snaps
*/
public class EhcacheEntityRegion extends EhcacheTransactionalDataRegion implements EntityRegion {
+ /**
+ * Constructs an EhcacheCollectionRegion around the given underlying cache.
+ *
+ * @param accessStrategyFactory The factory for building needed EntityRegionAccessStrategy instance
+ * @param underlyingCache The ehcache cache instance
+ * @param settings The Hibernate settings
+ * @param metadata Metadata about the data to be cached in this region
+ * @param properties Any additional[ properties
+ */
+ public EhcacheEntityRegion(
+ EhcacheAccessStrategyFactory accessStrategyFactory,
+ Ehcache underlyingCache,
+ Settings settings,
+ CacheDataDescription metadata,
+ Properties properties) {
+ super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
+ }
-
- /**
- * Constructs an EhcacheEntityRegion around the given underlying cache.
- *
- * @param accessStrategyFactory
- */
- public EhcacheEntityRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Settings settings,
- CacheDataDescription metadata, Properties properties) {
- super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
- }
-
- /**
- * {@inheritDoc}
- */
- public EntityRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
- return accessStrategyFactory.createEntityRegionAccessStrategy( this, accessType );
- }
-}
\ No newline at end of file
+ @Override
+ public EntityRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
+ return getAccessStrategyFactory().createEntityRegionAccessStrategy( this, accessType );
+ }
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheGeneralDataRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheGeneralDataRegion.java
index 8af54afb93..79bbbdeaa4 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheGeneralDataRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheGeneralDataRegion.java
@@ -28,6 +28,7 @@ import java.util.Properties;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
+
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
@@ -48,119 +49,117 @@ import org.hibernate.cache.spi.GeneralDataRegion;
* @author Alex Snaps
*/
abstract class EhcacheGeneralDataRegion extends EhcacheDataRegion implements GeneralDataRegion {
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ EhcacheGeneralDataRegion.class.getName()
+ );
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- EhcacheGeneralDataRegion.class.getName()
- );
+ /**
+ * Constructs an EhcacheGeneralDataRegion around the given underlying cache.
+ *
+ * @param accessStrategyFactory The factory for building needed RegionAccessStrategy instance
+ * @param underlyingCache The ehcache cache instance
+ * @param properties Any additional[ properties
+ */
+ public EhcacheGeneralDataRegion(
+ EhcacheAccessStrategyFactory accessStrategyFactory,
+ Ehcache underlyingCache,
+ Properties properties) {
+ super( accessStrategyFactory, underlyingCache, properties );
+ }
- /**
- * Creates an EhcacheGeneralDataRegion using the given Ehcache instance as a backing.
- */
- public EhcacheGeneralDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Properties properties) {
- super( accessStrategyFactory, cache, properties );
- }
+ @Override
+ public Object get(Object key) throws CacheException {
+ try {
+ LOG.debugf( "key: %s", key );
+ if ( key == null ) {
+ return null;
+ }
+ else {
+ final Element element = getCache().get( key );
+ if ( element == null ) {
+ LOG.debugf( "Element for key %s is null", key );
+ return null;
+ }
+ else {
+ return element.getObjectValue();
+ }
+ }
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ if ( e instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) e );
+ return null;
+ }
+ else {
+ throw new CacheException( e );
+ }
+ }
+ }
- /**
- * {@inheritDoc}
- */
- public Object get(Object key) throws CacheException {
- try {
- LOG.debugf( "key: %s", key );
- if ( key == null ) {
- return null;
- }
- else {
- Element element = cache.get( key );
- if ( element == null ) {
- LOG.debugf( "Element for key %s is null", key );
- return null;
- }
- else {
- return element.getObjectValue();
- }
- }
- }
- catch ( net.sf.ehcache.CacheException e ) {
- if ( e instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) e );
- return null;
- }
- else {
- throw new CacheException( e );
- }
- }
- }
+ @Override
+ public void put(Object key, Object value) throws CacheException {
+ LOG.debugf( "key: %s value: %s", key, value );
+ try {
+ final Element element = new Element( key, value );
+ getCache().put( element );
+ }
+ catch (IllegalArgumentException e) {
+ throw new CacheException( e );
+ }
+ catch (IllegalStateException e) {
+ throw new CacheException( e );
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ if ( e instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) e );
+ }
+ else {
+ throw new CacheException( e );
+ }
+ }
+ }
- /**
- * {@inheritDoc}
- */
- public void put(Object key, Object value) throws CacheException {
- LOG.debugf( "key: %s value: %s", key, value );
- try {
- Element element = new Element( key, value );
- cache.put( element );
- }
- catch ( IllegalArgumentException e ) {
- throw new CacheException( e );
- }
- catch ( IllegalStateException e ) {
- throw new CacheException( e );
- }
- catch ( net.sf.ehcache.CacheException e ) {
- if ( e instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) e );
- }
- else {
- throw new CacheException( e );
- }
- }
- }
+ @Override
+ public void evict(Object key) throws CacheException {
+ try {
+ getCache().remove( key );
+ }
+ catch (ClassCastException e) {
+ throw new CacheException( e );
+ }
+ catch (IllegalStateException e) {
+ throw new CacheException( e );
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ if ( e instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) e );
+ }
+ else {
+ throw new CacheException( e );
+ }
+ }
+ }
- /**
- * {@inheritDoc}
- */
- public void evict(Object key) throws CacheException {
- try {
- cache.remove( key );
- }
- catch ( ClassCastException e ) {
- throw new CacheException( e );
- }
- catch ( IllegalStateException e ) {
- throw new CacheException( e );
- }
- catch ( net.sf.ehcache.CacheException e ) {
- if ( e instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) e );
- }
- else {
- throw new CacheException( e );
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void evictAll() throws CacheException {
- try {
- cache.removeAll();
- }
- catch ( IllegalStateException e ) {
- throw new CacheException( e );
- }
- catch ( net.sf.ehcache.CacheException e ) {
- if ( e instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) e );
- }
- else {
- throw new CacheException( e );
- }
- }
- }
+ @Override
+ public void evictAll() throws CacheException {
+ try {
+ getCache().removeAll();
+ }
+ catch (IllegalStateException e) {
+ throw new CacheException( e );
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ if ( e instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) e );
+ }
+ else {
+ throw new CacheException( e );
+ }
+ }
+ }
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheNaturalIdRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheNaturalIdRegion.java
index 92d7c9d227..ab3b03b224 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheNaturalIdRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheNaturalIdRegion.java
@@ -47,20 +47,26 @@ import org.hibernate.cfg.Settings;
* @author Alex Snaps
*/
public class EhcacheNaturalIdRegion extends EhcacheTransactionalDataRegion implements NaturalIdRegion {
-
-
- /**
- * Constructs an EhcacheNaturalIdRegion around the given underlying cache.
- *
- * @param accessStrategyFactory
- */
- public EhcacheNaturalIdRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Settings settings,
- CacheDataDescription metadata, Properties properties) {
- super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
- }
+ /**
+ * Constructs an EhcacheNaturalIdRegion around the given underlying cache.
+ *
+ * @param accessStrategyFactory The factory for building needed NaturalIdRegionAccessStrategy instance
+ * @param underlyingCache The ehcache cache instance
+ * @param settings The Hibernate settings
+ * @param metadata Metadata about the data to be cached in this region
+ * @param properties Any additional[ properties
+ */
+ public EhcacheNaturalIdRegion(
+ EhcacheAccessStrategyFactory accessStrategyFactory,
+ Ehcache underlyingCache,
+ Settings settings,
+ CacheDataDescription metadata,
+ Properties properties) {
+ super( accessStrategyFactory, underlyingCache, settings, metadata, properties );
+ }
@Override
public NaturalIdRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
- return accessStrategyFactory.createNaturalIdRegionAccessStrategy( this, accessType );
+ return getAccessStrategyFactory().createNaturalIdRegionAccessStrategy( this, accessType );
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheQueryResultsRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheQueryResultsRegion.java
index f7952f98db..5305af419a 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheQueryResultsRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheQueryResultsRegion.java
@@ -37,14 +37,18 @@ import org.hibernate.cache.spi.QueryResultsRegion;
* @author Alex Snaps
*/
public class EhcacheQueryResultsRegion extends EhcacheGeneralDataRegion implements QueryResultsRegion {
-
/**
* Constructs an EhcacheQueryResultsRegion around the given underlying cache.
*
- * @param accessStrategyFactory
+ * @param accessStrategyFactory The factory for building needed CollectionRegionAccessStrategy instance
+ * @param underlyingCache The ehcache cache instance
+ * @param properties Any additional[ properties
*/
- public EhcacheQueryResultsRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Properties properties) {
+ public EhcacheQueryResultsRegion(
+ EhcacheAccessStrategyFactory accessStrategyFactory,
+ Ehcache underlyingCache,
+ Properties properties) {
super( accessStrategyFactory, underlyingCache, properties );
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTimestampsRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTimestampsRegion.java
index bbc87dfd00..cc3316853e 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTimestampsRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTimestampsRegion.java
@@ -38,13 +38,17 @@ import org.hibernate.cache.spi.TimestampsRegion;
* @author Alex Snaps
*/
public class EhcacheTimestampsRegion extends EhcacheGeneralDataRegion implements TimestampsRegion {
-
/**
* Constructs an EhcacheTimestampsRegion around the given underlying cache.
*
- * @param accessStrategyFactory
+ * @param accessStrategyFactory The factory for building needed CollectionRegionAccessStrategy instance
+ * @param underlyingCache The ehcache cache instance
+ * @param properties Any additional[ properties
*/
- public EhcacheTimestampsRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Properties properties) {
- super(accessStrategyFactory, underlyingCache, properties);
+ public EhcacheTimestampsRegion(
+ EhcacheAccessStrategyFactory accessStrategyFactory,
+ Ehcache underlyingCache,
+ Properties properties) {
+ super( accessStrategyFactory, underlyingCache, properties );
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTransactionalDataRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTransactionalDataRegion.java
index 60f4e92c9e..d46513cbe6 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTransactionalDataRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTransactionalDataRegion.java
@@ -51,13 +51,9 @@ import org.hibernate.cfg.Settings;
* @author Alex Snaps
*/
public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements TransactionalDataRegion {
-
private static final int LOCAL_LOCK_PROVIDER_CONCURRENCY = 128;
- /**
- * Hibernate settings associated with the persistence unit.
- */
- protected final Settings settings;
+ private final Settings settings;
/**
* Metadata associated with the objects stored in the region.
@@ -69,13 +65,14 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Construct an transactional Hibernate cache region around the given Ehcache instance.
*/
- EhcacheTransactionalDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Settings settings,
- CacheDataDescription metadata, Properties properties) {
+ EhcacheTransactionalDataRegion(
+ EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Settings settings,
+ CacheDataDescription metadata, Properties properties) {
super( accessStrategyFactory, cache, properties );
this.settings = settings;
this.metadata = metadata;
- Object context = cache.getInternalContext();
+ final Object context = cache.getInternalContext();
if ( context instanceof CacheLockProvider ) {
this.lockProvider = (CacheLockProvider) context;
}
@@ -85,7 +82,7 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
}
/**
- * Return the hibernate settings
+ * Access the Hibernate settings associated with the persistence unit.
*
* @return settings
*/
@@ -93,26 +90,26 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
return settings;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean isTransactionAware() {
return false;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public CacheDataDescription getCacheDataDescription() {
return metadata;
}
/**
* Get the value mapped to this key, or null if no value is mapped to this key.
+ *
+ * @param key The cache key
+ *
+ * @return The cached data
*/
public final Object get(Object key) {
try {
- Element element = cache.get( key );
+ final Element element = getCache().get( key );
if ( element == null ) {
return null;
}
@@ -120,7 +117,7 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
return element.getObjectValue();
}
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -134,19 +131,24 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Map the given value to the given key, replacing any existing mapping for this key
+ *
+ * @param key The cache key
+ * @param value The data to cache
+ *
+ * @throws CacheException Indicates a problem accessing the cache
*/
public final void put(Object key, Object value) throws CacheException {
try {
- Element element = new Element( key, value );
- cache.put( element );
+ final Element element = new Element( key, value );
+ getCache().put( element );
}
- catch ( IllegalArgumentException e ) {
+ catch (IllegalArgumentException e) {
throw new CacheException( e );
}
- catch ( IllegalStateException e ) {
+ catch (IllegalStateException e) {
throw new CacheException( e );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -159,18 +161,22 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Remove the mapping for this key (if any exists).
+ *
+ * @param key The cache key
+ *
+ * @throws CacheException Indicates a problem accessing the cache
*/
public final void remove(Object key) throws CacheException {
try {
- cache.remove( key );
+ getCache().remove( key );
}
- catch ( ClassCastException e ) {
+ catch (ClassCastException e) {
throw new CacheException( e );
}
- catch ( IllegalStateException e ) {
+ catch (IllegalStateException e) {
throw new CacheException( e );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -183,15 +189,17 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Remove all mapping from this cache region.
+ *
+ * @throws CacheException Indicates a problem accessing the cache
*/
public final void clear() throws CacheException {
try {
- cache.removeAll();
+ getCache().removeAll();
}
- catch ( IllegalStateException e ) {
+ catch (IllegalStateException e) {
throw new CacheException( e );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -204,12 +212,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Attempts to write lock the mapping for the given key.
+ *
+ * @param key The cache key
+ *
+ * @throws CacheException Indicates a problem accessing the cache
*/
public final void writeLock(Object key) {
try {
lockProvider.getSyncForKey( key ).lock( LockType.WRITE );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -222,12 +234,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Attempts to write unlock the mapping for the given key.
+ *
+ * @param key The cache key
+ *
+ * @throws CacheException Indicates a problem accessing the cache
*/
public final void writeUnlock(Object key) {
try {
lockProvider.getSyncForKey( key ).unlock( LockType.WRITE );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -240,12 +256,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Attempts to read lock the mapping for the given key.
+ *
+ * @param key The cache key
+ *
+ * @throws CacheException Indicates a problem accessing the cache
*/
public final void readLock(Object key) {
try {
lockProvider.getSyncForKey( key ).lock( LockType.WRITE );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -258,12 +278,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Attempts to read unlock the mapping for the given key.
+ *
+ * @param key The cache key
+ *
+ * @throws CacheException Indicates a problem accessing the cache
*/
public final void readUnlock(Object key) {
try {
lockProvider.getSyncForKey( key ).unlock( LockType.WRITE );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -279,6 +303,8 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
*
* 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;
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/package-info.java
new file mode 100644
index 0000000000..ff6247faea
--- /dev/null
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines {@link org.hibernate.cache.spi.RegionFactory} support for the Ehcache integration
+ */
+package org.hibernate.cache.ehcache.internal.regions;
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/AbstractEhcacheAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/AbstractEhcacheAccessStrategy.java
index 8703256b06..260bd0ccff 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/AbstractEhcacheAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/AbstractEhcacheAccessStrategy.java
@@ -37,24 +37,34 @@ import org.hibernate.cfg.Settings;
* @author Alex Snaps
*/
abstract class AbstractEhcacheAccessStrategy {
-
- /**
- * The wrapped Hibernate cache region.
- */
- protected final T region;
- /**
- * The settings for this persistence unit.
- */
- protected final Settings settings;
+ private final T region;
+ private final Settings settings;
/**
* Create an access strategy wrapping the given region.
+ *
+ * @param region The wrapped region. Accessible to subclasses via {@link #region()}
+ * @param settings The Hibernate settings. Accessible to subclasses via {@link #settings()}
*/
AbstractEhcacheAccessStrategy(T region, Settings settings) {
this.region = region;
this.settings = settings;
}
+ /**
+ * The wrapped Hibernate cache region.
+ */
+ protected T region() {
+ return region;
+ }
+
+ /**
+ * The settings for this persistence unit.
+ */
+ protected Settings settings() {
+ return settings;
+ }
+
/**
* This method is a placeholder for method signatures supplied by interfaces pulled in further down the class
* hierarchy.
@@ -84,6 +94,7 @@ abstract class AbstractEhcacheAccessStrategy
- extends AbstractEhcacheAccessStrategy {
+abstract class AbstractReadWriteEhcacheAccessStrategy
+ extends AbstractEhcacheAccessStrategy {
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- AbstractReadWriteEhcacheAccessStrategy.class.getName()
- );
- private final UUID uuid = UUID.randomUUID();
- private final AtomicLong nextLockId = new AtomicLong();
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ AbstractReadWriteEhcacheAccessStrategy.class.getName()
+ );
- private final Comparator versionComparator;
+ private final UUID uuid = UUID.randomUUID();
+ private final AtomicLong nextLockId = new AtomicLong();
- /**
- * Creates a read/write cache access strategy around the given cache region.
- */
- public AbstractReadWriteEhcacheAccessStrategy(T region, Settings settings) {
- super( region, settings );
- this.versionComparator = region.getCacheDataDescription().getVersionComparator();
- }
+ private final Comparator versionComparator;
- /**
- * Returns null
if the item is not readable. Locked items are not readable, nor are items created
- * after the start of this transaction.
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long)
- * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#get(java.lang.Object, long)
- */
- public final Object get(Object key, long txTimestamp) throws CacheException {
- readLockIfNeeded( key );
- try {
- Lockable item = (Lockable) region.get( key );
+ /**
+ * Creates a read/write cache access strategy around the given cache region.
+ */
+ public AbstractReadWriteEhcacheAccessStrategy(T region, Settings settings) {
+ super( region, settings );
+ this.versionComparator = region.getCacheDataDescription().getVersionComparator();
+ }
- boolean readable = item != null && item.isReadable( txTimestamp );
- if ( readable ) {
- return item.getValue();
- }
- else {
- return null;
- }
- }
- finally {
- readUnlockIfNeeded( key );
- }
- }
+ /**
+ * Returns null
if the item is not readable. Locked items are not readable, nor are items created
+ * after the start of this transaction.
+ *
+ * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long)
+ * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#get(java.lang.Object, long)
+ */
+ public final Object get(Object key, long txTimestamp) throws CacheException {
+ readLockIfNeeded( key );
+ try {
+ final Lockable item = (Lockable) region().get( key );
- /**
- * Returns false
and fails to put the value if there is an existing un-writeable item mapped to this
- * key.
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)
- * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)
- */
- @Override
- public final boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
- throws CacheException {
- region.writeLock( key );
- try {
- Lockable item = (Lockable) region.get( key );
- boolean writeable = item == null || item.isWriteable( txTimestamp, version, versionComparator );
- if ( writeable ) {
- region.put( key, new Item( value, version, region.nextTimestamp() ) );
- return true;
- }
- else {
- return false;
- }
- }
- finally {
- region.writeUnlock( key );
- }
- }
+ final boolean readable = item != null && item.isReadable( txTimestamp );
+ if ( readable ) {
+ return item.getValue();
+ }
+ else {
+ return null;
+ }
+ }
+ finally {
+ readUnlockIfNeeded( key );
+ }
+ }
- /**
- * Soft-lock a cache item.
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
- * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
- */
- public final SoftLock lockItem(Object key, Object version) throws CacheException {
- region.writeLock( key );
- try {
- Lockable item = (Lockable) region.get( key );
- long timeout = region.nextTimestamp() + region.getTimeout();
- final Lock lock = ( item == null ) ? new Lock( timeout, uuid, nextLockId(), version ) : item.lock(
- timeout,
- uuid,
- nextLockId()
- );
- region.put( key, lock );
- return lock;
- }
- finally {
- region.writeUnlock( key );
- }
- }
+ /**
+ * Returns false
and fails to put the value if there is an existing un-writeable item mapped to this
+ * key.
+ *
+ * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)
+ * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean)
+ */
+ @Override
+ public final boolean putFromLoad(
+ Object key,
+ Object value,
+ long txTimestamp,
+ Object version,
+ boolean minimalPutOverride)
+ throws CacheException {
+ region().writeLock( key );
+ try {
+ final Lockable item = (Lockable) region().get( key );
+ final boolean writeable = item == null || item.isWriteable( txTimestamp, version, versionComparator );
+ if ( writeable ) {
+ region().put( key, new Item( value, version, region().nextTimestamp() ) );
+ return true;
+ }
+ else {
+ return false;
+ }
+ }
+ finally {
+ region().writeUnlock( key );
+ }
+ }
- /**
- * Soft-unlock a cache item.
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
- * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
- */
- public final void unlockItem(Object key, SoftLock lock) throws CacheException {
- region.writeLock( key );
- try {
- Lockable item = (Lockable) region.get( key );
+ /**
+ * Soft-lock a cache item.
+ *
+ * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
+ * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
+ */
+ public final SoftLock lockItem(Object key, Object version) throws CacheException {
+ region().writeLock( key );
+ try {
+ final Lockable item = (Lockable) region().get( key );
+ final long timeout = region().nextTimestamp() + region().getTimeout();
+ final Lock lock = (item == null) ? new Lock( timeout, uuid, nextLockId(), version ) : item.lock(
+ timeout,
+ uuid,
+ nextLockId()
+ );
+ region().put( key, lock );
+ return lock;
+ }
+ finally {
+ region().writeUnlock( key );
+ }
+ }
- if ( ( item != null ) && item.isUnlockable( lock ) ) {
- decrementLock( key, (Lock) item );
- }
- else {
- handleLockExpiry( key, item );
- }
- }
- finally {
- region.writeUnlock( key );
- }
- }
+ /**
+ * Soft-unlock a cache item.
+ *
+ * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
+ * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
+ */
+ public final void unlockItem(Object key, SoftLock lock) throws CacheException {
+ region().writeLock( key );
+ try {
+ final Lockable item = (Lockable) region().get( key );
- private long nextLockId() {
- return nextLockId.getAndIncrement();
- }
+ if ( (item != null) && item.isUnlockable( lock ) ) {
+ decrementLock( key, (Lock) item );
+ }
+ else {
+ handleLockExpiry( key, item );
+ }
+ }
+ finally {
+ region().writeUnlock( key );
+ }
+ }
- /**
- * Unlock and re-put the given key, lock combination.
- */
- protected void decrementLock(Object key, Lock lock) {
- lock.unlock( region.nextTimestamp() );
- region.put( key, lock );
- }
+ private long nextLockId() {
+ return nextLockId.getAndIncrement();
+ }
- /**
- * Handle the timeout of a previous lock mapped to this key
- */
- protected void handleLockExpiry(Object key, Lockable lock) {
- LOG.softLockedCacheExpired( region.getName(), key, lock == null ? "(null)" : lock.toString() );
+ /**
+ * Unlock and re-put the given key, lock combination.
+ */
+ protected void decrementLock(Object key, Lock lock) {
+ lock.unlock( region().nextTimestamp() );
+ region().put( key, lock );
+ }
- long ts = region.nextTimestamp() + region.getTimeout();
- // create new lock that times out immediately
- Lock newLock = new Lock( ts, uuid, nextLockId.getAndIncrement(), null );
- newLock.unlock( ts );
- region.put( key, newLock );
- }
+ /**
+ * Handle the timeout of a previous lock mapped to this key
+ */
+ protected void handleLockExpiry(Object key, Lockable lock) {
+ LOG.softLockedCacheExpired( region().getName(), key, lock == null ? "(null)" : lock.toString() );
- /**
- * Read lock the entry for the given key if internal cache locks will not provide correct exclusion.
- */
- private void readLockIfNeeded(Object key) {
- if ( region.locksAreIndependentOfCache() ) {
- region.readLock( key );
- }
- }
+ final long ts = region().nextTimestamp() + region().getTimeout();
+ // create new lock that times out immediately
+ final Lock newLock = new Lock( ts, uuid, nextLockId.getAndIncrement(), null );
+ newLock.unlock( ts );
+ region().put( key, newLock );
+ }
- /**
- * Read unlock the entry for the given key if internal cache locks will not provide correct exclusion.
- */
- private void readUnlockIfNeeded(Object key) {
- if ( region.locksAreIndependentOfCache() ) {
- region.readUnlock( key );
- }
- }
+ /**
+ * Read lock the entry for the given key if internal cache locks will not provide correct exclusion.
+ */
+ private void readLockIfNeeded(Object key) {
+ if ( region().locksAreIndependentOfCache() ) {
+ region().readLock( key );
+ }
+ }
- /**
- * Interface type implemented by all wrapper objects in the cache.
- */
- protected static interface Lockable {
+ /**
+ * Read unlock the entry for the given key if internal cache locks will not provide correct exclusion.
+ */
+ private void readUnlockIfNeeded(Object key) {
+ if ( region().locksAreIndependentOfCache() ) {
+ region().readUnlock( key );
+ }
+ }
- /**
- * Returns true
if the enclosed value can be read by a transaction started at the given time.
- */
- public boolean isReadable(long txTimestamp);
+ /**
+ * Interface type implemented by all wrapper objects in the cache.
+ */
+ protected static interface Lockable {
- /**
- * Returns true
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 true
if the enclosed value can be read by a transaction started at the given time.
+ */
+ public boolean isReadable(long txTimestamp);
- /**
- * Returns the enclosed value.
- */
- public Object getValue();
+ /**
+ * Returns true
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 true
if the given lock can be unlocked using the given SoftLock instance as a handle.
- */
- public boolean isUnlockable(SoftLock lock);
+ /**
+ * Returns the enclosed value.
+ */
+ public Object getValue();
- /**
- * Locks this entry, stamping it with the UUID and lockId given, with the lock timeout occuring at the specified
- * time. The returned Lock object can be used to unlock the entry in the future.
- */
- public Lock lock(long timeout, UUID uuid, long lockId);
- }
+ /**
+ * Returns true
if the given lock can be unlocked using the given SoftLock instance as a handle.
+ */
+ public boolean isUnlockable(SoftLock lock);
- /**
- * Wrapper type representing unlocked items.
- */
- protected final static class Item implements Serializable, Lockable {
+ /**
+ * Locks this entry, stamping it with the UUID and lockId given, with the lock timeout occuring at the specified
+ * time. The returned Lock object can be used to unlock the entry in the future.
+ */
+ public Lock lock(long timeout, UUID uuid, long lockId);
+ }
- private static final long serialVersionUID = 1L;
- private final Object value;
- private final Object version;
- private final long timestamp;
+ /**
+ * Wrapper type representing unlocked items.
+ */
+ protected static final class Item implements Serializable, Lockable {
+ private static final long serialVersionUID = 1L;
+ private final Object value;
+ private final Object version;
+ private final long timestamp;
- /**
- * Creates an unlocked item wrapping the given value with a version and creation timestamp.
- */
- Item(Object value, Object version, long timestamp) {
- this.value = value;
- this.version = version;
- this.timestamp = timestamp;
- }
+ /**
+ * Creates an unlocked item wrapping the given value with a version and creation timestamp.
+ */
+ Item(Object value, Object version, long timestamp) {
+ this.value = value;
+ this.version = version;
+ this.timestamp = timestamp;
+ }
- /**
- * {@inheritDoc}
- */
- public boolean isReadable(long txTimestamp) {
- return txTimestamp > timestamp;
- }
+ @Override
+ public boolean isReadable(long txTimestamp) {
+ return txTimestamp > timestamp;
+ }
- /**
- * {@inheritDoc}
- */
- public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) {
- return version != null && versionComparator.compare( version, newVersion ) < 0;
- }
+ @Override
+ @SuppressWarnings("unchecked")
+ public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) {
+ return version != null && versionComparator.compare( version, newVersion ) < 0;
+ }
- /**
- * {@inheritDoc}
- */
- public Object getValue() {
- return value;
- }
+ @Override
+ public Object getValue() {
+ return value;
+ }
- /**
- * {@inheritDoc}
- */
- public boolean isUnlockable(SoftLock lock) {
- return false;
- }
+ @Override
+ public boolean isUnlockable(SoftLock lock) {
+ return false;
+ }
- /**
- * {@inheritDoc}
- */
- public Lock lock(long timeout, UUID uuid, long lockId) {
- return new Lock( timeout, uuid, lockId, version );
- }
- }
+ @Override
+ public Lock lock(long timeout, UUID uuid, long lockId) {
+ return new Lock( timeout, uuid, lockId, version );
+ }
+ }
- /**
- * Wrapper type representing locked items.
- */
- protected final static class Lock implements Serializable, Lockable, SoftLock {
+ /**
+ * Wrapper type representing locked items.
+ */
+ protected static final class Lock implements Serializable, Lockable, SoftLock {
+ private static final long serialVersionUID = 2L;
- private static final long serialVersionUID = 2L;
+ private final UUID sourceUuid;
+ private final long lockId;
+ private final Object version;
- private final UUID sourceUuid;
- private final long lockId;
- private final Object version;
+ private long timeout;
+ private boolean concurrent;
+ private int multiplicity = 1;
+ private long unlockTimestamp;
- private long timeout;
- private boolean concurrent;
- private int multiplicity = 1;
- private long unlockTimestamp;
+ /**
+ * Creates a locked item with the given identifiers and object version.
+ */
+ Lock(long timeout, UUID sourceUuid, long lockId, Object version) {
+ this.timeout = timeout;
+ this.lockId = lockId;
+ this.version = version;
+ this.sourceUuid = sourceUuid;
+ }
- /**
- * Creates a locked item with the given identifiers and object version.
- */
- Lock(long timeout, UUID sourceUuid, long lockId, Object version) {
- this.timeout = timeout;
- this.lockId = lockId;
- this.version = version;
- this.sourceUuid = sourceUuid;
- }
+ @Override
+ public boolean isReadable(long txTimestamp) {
+ return false;
+ }
- /**
- * {@inheritDoc}
- */
- public boolean isReadable(long txTimestamp) {
- return false;
- }
+ @Override
+ @SuppressWarnings({"SimplifiableIfStatement", "unchecked"})
+ public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) {
+ if ( txTimestamp > timeout ) {
+ // if timedout then allow write
+ return true;
+ }
+ if ( multiplicity > 0 ) {
+ // if still locked then disallow write
+ return false;
+ }
+ return version == null
+ ? txTimestamp > unlockTimestamp
+ : versionComparator.compare( version, newVersion ) < 0;
+ }
- /**
- * {@inheritDoc}
- */
- public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) {
- if ( txTimestamp > timeout ) {
- // if timedout then allow write
- return true;
- }
- if ( multiplicity > 0 ) {
- // if still locked then disallow write
- return false;
- }
- return version == null ? txTimestamp > unlockTimestamp : versionComparator.compare(
- version,
- newVersion
- ) < 0;
- }
+ @Override
+ public Object getValue() {
+ return null;
+ }
- /**
- * {@inheritDoc}
- */
- public Object getValue() {
- return null;
- }
+ @Override
+ public boolean isUnlockable(SoftLock lock) {
+ return equals( lock );
+ }
- /**
- * {@inheritDoc}
- */
- public boolean isUnlockable(SoftLock lock) {
- return equals( lock );
- }
+ @Override
+ @SuppressWarnings("SimplifiableIfStatement")
+ public boolean equals(Object o) {
+ if ( o == this ) {
+ return true;
+ }
+ else if ( o instanceof Lock ) {
+ return (lockId == ((Lock) o).lockId) && sourceUuid.equals( ((Lock) o).sourceUuid );
+ }
+ else {
+ return false;
+ }
+ }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean equals(Object o) {
- if ( o == this ) {
- return true;
- }
- else if ( o instanceof Lock ) {
- return ( lockId == ( (Lock) o ).lockId ) && sourceUuid.equals( ( (Lock) o ).sourceUuid );
- }
- else {
- return false;
- }
- }
+ @Override
+ public int hashCode() {
+ final int hash = (sourceUuid != null ? sourceUuid.hashCode() : 0);
+ int temp = (int) lockId;
+ for ( int i = 1; i < Long.SIZE / Integer.SIZE; i++ ) {
+ temp ^= (lockId >>> (i * Integer.SIZE));
+ }
+ return hash + temp;
+ }
- /**
- * {@inheritDoc}
- */
- @Override
- public int hashCode() {
- int hash = ( sourceUuid != null ? sourceUuid.hashCode() : 0 );
- int temp = (int) lockId;
- for ( int i = 1; i < Long.SIZE / Integer.SIZE; i++ ) {
- temp ^= ( lockId >>> ( i * Integer.SIZE ) );
- }
- return hash + temp;
- }
+ /**
+ * Returns true if this Lock has been concurrently locked by more than one transaction.
+ */
+ public boolean wasLockedConcurrently() {
+ return concurrent;
+ }
- /**
- * Returns true if this Lock has been concurrently locked by more than one transaction.
- */
- public boolean wasLockedConcurrently() {
- return concurrent;
- }
+ @Override
+ public Lock lock(long timeout, UUID uuid, long lockId) {
+ concurrent = true;
+ multiplicity++;
+ this.timeout = timeout;
+ return this;
+ }
- /**
- * {@inheritDoc}
- */
- public Lock lock(long timeout, UUID uuid, long lockId) {
- concurrent = true;
- multiplicity++;
- this.timeout = timeout;
- return this;
- }
+ /**
+ * Unlocks this Lock, and timestamps the unlock event.
+ */
+ public void unlock(long timestamp) {
+ if ( --multiplicity == 0 ) {
+ unlockTimestamp = timestamp;
+ }
+ }
- /**
- * Unlocks this Lock, and timestamps the unlock event.
- */
- public void unlock(long timestamp) {
- if ( --multiplicity == 0 ) {
- unlockTimestamp = timestamp;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder( "Lock Source-UUID:" + sourceUuid + " Lock-ID:" + lockId );
- return sb.toString();
- }
- }
+ @Override
+ public String toString() {
+ return "Lock Source-UUID:" + sourceUuid + " Lock-ID:" + lockId;
+ }
+ }
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactory.java
index 6265cdae58..c97ff57593 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactory.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactory.java
@@ -32,42 +32,46 @@ import org.hibernate.cache.spi.access.EntityRegionAccessStrategy;
import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy;
/**
- * Factory to create {@link EntityRegionAccessStrategy}
+ * Factory to create {@link org.hibernate.cache.spi.access.RegionAccessStrategy} instance
*
* @author Abhishek Sanoujam
* @author Alex Snaps
*/
public interface EhcacheAccessStrategyFactory {
-
/**
* Create {@link EntityRegionAccessStrategy} for the input {@link EhcacheEntityRegion} and {@link AccessType}
*
- * @param entityRegion
- * @param accessType
+ * @param entityRegion The entity region being wrapped
+ * @param accessType The type of access to allow to the region
*
* @return the created {@link EntityRegionAccessStrategy}
*/
- public EntityRegionAccessStrategy createEntityRegionAccessStrategy(EhcacheEntityRegion entityRegion, AccessType accessType);
+ public EntityRegionAccessStrategy createEntityRegionAccessStrategy(
+ EhcacheEntityRegion entityRegion,
+ AccessType accessType);
/**
- * Create {@link CollectionRegionAccessStrategy} for the input {@link org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion} and {@link AccessType}
+ * Create {@link CollectionRegionAccessStrategy} for the input {@link EhcacheCollectionRegion} and {@link AccessType}
*
- * @param collectionRegion
- * @param accessType
+ * @param collectionRegion The collection region being wrapped
+ * @param accessType The type of access to allow to the region
*
* @return the created {@link CollectionRegionAccessStrategy}
*/
- public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(EhcacheCollectionRegion collectionRegion,
- AccessType accessType);
- /**
- * Create {@link NaturalIdRegionAccessStrategy} for the input {@link org.hibernate.cache.ehcache.internal.regions.EhcacheNaturalIdRegion} and {@link AccessType}
- *
- * @param naturalIdRegion
- * @param accessType
- *
- * @return the created {@link NaturalIdRegionAccessStrategy}
- */
- public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion naturalIdRegion,
- AccessType accessType);
+ public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(
+ EhcacheCollectionRegion collectionRegion,
+ AccessType accessType);
+
+ /**
+ * Create {@link NaturalIdRegionAccessStrategy} for the input {@link EhcacheNaturalIdRegion} and {@link AccessType}
+ *
+ * @param naturalIdRegion The natural-id region being wrapped
+ * @param accessType The type of access to allow to the region
+ *
+ * @return the created {@link NaturalIdRegionAccessStrategy}
+ */
+ public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(
+ EhcacheNaturalIdRegion naturalIdRegion,
+ AccessType accessType);
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactoryImpl.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactoryImpl.java
index 94cc5dc042..7062d5652c 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactoryImpl.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactoryImpl.java
@@ -42,108 +42,108 @@ import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy;
*/
public class EhcacheAccessStrategyFactoryImpl implements EhcacheAccessStrategyFactory {
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- EhcacheAccessStrategyFactoryImpl.class.getName()
- );
-
- /**
- * {@inheritDoc}
- */
- public EntityRegionAccessStrategy createEntityRegionAccessStrategy(EhcacheEntityRegion entityRegion, AccessType accessType) {
- switch ( accessType ) {
- case READ_ONLY:
- if ( entityRegion.getCacheDataDescription().isMutable() ) {
- LOG.readOnlyCacheConfiguredForMutableEntity( entityRegion.getName() );
- }
- return new ReadOnlyEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() );
- case READ_WRITE:
- return new ReadWriteEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() );
-
- case NONSTRICT_READ_WRITE:
- return new NonStrictReadWriteEhcacheEntityRegionAccessStrategy(
- entityRegion,
- entityRegion.getSettings()
- );
-
- case TRANSACTIONAL:
- return new TransactionalEhcacheEntityRegionAccessStrategy(
- entityRegion,
- entityRegion.getEhcache(),
- entityRegion.getSettings()
- );
- default:
- throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
-
- }
-
- }
-
- /**
- * {@inheritDoc}
- */
- public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(EhcacheCollectionRegion collectionRegion,
- AccessType accessType) {
- switch ( accessType ) {
- case READ_ONLY:
- if ( collectionRegion.getCacheDataDescription().isMutable() ) {
- LOG.readOnlyCacheConfiguredForMutableEntity( collectionRegion.getName() );
- }
- return new ReadOnlyEhcacheCollectionRegionAccessStrategy(
- collectionRegion,
- collectionRegion.getSettings()
- );
- case READ_WRITE:
- return new ReadWriteEhcacheCollectionRegionAccessStrategy(
- collectionRegion,
- collectionRegion.getSettings()
- );
- case NONSTRICT_READ_WRITE:
- return new NonStrictReadWriteEhcacheCollectionRegionAccessStrategy(
- collectionRegion,
- collectionRegion.getSettings()
- );
- case TRANSACTIONAL:
- return new TransactionalEhcacheCollectionRegionAccessStrategy(
- collectionRegion, collectionRegion.getEhcache(), collectionRegion
- .getSettings()
- );
- default:
- throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
- }
- }
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ EhcacheAccessStrategyFactoryImpl.class.getName()
+ );
@Override
- public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion naturalIdRegion,
+ public EntityRegionAccessStrategy createEntityRegionAccessStrategy(
+ EhcacheEntityRegion entityRegion,
AccessType accessType) {
- switch ( accessType ) {
- case READ_ONLY:
- if ( naturalIdRegion.getCacheDataDescription().isMutable() ) {
- LOG.readOnlyCacheConfiguredForMutableEntity( naturalIdRegion.getName() );
- }
- return new ReadOnlyEhcacheNaturalIdRegionAccessStrategy(
- naturalIdRegion,
- naturalIdRegion.getSettings()
- );
- case READ_WRITE:
- return new ReadWriteEhcacheNaturalIdRegionAccessStrategy(
- naturalIdRegion,
- naturalIdRegion.getSettings()
- );
- case NONSTRICT_READ_WRITE:
- return new NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy(
- naturalIdRegion,
- naturalIdRegion.getSettings()
- );
- case TRANSACTIONAL:
- return new TransactionalEhcacheNaturalIdRegionAccessStrategy(
- naturalIdRegion, naturalIdRegion.getEhcache(), naturalIdRegion
- .getSettings()
- );
- default:
- throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
- }
+ switch ( accessType ) {
+ case READ_ONLY:
+ if ( entityRegion.getCacheDataDescription().isMutable() ) {
+ LOG.readOnlyCacheConfiguredForMutableEntity( entityRegion.getName() );
+ }
+ return new ReadOnlyEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() );
+ case READ_WRITE:
+ return new ReadWriteEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() );
+
+ case NONSTRICT_READ_WRITE:
+ return new NonStrictReadWriteEhcacheEntityRegionAccessStrategy(
+ entityRegion,
+ entityRegion.getSettings()
+ );
+
+ case TRANSACTIONAL:
+ return new TransactionalEhcacheEntityRegionAccessStrategy(
+ entityRegion,
+ entityRegion.getEhcache(),
+ entityRegion.getSettings()
+ );
+ default:
+ throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
+
+ }
+
}
-
+ @Override
+ public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(
+ EhcacheCollectionRegion collectionRegion,
+ AccessType accessType) {
+ switch ( accessType ) {
+ case READ_ONLY:
+ if ( collectionRegion.getCacheDataDescription().isMutable() ) {
+ LOG.readOnlyCacheConfiguredForMutableEntity( collectionRegion.getName() );
+ }
+ return new ReadOnlyEhcacheCollectionRegionAccessStrategy(
+ collectionRegion,
+ collectionRegion.getSettings()
+ );
+ case READ_WRITE:
+ return new ReadWriteEhcacheCollectionRegionAccessStrategy(
+ collectionRegion,
+ collectionRegion.getSettings()
+ );
+ case NONSTRICT_READ_WRITE:
+ return new NonStrictReadWriteEhcacheCollectionRegionAccessStrategy(
+ collectionRegion,
+ collectionRegion.getSettings()
+ );
+ case TRANSACTIONAL:
+ return new TransactionalEhcacheCollectionRegionAccessStrategy(
+ collectionRegion, collectionRegion.getEhcache(), collectionRegion
+ .getSettings()
+ );
+ default:
+ throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
+ }
+ }
+
+ @Override
+ public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(
+ EhcacheNaturalIdRegion naturalIdRegion,
+ AccessType accessType) {
+ switch ( accessType ) {
+ case READ_ONLY:
+ if ( naturalIdRegion.getCacheDataDescription().isMutable() ) {
+ LOG.readOnlyCacheConfiguredForMutableEntity( naturalIdRegion.getName() );
+ }
+ return new ReadOnlyEhcacheNaturalIdRegionAccessStrategy(
+ naturalIdRegion,
+ naturalIdRegion.getSettings()
+ );
+ case READ_WRITE:
+ return new ReadWriteEhcacheNaturalIdRegionAccessStrategy(
+ naturalIdRegion,
+ naturalIdRegion.getSettings()
+ );
+ case NONSTRICT_READ_WRITE:
+ return new NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy(
+ naturalIdRegion,
+ naturalIdRegion.getSettings()
+ );
+ case TRANSACTIONAL:
+ return new TransactionalEhcacheNaturalIdRegionAccessStrategy(
+ naturalIdRegion, naturalIdRegion.getEhcache(), naturalIdRegion
+ .getSettings()
+ );
+ default:
+ throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" );
+ }
+ }
+
+
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheCollectionRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheCollectionRegionAccessStrategy.java
index bada4b02bb..959d4e48cb 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheCollectionRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheCollectionRegionAccessStrategy.java
@@ -42,58 +42,58 @@ public class NonStrictReadWriteEhcacheCollectionRegionAccessStrategy
/**
* Create a non-strict read/write access strategy accessing the given collection region.
+ *
+ * @param region The wrapped region
+ * @param settings The Hibernate settings
*/
public NonStrictReadWriteEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Settings settings) {
super( region, settings );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public CollectionRegion getRegion() {
- return region;
+ return region();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
- return region.get( key );
+ return region().get( key );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
- if ( minimalPutOverride && region.contains( key ) ) {
+ if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
- region.put( key, value );
+ region().put( key, value );
return true;
}
}
/**
+ * {@inheritDoc}
+ *
* Since this is a non-strict read/write strategy item locking is not used.
*/
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
/**
+ * {@inheritDoc}
+ *
* Since this is a non-strict read/write strategy item locking is not used.
*/
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
- region.remove( key );
+ region().remove( key );
}
- /**
- * {@inheritDoc}
- */
@Override
public void remove(Object key) throws CacheException {
- region.remove( key );
+ region().remove( key );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheEntityRegionAccessStrategy.java
index c953ffc71d..9340d2b171 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheEntityRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheEntityRegionAccessStrategy.java
@@ -42,90 +42,97 @@ public class NonStrictReadWriteEhcacheEntityRegionAccessStrategy
/**
* Create a non-strict read/write access strategy accessing the given collection region.
+ *
+ * @param region The wrapped region
+ * @param settings The Hibernate settings
*/
public NonStrictReadWriteEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Settings settings) {
super( region, settings );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public EntityRegion getRegion() {
- return region;
+ return super.region();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
- return region.get( key );
+ return region().get( key );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
- if ( minimalPutOverride && region.contains( key ) ) {
+ if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
- region.put( key, value );
+ region().put( key, value );
return true;
}
}
/**
+ * {@inheritDoc}
+ *
* Since this is a non-strict read/write strategy item locking is not used.
*/
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
/**
+ * {@inheritDoc}
+ *
* Since this is a non-strict read/write strategy item locking is not used.
*/
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
- region.remove( key );
+ region().remove( key );
}
/**
+ * {@inheritDoc}
+ *
* Returns false
since this is an asynchronous cache access strategy.
*/
+ @Override
public boolean insert(Object key, Object value, Object version) throws CacheException {
return false;
}
/**
+ * {@inheritDoc}
+ *
* Returns false
since this is a non-strict read/write cache access strategy
*/
+ @Override
public boolean afterInsert(Object key, Object value, Object version) throws CacheException {
return false;
}
/**
+ * {@inheritDoc}
+ *
* Removes the entry since this is a non-strict read/write cache strategy.
*/
+ @Override
public boolean update(Object key, Object value, Object currentVersion, Object previousVersion)
throws CacheException {
remove( key );
return false;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock)
throws CacheException {
unlockItem( key, lock );
return false;
}
- /**
- * {@inheritDoc}
- */
@Override
public void remove(Object key) throws CacheException {
- region.remove( key );
+ region().remove( key );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy.java
index 6f6f8f26fb..1a633ae785 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy.java
@@ -42,88 +42,95 @@ public class NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy
/**
* Create a non-strict read/write access strategy accessing the given NaturalId region.
+ *
+ * @param region The wrapped region
+ * @param settings The Hibernate settings
*/
public NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Settings settings) {
super( region, settings );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public NaturalIdRegion getRegion() {
- return region;
+ return region();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
- return region.get( key );
+ return region().get( key );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
- if ( minimalPutOverride && region.contains( key ) ) {
+ if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
- region.put( key, value );
+ region().put( key, value );
return true;
}
}
/**
+ * {@inheritDoc}
+ *
* Since this is a non-strict read/write strategy item locking is not used.
*/
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
/**
+ * {@inheritDoc}
+ *
* Since this is a non-strict read/write strategy item locking is not used.
*/
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
- region.remove( key );
+ region().remove( key );
}
/**
+ * {@inheritDoc}
+ *
* Returns false
since this is an asynchronous cache access strategy.
*/
- public boolean insert(Object key, Object value ) throws CacheException {
- return false;
- }
-
- /**
- * Returns false
since this is a non-strict read/write cache access strategy
- */
- public boolean afterInsert(Object key, Object value ) throws CacheException {
- return false;
- }
-
- /**
- * Removes the entry since this is a non-strict read/write cache strategy.
- */
- public boolean update(Object key, Object value ) throws CacheException {
- remove( key );
+ @Override
+ public boolean insert(Object key, Object value) throws CacheException {
return false;
}
/**
* {@inheritDoc}
+ *
+ * Returns false
since this is a non-strict read/write cache access strategy
*/
+ @Override
+ public boolean afterInsert(Object key, Object value) throws CacheException {
+ return false;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * Removes the entry since this is a non-strict read/write cache strategy.
+ */
+ @Override
+ public boolean update(Object key, Object value) throws CacheException {
+ remove( key );
+ return false;
+ }
+
+ @Override
public boolean afterUpdate(Object key, Object value, SoftLock lock) throws CacheException {
unlockItem( key, lock );
return false;
}
- /**
- * {@inheritDoc}
- */
@Override
public void remove(Object key) throws CacheException {
- region.remove( key );
+ region().remove( key );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheCollectionRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheCollectionRegionAccessStrategy.java
index 449f1b40c7..7469f0e11a 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheCollectionRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheCollectionRegionAccessStrategy.java
@@ -42,46 +42,47 @@ public class ReadOnlyEhcacheCollectionRegionAccessStrategy
/**
* Create a read-only access strategy accessing the given collection region.
+ *
+ * @param region The wrapped region
+ * @param settings The Hibernate settings
*/
public ReadOnlyEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Settings settings) {
super( region, settings );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public CollectionRegion getRegion() {
- return region;
+ return region();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
- return region.get( key );
+ return region().get( key );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
- if ( minimalPutOverride && region.contains( key ) ) {
+ if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
- region.put( key, value );
+ region().put( key, value );
return true;
}
}
+ @Override
public SoftLock lockItem(Object key, Object version) throws UnsupportedOperationException {
return null;
}
/**
+ * {@inheritDoc}
+ *
* A no-op since this cache is read-only
*/
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java
index acd8fc2c5f..6631922159 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java
@@ -30,10 +30,6 @@ import org.hibernate.cache.spi.access.EntityRegionAccessStrategy;
import org.hibernate.cache.spi.access.SoftLock;
import org.hibernate.cfg.Settings;
-/**
- * @author Alex Snaps
- */
-
/**
* Ehcache specific read-only entity region access strategy
*
@@ -45,6 +41,9 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc
/**
* Create a read-only access strategy accessing the given entity region.
+ *
+ * @param region The wrapped region
+ * @param settings The Hibernate settings
*/
public ReadOnlyEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Settings settings) {
super( region, settings );
@@ -54,14 +53,14 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc
* {@inheritDoc}
*/
public EntityRegion getRegion() {
- return region;
+ return region();
}
/**
* {@inheritDoc}
*/
public Object get(Object key, long txTimestamp) throws CacheException {
- return region.get( key );
+ return region().get( key );
}
/**
@@ -69,11 +68,11 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc
*/
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
- if ( minimalPutOverride && region.contains( key ) ) {
+ if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
- region.put( key, value );
+ region().put( key, value );
return true;
}
}
@@ -100,7 +99,7 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc
* {@inheritDoc}
*/
public boolean afterInsert(Object key, Object value, Object version) throws CacheException {
- region.put( key, value );
+ region().put( key, value );
return true;
}
@@ -123,4 +122,4 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc
throws UnsupportedOperationException {
throw new UnsupportedOperationException( "Can't write to a readonly object" );
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheNaturalIdRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheNaturalIdRegionAccessStrategy.java
index 78d8839266..1e9488507e 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheNaturalIdRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheNaturalIdRegionAccessStrategy.java
@@ -42,79 +42,87 @@ public class ReadOnlyEhcacheNaturalIdRegionAccessStrategy
/**
* Create a read-only access strategy accessing the given NaturalId region.
+ *
+ * @param region THe wrapped region
+ * @param settings The Hibermate settings
*/
public ReadOnlyEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Settings settings) {
super( region, settings );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public NaturalIdRegion getRegion() {
- return region;
+ return region();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
- return region.get( key );
+ return region().get( key );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
- if ( minimalPutOverride && region.contains( key ) ) {
+ if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
- region.put( key, value );
+ region().put( key, value );
return true;
}
}
+ @Override
public SoftLock lockItem(Object key, Object version) throws UnsupportedOperationException {
return null;
}
/**
+ * {@inheritDoc}
+ *
* A no-op since this cache is read-only
*/
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
- region.remove( key );
- }
-
- /**
- * This cache is asynchronous hence a no-op
- */
- public boolean insert(Object key, Object value ) throws CacheException {
- return false;
+ region().remove( key );
}
/**
* {@inheritDoc}
+ *
+ * This cache is asynchronous hence a no-op
*/
- public boolean afterInsert(Object key, Object value ) throws CacheException {
- region.put( key, value );
+ @Override
+ public boolean insert(Object key, Object value) throws CacheException {
+ return false;
+ }
+
+ @Override
+ public boolean afterInsert(Object key, Object value) throws CacheException {
+ region().put( key, value );
return true;
}
/**
+ * {@inheritDoc}
+ *
* Throws UnsupportedOperationException since this cache is read-only
*
* @throws UnsupportedOperationException always
*/
- public boolean update(Object key, Object value ) throws UnsupportedOperationException {
+ @Override
+ public boolean update(Object key, Object value) throws UnsupportedOperationException {
throw new UnsupportedOperationException( "Can't write to a readonly object" );
}
/**
+ * {@inheritDoc}
+ *
* Throws UnsupportedOperationException since this cache is read-only
*
* @throws UnsupportedOperationException always
*/
+ @Override
public boolean afterUpdate(Object key, Object value, SoftLock lock) throws UnsupportedOperationException {
throw new UnsupportedOperationException( "Can't write to a readonly object" );
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheCollectionRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheCollectionRegionAccessStrategy.java
index f43e666afa..36efcd2df9 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheCollectionRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheCollectionRegionAccessStrategy.java
@@ -40,15 +40,16 @@ public class ReadWriteEhcacheCollectionRegionAccessStrategy
/**
* Create a read/write access strategy accessing the given collection region.
+ *
+ * @param region The wrapped region
+ * @param settings The Hibernate settings
*/
public ReadWriteEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Settings settings) {
super( region, settings );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public CollectionRegion getRegion() {
- return region;
+ return region();
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java
index 31ecd277e8..1cf14387f0 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java
@@ -42,21 +42,25 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
/**
* Create a read/write access strategy accessing the given entity region.
+ *
+ * @param region The wrapped region
+ * @param settings The Hibernate settings
*/
public ReadWriteEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Settings settings) {
super( region, settings );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public EntityRegion getRegion() {
- return region;
+ return region();
}
/**
+ * {@inheritDoc}
+ *
* A no-op since this is an asynchronous cache access strategy.
*/
+ @Override
public boolean insert(Object key, Object value, Object version) throws CacheException {
return false;
}
@@ -66,12 +70,13 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
*
* Inserts will only succeed if there is no existing value mapped to this key.
*/
+ @Override
public boolean afterInsert(Object key, Object value, Object version) throws CacheException {
- region.writeLock( key );
+ region().writeLock( key );
try {
- Lockable item = (Lockable) region.get( key );
+ final Lockable item = (Lockable) region().get( key );
if ( item == null ) {
- region.put( key, new Item( value, version, region.nextTimestamp() ) );
+ region().put( key, new Item( value, version, region().nextTimestamp() ) );
return true;
}
else {
@@ -79,13 +84,16 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
}
}
finally {
- region.writeUnlock( key );
+ region().writeUnlock( key );
}
}
/**
+ * {@inheritDoc}
+ *
* A no-op since this is an asynchronous cache access strategy.
*/
+ @Override
public boolean update(Object key, Object value, Object currentVersion, Object previousVersion)
throws CacheException {
return false;
@@ -98,12 +106,13 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
* duration of this transaction. It is important to also note that updates will fail if the soft-lock expired during
* the course of this transaction.
*/
+ @Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock)
throws CacheException {
//what should we do with previousVersion here?
- region.writeLock( key );
+ region().writeLock( key );
try {
- Lockable item = (Lockable) region.get( key );
+ final Lockable item = (Lockable) region().get( key );
if ( item != null && item.isUnlockable( lock ) ) {
Lock lockItem = (Lock) item;
@@ -112,7 +121,7 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
return false;
}
else {
- region.put( key, new Item( value, currentVersion, region.nextTimestamp() ) );
+ region().put( key, new Item( value, currentVersion, region().nextTimestamp() ) );
return true;
}
}
@@ -122,7 +131,7 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
}
}
finally {
- region.writeUnlock( key );
+ region().writeUnlock( key );
}
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheNaturalIdRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheNaturalIdRegionAccessStrategy.java
index 6d287f0bf7..ef40d5dd82 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheNaturalIdRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheNaturalIdRegionAccessStrategy.java
@@ -42,22 +42,26 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
/**
* Create a read/write access strategy accessing the given NaturalId region.
+ *
+ * @param region The wrapped region
+ * @param settings The Hibernate settings
*/
public ReadWriteEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Settings settings) {
super( region, settings );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public NaturalIdRegion getRegion() {
- return region;
+ return region();
}
/**
+ * {@inheritDoc}
+ *
* A no-op since this is an asynchronous cache access strategy.
*/
- public boolean insert(Object key, Object value ) throws CacheException {
+ @Override
+ public boolean insert(Object key, Object value) throws CacheException {
return false;
}
@@ -66,12 +70,13 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
*
* Inserts will only succeed if there is no existing value mapped to this key.
*/
- public boolean afterInsert(Object key, Object value ) throws CacheException {
- region.writeLock( key );
+ @Override
+ public boolean afterInsert(Object key, Object value) throws CacheException {
+ region().writeLock( key );
try {
- Lockable item = (Lockable) region.get( key );
+ final Lockable item = (Lockable) region().get( key );
if ( item == null ) {
- region.put( key, new Item( value, null, region.nextTimestamp() ) );
+ region().put( key, new Item( value, null, region().nextTimestamp() ) );
return true;
}
else {
@@ -79,15 +84,17 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
}
}
finally {
- region.writeUnlock( key );
+ region().writeUnlock( key );
}
}
/**
+ * {@inheritDoc}
+ *
* A no-op since this is an asynchronous cache access strategy.
*/
- public boolean update(Object key, Object value )
- throws CacheException {
+ @Override
+ public boolean update(Object key, Object value) throws CacheException {
return false;
}
@@ -98,20 +105,21 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
* duration of this transaction. It is important to also note that updates will fail if the soft-lock expired during
* the course of this transaction.
*/
+ @Override
public boolean afterUpdate(Object key, Object value, SoftLock lock) throws CacheException {
//what should we do with previousVersion here?
- region.writeLock( key );
+ region().writeLock( key );
try {
- Lockable item = (Lockable) region.get( key );
+ final Lockable item = (Lockable) region().get( key );
if ( item != null && item.isUnlockable( lock ) ) {
- Lock lockItem = (Lock) item;
+ final Lock lockItem = (Lock) item;
if ( lockItem.wasLockedConcurrently() ) {
decrementLock( key, lockItem );
return false;
}
else {
- region.put( key, new Item( value, null, region.nextTimestamp() ) );
+ region().put( key, new Item( value, null, region().nextTimestamp() ) );
return true;
}
}
@@ -121,7 +129,7 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
}
}
finally {
- region.writeUnlock( key );
+ region().writeUnlock( key );
}
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheCollectionRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheCollectionRegionAccessStrategy.java
index e6e120ce97..5b76fbd653 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheCollectionRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheCollectionRegionAccessStrategy.java
@@ -53,44 +53,42 @@ public class TransactionalEhcacheCollectionRegionAccessStrategy
* @param ehcache the cache.
* @param settings the Hibernate settings.
*/
- public TransactionalEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Ehcache ehcache, Settings settings) {
+ public TransactionalEhcacheCollectionRegionAccessStrategy(
+ EhcacheCollectionRegion region,
+ Ehcache ehcache,
+ Settings settings) {
super( region, settings );
this.ehcache = ehcache;
}
-
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
- Element element = ehcache.get( key );
+ final Element element = ehcache.get( key );
return element == null ? null : element.getObjectValue();
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public CollectionRegion getRegion() {
- return region;
+ return region();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
- /**
- * {@inheritDoc}
- */
- public boolean putFromLoad(Object key, Object value, long txTimestamp,
- Object version, boolean minimalPutOverride) throws CacheException {
+ @Override
+ public boolean putFromLoad(
+ Object key,
+ Object value,
+ long txTimestamp,
+ Object version,
+ boolean minimalPutOverride) throws CacheException {
try {
if ( minimalPutOverride && ehcache.get( key ) != null ) {
return false;
@@ -99,27 +97,22 @@ public class TransactionalEhcacheCollectionRegionAccessStrategy
ehcache.put( new Element( key, value ) );
return true;
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
@Override
public void remove(Object key) throws CacheException {
try {
ehcache.remove( key );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
// no-op
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheEntityRegionAccessStrategy.java
index b5ac353cfe..1e0bb318dd 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheEntityRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheEntityRegionAccessStrategy.java
@@ -52,48 +52,41 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca
* @param ehcache the cache.
* @param settings the Hibernate settings.
*/
- public TransactionalEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Ehcache ehcache, Settings settings) {
+ public TransactionalEhcacheEntityRegionAccessStrategy(
+ EhcacheEntityRegion region,
+ Ehcache ehcache,
+ Settings settings) {
super( region, settings );
this.ehcache = ehcache;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean afterInsert(Object key, Object value, Object version) {
return false;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) {
return false;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
- Element element = ehcache.get( key );
+ final Element element = ehcache.get( key );
return element == null ? null : element.getObjectValue();
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public EntityRegion getRegion() {
- return region;
+ return region();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean insert(Object key, Object value, Object version)
throws CacheException {
//OptimisticCache? versioning?
@@ -101,23 +94,23 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca
ehcache.put( new Element( key, value ) );
return true;
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
- /**
- * {@inheritDoc}
- */
- public boolean putFromLoad(Object key, Object value, long txTimestamp,
- Object version, boolean minimalPutOverride) throws CacheException {
+ @Override
+ public boolean putFromLoad(
+ Object key,
+ Object value,
+ long txTimestamp,
+ Object version,
+ boolean minimalPutOverride) throws CacheException {
try {
if ( minimalPutOverride && ehcache.get( key ) != null ) {
return false;
@@ -126,41 +119,37 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca
ehcache.put( new Element( key, value ) );
return true;
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
@Override
public void remove(Object key) throws CacheException {
try {
ehcache.remove( key );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
// no-op
}
- /**
- * {@inheritDoc}
- */
- public boolean update(Object key, Object value, Object currentVersion,
- Object previousVersion) throws CacheException {
+ @Override
+ public boolean update(
+ Object key,
+ Object value,
+ Object currentVersion,
+ Object previousVersion) throws CacheException {
try {
ehcache.put( new Element( key, value ) );
return true;
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheNaturalIdRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheNaturalIdRegionAccessStrategy.java
index f87461312a..653e036e7d 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheNaturalIdRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheNaturalIdRegionAccessStrategy.java
@@ -53,72 +53,64 @@ public class TransactionalEhcacheNaturalIdRegionAccessStrategy
* @param ehcache the cache.
* @param settings the Hibernate settings.
*/
- public TransactionalEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Ehcache ehcache, Settings settings) {
+ public TransactionalEhcacheNaturalIdRegionAccessStrategy(
+ EhcacheNaturalIdRegion region,
+ Ehcache ehcache,
+ Settings settings) {
super( region, settings );
this.ehcache = ehcache;
}
- /**
- * {@inheritDoc}
- */
- public boolean afterInsert(Object key, Object value ) {
+ @Override
+ public boolean afterInsert(Object key, Object value) {
return false;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean afterUpdate(Object key, Object value, SoftLock lock) {
return false;
}
-
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
- Element element = ehcache.get( key );
+ final Element element = ehcache.get( key );
return element == null ? null : element.getObjectValue();
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public NaturalIdRegion getRegion() {
- return region;
+ return region();
}
- /**
- * {@inheritDoc}
- */
- public boolean insert(Object key, Object value ) throws CacheException {
+ @Override
+ public boolean insert(Object key, Object value) throws CacheException {
//OptimisticCache? versioning?
try {
ehcache.put( new Element( key, value ) );
return true;
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
- /**
- * {@inheritDoc}
- */
- public boolean putFromLoad(Object key, Object value, long txTimestamp,
- Object version, boolean minimalPutOverride) throws CacheException {
+ @Override
+ public boolean putFromLoad(
+ Object key,
+ Object value,
+ long txTimestamp,
+ Object version,
+ boolean minimalPutOverride) throws CacheException {
try {
if ( minimalPutOverride && ehcache.get( key ) != null ) {
return false;
@@ -127,40 +119,33 @@ public class TransactionalEhcacheNaturalIdRegionAccessStrategy
ehcache.put( new Element( key, value ) );
return true;
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
@Override
public void remove(Object key) throws CacheException {
try {
ehcache.remove( key );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
// no-op
}
- /**
- * {@inheritDoc}
- */
- public boolean update(Object key, Object value ) throws CacheException {
+ @Override
+ public boolean update(Object key, Object value) throws CacheException {
try {
ehcache.put( new Element( key, value ) );
return true;
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/package-info.java
new file mode 100644
index 0000000000..f055c0e74d
--- /dev/null
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines {@link org.hibernate.cache.spi.access.RegionAccessStrategy} support for the Ehcache integration
+ */
+package org.hibernate.cache.ehcache.internal.strategy;
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateEhcacheUtils.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateEhcacheUtils.java
new file mode 100644
index 0000000000..6167af991e
--- /dev/null
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateEhcacheUtils.java
@@ -0,0 +1,129 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2011, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.cache.ehcache.internal.util;
+
+import java.net.URL;
+
+import net.sf.ehcache.Ehcache;
+import net.sf.ehcache.config.CacheConfiguration;
+import net.sf.ehcache.config.Configuration;
+import net.sf.ehcache.config.ConfigurationFactory;
+import net.sf.ehcache.config.NonstopConfiguration;
+import net.sf.ehcache.config.TerracottaConfiguration;
+import net.sf.ehcache.config.TerracottaConfiguration.ValueMode;
+import net.sf.ehcache.config.TimeoutBehaviorConfiguration.TimeoutBehaviorType;
+
+import org.jboss.logging.Logger;
+
+import org.hibernate.cache.CacheException;
+import org.hibernate.cache.ehcache.EhCacheMessageLogger;
+
+
+/**
+ * Copy of Ehcache utils into Hibernate code base
+ *
+ * @author Chris Dennis
+ * @author Abhishek Sanoujam
+ * @author Alex Snaps
+ */
+public final class HibernateEhcacheUtils {
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ HibernateEhcacheUtils.class.getName()
+ );
+
+ private HibernateEhcacheUtils() {
+ }
+
+ /**
+ * Create a cache manager configuration from the supplied url, correcting it for Hibernate compatibility.
+ *
+ * Currently "correcting" for Hibernate compatibility means simply switching any identity based value modes
+ * to serialization.
+ *
+ * @param url The url to load the config from
+ *
+ * @return The Ehcache Configuration object
+ */
+ public static Configuration loadAndCorrectConfiguration(URL url) {
+ final Configuration config = ConfigurationFactory.parseConfiguration( url );
+ if ( config.getDefaultCacheConfiguration().isTerracottaClustered() ) {
+ if ( ValueMode.IDENTITY
+ .equals( config.getDefaultCacheConfiguration().getTerracottaConfiguration().getValueMode() ) ) {
+ LOG.incompatibleCacheValueMode();
+ config.getDefaultCacheConfiguration()
+ .getTerracottaConfiguration()
+ .setValueMode( ValueMode.SERIALIZATION.name() );
+ }
+ setupHibernateTimeoutBehavior(
+ config.getDefaultCacheConfiguration()
+ .getTerracottaConfiguration()
+ .getNonstopConfiguration()
+ );
+ }
+
+ for ( CacheConfiguration cacheConfig : config.getCacheConfigurations().values() ) {
+ if ( cacheConfig.isTerracottaClustered() ) {
+ if ( ValueMode.IDENTITY.equals( cacheConfig.getTerracottaConfiguration().getValueMode() ) ) {
+ LOG.incompatibleCacheValueModePerCache( cacheConfig.getName() );
+ cacheConfig.getTerracottaConfiguration().setValueMode( ValueMode.SERIALIZATION.name() );
+ }
+ setupHibernateTimeoutBehavior( cacheConfig.getTerracottaConfiguration().getNonstopConfiguration() );
+ }
+ }
+ return config;
+ }
+
+ private static void setupHibernateTimeoutBehavior(NonstopConfiguration nonstopConfig) {
+ nonstopConfig.getTimeoutBehavior().setType( TimeoutBehaviorType.EXCEPTION.getTypeName() );
+ }
+
+ /**
+ * Validates that the supplied Ehcache instance is valid for use as a Hibernate cache.
+ *
+ * @param cache The cache instance
+ *
+ * @throws CacheException If any explicit settings on the cache are not validate
+ */
+ public static void validateEhcache(Ehcache cache) throws CacheException {
+ final CacheConfiguration cacheConfig = cache.getCacheConfiguration();
+
+ if ( cacheConfig.isTerracottaClustered() ) {
+ final TerracottaConfiguration tcConfig = cacheConfig.getTerracottaConfiguration();
+ switch ( tcConfig.getValueMode() ) {
+ case IDENTITY: {
+ throw new CacheException(
+ "The clustered Hibernate cache " + cache.getName() + " is using IDENTITY value mode.\n"
+ + "Identity value mode cannot be used with Hibernate cache regions."
+ );
+ }
+ case SERIALIZATION:
+ default: {
+ // this is the recommended valueMode
+ break;
+ }
+ }
+ }
+ }
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateUtil.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateUtil.java
deleted file mode 100644
index 7d66b8820d..0000000000
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateUtil.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2011, Red Hat Inc. or third-party contributors as
- * indicated by the @author tags or express copyright attribution
- * statements applied by the authors. All third-party contributions are
- * distributed under license by Red Hat Inc.
- *
- * This copyrighted material is made available to anyone wishing to use, modify,
- * copy, or redistribute it subject to the terms and conditions of the GNU
- * Lesser General Public License, as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
- * for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this distribution; if not, write to:
- * Free Software Foundation, Inc.
- * 51 Franklin Street, Fifth Floor
- * Boston, MA 02110-1301 USA
- */
-package org.hibernate.cache.ehcache.internal.util;
-
-import java.net.URL;
-
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.ConfigurationFactory;
-import net.sf.ehcache.config.NonstopConfiguration;
-import net.sf.ehcache.config.TerracottaConfiguration;
-import net.sf.ehcache.config.TerracottaConfiguration.ValueMode;
-import net.sf.ehcache.config.TimeoutBehaviorConfiguration.TimeoutBehaviorType;
-import org.jboss.logging.Logger;
-
-import org.hibernate.cache.CacheException;
-import org.hibernate.cache.ehcache.EhCacheMessageLogger;
-
-
-/**
- * @author Chris Dennis
- * @author Abhishek Sanoujam
- * @author Alex Snaps
- */
-public final class HibernateUtil {
-
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- HibernateUtil.class.getName()
- );
-
- private HibernateUtil() {
- }
-
- /**
- * Create a cache manager configuration from the supplied url, correcting it for Hibernate compatibility.
- *
- * Currently correcting for Hibernate compatibility means simply switching any identity based value modes to serialization.
- */
- public static Configuration loadAndCorrectConfiguration(URL url) {
- Configuration config = ConfigurationFactory.parseConfiguration( url );
- if ( config.getDefaultCacheConfiguration().isTerracottaClustered() ) {
- if ( ValueMode.IDENTITY
- .equals( config.getDefaultCacheConfiguration().getTerracottaConfiguration().getValueMode() ) ) {
- LOG.incompatibleCacheValueMode();
- config.getDefaultCacheConfiguration()
- .getTerracottaConfiguration()
- .setValueMode( ValueMode.SERIALIZATION.name() );
- }
- setupHibernateTimeoutBehavior(
- config.getDefaultCacheConfiguration()
- .getTerracottaConfiguration()
- .getNonstopConfiguration()
- );
- }
-
- for ( CacheConfiguration cacheConfig : config.getCacheConfigurations().values() ) {
- if ( cacheConfig.isTerracottaClustered() ) {
- if ( ValueMode.IDENTITY.equals( cacheConfig.getTerracottaConfiguration().getValueMode() ) ) {
- LOG.incompatibleCacheValueModePerCache( cacheConfig.getName() );
- cacheConfig.getTerracottaConfiguration().setValueMode( ValueMode.SERIALIZATION.name() );
- }
- setupHibernateTimeoutBehavior( cacheConfig.getTerracottaConfiguration().getNonstopConfiguration() );
- }
- }
- return config;
- }
-
- private static void setupHibernateTimeoutBehavior(NonstopConfiguration nonstopConfig) {
- nonstopConfig.getTimeoutBehavior().setType( TimeoutBehaviorType.EXCEPTION.getTypeName() );
- }
-
- /**
- * Validates that the supplied Ehcache instance is valid for use as a Hibernate cache.
- */
- public static void validateEhcache(Ehcache cache) throws CacheException {
- CacheConfiguration cacheConfig = cache.getCacheConfiguration();
-
- if ( cacheConfig.isTerracottaClustered() ) {
- TerracottaConfiguration tcConfig = cacheConfig.getTerracottaConfiguration();
- switch ( tcConfig.getValueMode() ) {
- case IDENTITY:
- throw new CacheException(
- "The clustered Hibernate cache " + cache.getName() + " is using IDENTITY value mode.\n"
- + "Identity value mode cannot be used with Hibernate cache regions."
- );
- case SERIALIZATION:
- default:
- // this is the recommended valueMode
- break;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/package-info.java
new file mode 100644
index 0000000000..5c6a04407f
--- /dev/null
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines utilities used by the Ehcache integration
+ */
+package org.hibernate.cache.ehcache.internal.util;
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BaseEmitterBean.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java
similarity index 69%
rename from hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BaseEmitterBean.java
rename to hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java
index 2c6a6d27f5..5d3f3abc31 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BaseEmitterBean.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java
@@ -24,9 +24,6 @@
package org.hibernate.cache.ehcache.management.impl;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.atomic.AtomicLong;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
@@ -36,64 +33,61 @@ import javax.management.NotificationEmitter;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.StandardMBean;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicLong;
/**
+ * Base MBean impl
+ *
* @author gkeim
*/
-public abstract class BaseEmitterBean extends StandardMBean implements NotificationEmitter {
- /**
- * emitter
- */
- protected final Emitter emitter = new Emitter();
-
- /**
- * sequenceNumber
- */
- protected final AtomicLong sequenceNumber = new AtomicLong();
-
+public abstract class AbstractEmitterBean extends StandardMBean implements NotificationEmitter {
+ private final Emitter emitter = new Emitter();
+ private final AtomicLong sequenceNumber = new AtomicLong();
private final List notificationListeners = new CopyOnWriteArrayList();
/**
- * BaseEmitterBean
+ * Constructs a AbstractEmitterBean
*
- * @param
- * @param mbeanInterface
+ * @param mbeanInterface The MBean contract
+ * @param Not used as far as I can see
*
- * @throws javax.management.NotCompliantMBeanException
+ * @throws javax.management.NotCompliantMBeanException thrown from JMX super ctor
*/
- protected BaseEmitterBean(Class mbeanInterface) throws NotCompliantMBeanException {
+ protected AbstractEmitterBean(Class mbeanInterface) throws NotCompliantMBeanException {
super( mbeanInterface );
}
/**
- * sendNotification
+ * Sends notification of an event
*
- * @param eventType
+ * @param eventType The type of event
*/
public void sendNotification(String eventType) {
sendNotification( eventType, null, null );
}
/**
- * sendNotification
+ * Sends notification of an event
*
- * @param eventType
- * @param data
+ * @param eventType The type of event
+ * @param data The event data
*/
public void sendNotification(String eventType, Object data) {
sendNotification( eventType, data, null );
}
/**
- * sendNotification
+ * Sends notification of an event
*
- * @param eventType
- * @param data
- * @param msg
+ * @param eventType The type of event
+ * @param data The event data
+ * @param msg A message
*/
public void sendNotification(String eventType, Object data, String msg) {
- Notification notif = new Notification(
+ final Notification notification = new Notification(
eventType,
this,
sequenceNumber.incrementAndGet(),
@@ -101,9 +95,9 @@ public abstract class BaseEmitterBean extends StandardMBean implements Notificat
msg
);
if ( data != null ) {
- notif.setUserData( data );
+ notification.setUserData( data );
}
- emitter.sendNotification( notif );
+ emitter.sendNotification( notification );
}
/**
@@ -119,61 +113,42 @@ public abstract class BaseEmitterBean extends StandardMBean implements Notificat
*/
protected abstract void doDispose();
- /**
- * @author gkeim
- */
private class Emitter extends NotificationBroadcasterSupport {
- /**
- * @see javax.management.NotificationBroadcasterSupport#getNotificationInfo()
- */
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
- return BaseEmitterBean.this.getNotificationInfo();
+ return AbstractEmitterBean.this.getNotificationInfo();
}
}
- /**
- * @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener,
- * javax.management.NotificationFilter, java.lang.Object)
- */
+ @Override
public void addNotificationListener(NotificationListener notif, NotificationFilter filter, Object callBack) {
emitter.addNotificationListener( notif, filter, callBack );
notificationListeners.add( notif );
}
- /**
- * remove all added notification listeners
- */
private void removeAllNotificationListeners() {
for ( NotificationListener listener : notificationListeners ) {
try {
emitter.removeNotificationListener( listener );
}
- catch ( ListenerNotFoundException e ) {
+ catch (ListenerNotFoundException e) {
// ignore
}
}
notificationListeners.clear();
}
- /**
- * @see javax.management.NotificationBroadcaster#getNotificationInfo()
- */
+ @Override
public abstract MBeanNotificationInfo[] getNotificationInfo();
- /**
- * @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener)
- */
+ @Override
public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
emitter.removeNotificationListener( listener );
notificationListeners.remove( listener );
}
- /**
- * @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener,
- * javax.management.NotificationFilter, java.lang.Object)
- */
+ @Override
public void removeNotificationListener(NotificationListener notif, NotificationFilter filter, Object callBack)
throws ListenerNotFoundException {
emitter.removeNotificationListener( notif, filter, callBack );
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BeanUtils.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BeanUtils.java
index 1352c0fbfc..afcd716ae7 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BeanUtils.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BeanUtils.java
@@ -36,17 +36,17 @@ public class BeanUtils {
/**
* Return the named getter method on the bean or null if not found.
*
- * @param bean
- * @param propertyName
+ * @param bean The bean
+ * @param propertyName The property to get the getter for
*
* @return the named getter method
*/
private static Method getMethod(Object bean, String propertyName) {
- StringBuilder sb = new StringBuilder( "get" ).append( Character.toUpperCase( propertyName.charAt( 0 ) ) );
+ final StringBuilder sb = new StringBuilder( "get" ).append( Character.toUpperCase( propertyName.charAt( 0 ) ) );
if ( propertyName.length() > 1 ) {
sb.append( propertyName.substring( 1 ) );
}
- String getterName = sb.toString();
+ final String getterName = sb.toString();
for ( Method m : bean.getClass().getMethods() ) {
if ( getterName.equals( m.getName() ) && m.getParameterTypes().length == 0 ) {
return m;
@@ -55,14 +55,6 @@ public class BeanUtils {
return null;
}
- /**
- * Return the named field on the bean or null if not found.
- *
- * @param bean
- * @param propertyName
- *
- * @return the named field
- */
private static Field getField(Object bean, String propertyName) {
for ( Field f : bean.getClass().getDeclaredFields() ) {
if ( propertyName.equals( f.getName() ) ) {
@@ -87,8 +79,8 @@ public class BeanUtils {
/**
* Retrieve a named bean property value.
*
- * @param bean bean
- * @param propertyName
+ * @param bean The bean instance
+ * @param propertyName The name of the property whose value to extract
*
* @return the property value
*/
@@ -96,24 +88,24 @@ public class BeanUtils {
validateArgs( bean, propertyName );
// try getters first
- Method getter = getMethod( bean, propertyName );
+ final Method getter = getMethod( bean, propertyName );
if ( getter != null ) {
try {
return getter.invoke( bean );
}
- catch ( Exception e ) {
+ catch (Exception e) {
/**/
}
}
// then try fields
- Field field = getField( bean, propertyName );
+ final Field field = getField( bean, propertyName );
if ( field != null ) {
try {
field.setAccessible( true );
return field.get( bean );
}
- catch ( Exception e ) {
+ catch (Exception e) {
/**/
}
}
@@ -124,22 +116,25 @@ public class BeanUtils {
/**
* Retrieve a Long bean property value.
*
- * @param bean bean
- * @param propertyName
+ * @param bean The bean instance
+ * @param propertyName The name of the property whose value to extract
*
* @return long value
*
- * @throws NoSuchFieldException
+ * @throws NoSuchFieldException If the value is null (wow)
*/
public static long getLongBeanProperty(final Object bean, final String propertyName) throws NoSuchFieldException {
validateArgs( bean, propertyName );
- Object o = getBeanProperty( bean, propertyName );
+ final Object o = getBeanProperty( bean, propertyName );
if ( o == null ) {
throw new NoSuchFieldException( propertyName );
}
- else if ( !( o instanceof Number ) ) {
+ else if ( !(o instanceof Number) ) {
throw new IllegalArgumentException( propertyName + " not an Number" );
}
- return ( (Number) o ).longValue();
+ return ((Number) o).longValue();
+ }
+
+ private BeanUtils() {
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionStats.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionStats.java
index 677f217d1f..9f1264a56b 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionStats.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionStats.java
@@ -23,10 +23,6 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
@@ -36,10 +32,15 @@ import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
import org.hibernate.stat.SecondLevelCacheStatistics;
/**
+ * Bean for exposing region stats
+ *
* @author gkeim
*/
public class CacheRegionStats implements Serializable {
@@ -61,7 +62,7 @@ public class CacheRegionStats implements Serializable {
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Cache-region";
private static final String TABULAR_TYPE_DESCRIPTION = "All Cache Region Statistics";
- private static final String[] INDEX_NAMES = new String[] { "region", };
+ private static final String[] INDEX_NAMES = new String[] {"region",};
private static final TabularType TABULAR_TYPE;
static {
@@ -72,7 +73,7 @@ public class CacheRegionStats implements Serializable {
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
@@ -123,7 +124,9 @@ public class CacheRegionStats implements Serializable {
protected long elementCountTotal;
/**
- * @param region
+ * Construct a CacheRegionStats
+ *
+ * @param region The region name
*/
public CacheRegionStats(String region) {
this.region = region;
@@ -131,8 +134,10 @@ public class CacheRegionStats implements Serializable {
}
/**
- * @param region
- * @param src
+ * Construct a CacheRegionStats
+ *
+ * @param region The region name
+ * @param src The SecondLevelCacheStatistics reference
*/
public CacheRegionStats(String region, SecondLevelCacheStatistics src) {
this( region );
@@ -146,15 +151,18 @@ public class CacheRegionStats implements Serializable {
this.elementCountOnDisk = BeanUtils.getLongBeanProperty( src, "elementCountOnDisk" );
this.elementCountTotal = BeanUtils.getLongBeanProperty( src, "elementCountOnDisk" );
}
- catch ( Exception e ) {
+ catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
}
/**
- * @param cData
+ * Construct a CacheRegionStats
+ *
+ * @param cData No idea
*/
+ @SuppressWarnings("UnusedAssignment")
public CacheRegionStats(final CompositeData cData) {
int i = 0;
region = (String) cData.get( ITEM_NAMES[i++] );
@@ -168,30 +176,15 @@ public class CacheRegionStats implements Serializable {
elementCountTotal = (Long) cData.get( ITEM_NAMES[i++] );
}
- private static int safeParseInt(String s) {
- try {
- return Integer.parseInt( s );
- }
- catch ( Exception e ) {
- return -1;
- }
- }
-
- /**
- * @return hit ratio
- */
protected double determineHitRatio() {
+ final long readCount = getHitCount() + getMissCount();
double result = 0;
- long readCount = getHitCount() + getMissCount();
if ( readCount > 0 ) {
- result = getHitCount() / ( (double) readCount );
+ result = getHitCount() / ((double) readCount);
}
return result;
}
- /**
- * @see java.lang.Object#toString()
- */
@Override
public String toString() {
return "region=" + getRegion() + "shortName=" + getShortName() + ", hitCount=" + getHitCount() + ", missCount="
@@ -200,70 +193,45 @@ public class CacheRegionStats implements Serializable {
+ getElementCountTotal();
}
- /**
- * @return region name
- */
public String getRegion() {
return region;
}
- /**
- * @return short name
- */
public String getShortName() {
return shortName;
}
- /**
- * @return hit count
- */
public long getHitCount() {
return hitCount;
}
- /**
- * @return miss count
- */
public long getMissCount() {
return missCount;
}
- /**
- * @return put count
- */
public long getPutCount() {
return putCount;
}
- /**
- * @return hit ratio
- */
public double getHitRatio() {
return hitRatio;
}
- /**
- * @return in-memory element count
- */
public long getElementCountInMemory() {
return elementCountInMemory;
}
- /**
- * @return on-disk element count
- */
public long getElementCountOnDisk() {
return elementCountOnDisk;
}
- /**
- * @return total element count
- */
public long getElementCountTotal() {
return elementCountTotal;
}
/**
+ * Convert our state into a JMX CompositeData
+ *
* @return composite data
*/
public CompositeData toCompositeData() {
@@ -276,12 +244,14 @@ public class CacheRegionStats implements Serializable {
}
);
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
/**
+ * Convert our state into a JMX TabularData
+ *
* @return tabular data
*/
public static TabularData newTabularDataInstance() {
@@ -289,14 +259,17 @@ public class CacheRegionStats implements Serializable {
}
/**
- * @param tabularData
+ * Re-build the CacheRegionStats from JMX tabular data
+ *
+ * @param tabularData The JMX tabular data
*
* @return array of region statistics
*/
+ @SuppressWarnings("UnusedDeclaration")
public static CacheRegionStats[] fromTabularData(final TabularData tabularData) {
- final List countList = new ArrayList( tabularData.size() );
- for ( final Iterator pos = tabularData.values().iterator(); pos.hasNext(); ) {
- countList.add( new CacheRegionStats( (CompositeData) pos.next() ) );
+ final List countList = new ArrayList( tabularData.size() );
+ for ( Object o : tabularData.values() ) {
+ countList.add( new CacheRegionStats( (CompositeData) o ) );
}
return countList.toArray( new CacheRegionStats[countList.size()] );
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionUtils.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionUtils.java
index 023876fa68..267486a6a2 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionUtils.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionUtils.java
@@ -23,13 +23,14 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.awt.*;
+import java.awt.Color;
/**
* CacheRegionUtils
*
* @author gkeim
*/
+@SuppressWarnings("UnusedDeclaration")
public abstract class CacheRegionUtils {
/**
* HIT_COLOR
@@ -49,51 +50,53 @@ public abstract class CacheRegionUtils {
/**
* HIT_FILL_COLOR
*/
- public final static Color HIT_FILL_COLOR = CacheRegionUtils.HIT_COLOR.brighter().brighter().brighter();
+ public static final Color HIT_FILL_COLOR = CacheRegionUtils.HIT_COLOR.brighter().brighter().brighter();
/**
* MISS_FILL_COLOR
*/
- public final static Color MISS_FILL_COLOR = CacheRegionUtils.MISS_COLOR.brighter().brighter().brighter();
+ public static final Color MISS_FILL_COLOR = CacheRegionUtils.MISS_COLOR.brighter().brighter().brighter();
/**
* PUT_FILL_COLOR
*/
- public final static Color PUT_FILL_COLOR = CacheRegionUtils.PUT_COLOR.brighter().brighter().brighter();
+ public static final Color PUT_FILL_COLOR = CacheRegionUtils.PUT_COLOR.brighter().brighter().brighter();
/**
* HIT_DRAW_COLOR
*/
- public final static Color HIT_DRAW_COLOR = CacheRegionUtils.HIT_COLOR.darker();
+ public static final Color HIT_DRAW_COLOR = CacheRegionUtils.HIT_COLOR.darker();
/**
* MISS_DRAW_COLOR
*/
- public final static Color MISS_DRAW_COLOR = CacheRegionUtils.MISS_COLOR.darker();
+ public static final Color MISS_DRAW_COLOR = CacheRegionUtils.MISS_COLOR.darker();
/**
* PUT_DRAW_COLOR
*/
- public final static Color PUT_DRAW_COLOR = CacheRegionUtils.PUT_COLOR.darker();
+ public static final Color PUT_DRAW_COLOR = CacheRegionUtils.PUT_COLOR.darker();
/**
- * determineShortName
+ * Determine a short name from the full name
*
- * @param fullName
+ * @param fullName The full name
+ *
+ * @return The short name
*/
public static String determineShortName(String fullName) {
String result = fullName;
if ( fullName != null ) {
- String[] comps = fullName.split( "\\." );
+ final String[] comps = fullName.split( "\\." );
if ( comps.length == 1 ) {
return fullName;
}
boolean truncate = true;
for ( int i = 0; i < comps.length; i++ ) {
String comp = comps[i];
- char c = comp.charAt( 0 );
+ final char c = comp.charAt( 0 );
if ( truncate && Character.isUpperCase( c ) ) {
truncate = false;
}
@@ -108,16 +111,18 @@ public abstract class CacheRegionUtils {
}
/**
- * join
+ * Same as Hibernate internal {@link org.hibernate.internal.util.StringHelper#join} methods
*
- * @param elements
- * @param c
+ * @param elements The things to join
+ * @param c The separator between elements
+ *
+ * @return The joined string
*/
private static String join(String[] elements, char c) {
if ( elements == null ) {
return null;
}
- StringBuilder sb = new StringBuilder();
+ final StringBuilder sb = new StringBuilder();
for ( String s : elements ) {
sb.append( s ).append( c );
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CollectionStats.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CollectionStats.java
index a6eebe5280..667a3ab8b3 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CollectionStats.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CollectionStats.java
@@ -23,10 +23,6 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
@@ -36,6 +32,9 @@ import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
import org.hibernate.stat.CollectionStatistics;
@@ -62,7 +61,7 @@ public class CollectionStats implements Serializable {
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Collection";
private static final String TABULAR_TYPE_DESCRIPTION = "All Collection Statistics";
- private static final String[] INDEX_NAMES = new String[] { "roleName", };
+ private static final String[] INDEX_NAMES = new String[] {"roleName",};
private static final TabularType TABULAR_TYPE;
static {
@@ -73,7 +72,7 @@ public class CollectionStats implements Serializable {
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
@@ -115,19 +114,23 @@ public class CollectionStats implements Serializable {
/**
- * @param roleName
+ * Constructs a CollectionsStats
+ *
+ * @param role The collection role
*/
- public CollectionStats(String roleName) {
- this.roleName = roleName;
- this.shortName = CacheRegionUtils.determineShortName( roleName );
+ public CollectionStats(String role) {
+ this.roleName = role;
+ this.shortName = CacheRegionUtils.determineShortName( role );
}
/**
- * @param name
- * @param src
+ * Constructs a CollectionsStats
+ *
+ * @param role The collection role
+ * @param src The CollectionStatistics instance
*/
- public CollectionStats(String name, CollectionStatistics src) {
- this( name );
+ public CollectionStats(String role, CollectionStatistics src) {
+ this( role );
try {
this.loadCount = BeanUtils.getLongBeanProperty( src, "loadCount" );
@@ -136,15 +139,18 @@ public class CollectionStats implements Serializable {
this.removeCount = BeanUtils.getLongBeanProperty( src, "removeCount" );
this.recreateCount = BeanUtils.getLongBeanProperty( src, "recreateCount" );
}
- catch ( Exception e ) {
+ catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
}
/**
- * @param cData
+ * Constructs a CollectionsStats from a JMX CompositeData
+ *
+ * @param cData The JMX CompositeData
*/
+ @SuppressWarnings("UnusedAssignment")
public CollectionStats(final CompositeData cData) {
int i = 0;
roleName = (String) cData.get( ITEM_NAMES[i++] );
@@ -156,17 +162,10 @@ public class CollectionStats implements Serializable {
recreateCount = (Long) cData.get( ITEM_NAMES[i++] );
}
- private static int safeParseInt(String s) {
- try {
- return Integer.parseInt( s );
- }
- catch ( Exception e ) {
- return -1;
- }
- }
-
/**
- * @param stats
+ * Update the internal stats
+ *
+ * @param stats The incoming stats
*/
public void add(CollectionStats stats) {
loadCount += stats.getLoadCount();
@@ -176,9 +175,6 @@ public class CollectionStats implements Serializable {
recreateCount += stats.getRecreateCount();
}
- /**
- * toString
- */
@Override
public String toString() {
return "roleName=" + roleName + "shortName=" + shortName + ", loadCount=" + loadCount + ", fetchCount="
@@ -186,86 +182,75 @@ public class CollectionStats implements Serializable {
+ recreateCount;
}
- /**
- * getRoleName
- */
+ @SuppressWarnings("UnusedDeclaration")
public String getRoleName() {
return roleName;
}
- /**
- * getShortName
- */
+ @SuppressWarnings("UnusedDeclaration")
public String getShortName() {
return shortName;
}
- /**
- * getLoadCount
- */
public long getLoadCount() {
return loadCount;
}
- /**
- * getFetchCount
- */
public long getFetchCount() {
return fetchCount;
}
- /**
- * getUpdateCount
- */
public long getUpdateCount() {
return updateCount;
}
- /**
- * getRemoveCount
- */
public long getRemoveCount() {
return removeCount;
}
- /**
- * getRecreateCount
- */
public long getRecreateCount() {
return recreateCount;
}
/**
- * toCompositeData
+ * Builds a JMX CompositeData view of our state
+ *
+ * @return The JMX CompositeData
*/
public CompositeData toCompositeData() {
try {
return new CompositeDataSupport(
- COMPOSITE_TYPE, ITEM_NAMES, new Object[] {
- roleName, shortName, loadCount,
- fetchCount, updateCount, removeCount, recreateCount,
- }
+ COMPOSITE_TYPE,
+ ITEM_NAMES,
+ new Object[] { roleName, shortName, loadCount, fetchCount, updateCount, removeCount, recreateCount }
);
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
/**
- * newTabularDataInstance
+ * Builds a JMX TabularData
+ *
+ * @return JMX TabularData
*/
public static TabularData newTabularDataInstance() {
return new TabularDataSupport( TABULAR_TYPE );
}
/**
- * fromTabularData
+ * Re-builds CollectionStats from JMX TabularData
+ *
+ * @param tabularData The JMX TabularData
+ *
+ * @return The CollectionsStats
*/
+ @SuppressWarnings("UnusedDeclaration")
public static CollectionStats[] fromTabularData(final TabularData tabularData) {
- final List countList = new ArrayList( tabularData.size() );
- for ( final Iterator pos = tabularData.values().iterator(); pos.hasNext(); ) {
- countList.add( new CollectionStats( (CompositeData) pos.next() ) );
+ final List countList = new ArrayList( tabularData.size() );
+ for ( Object o : tabularData.values() ) {
+ countList.add( new CollectionStats( (CompositeData) o ) );
}
return countList.toArray( new CollectionStats[countList.size()] );
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernate.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernate.java
index d63a0c8407..a978ff6140 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernate.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernate.java
@@ -23,12 +23,12 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicBoolean;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
import javax.management.openmbean.TabularData;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.hibernate.management.api.EhcacheHibernateMBean;
@@ -44,7 +44,7 @@ import org.hibernate.SessionFactory;
*
* @author Abhishek Sanoujam
*/
-public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernateMBean {
+public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibernateMBean {
private static final MBeanNotificationInfo NOTIFICATION_INFO;
private final AtomicBoolean statsEnabled = new AtomicBoolean( true );
@@ -52,7 +52,7 @@ public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernat
private volatile HibernateStats hibernateStats = NullHibernateStats.INSTANCE;
static {
- final String[] notifTypes = new String[] { };
+ final String[] notifTypes = new String[] {};
final String name = Notification.class.getName();
final String description = "Ehcache Hibernate Statistics Event";
NOTIFICATION_INFO = new MBeanNotificationInfo( notifTypes, name, description );
@@ -77,7 +77,7 @@ public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernat
try {
hibernateStats = new HibernateStatsImpl( sessionFactory );
}
- catch ( Exception e ) {
+ catch (Exception e) {
throw new RuntimeException( e );
}
}
@@ -588,10 +588,10 @@ public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernat
}
/**
- * @see BaseEmitterBean#getNotificationInfo()
+ * @see AbstractEmitterBean#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
- return new MBeanNotificationInfo[] { NOTIFICATION_INFO };
+ return new MBeanNotificationInfo[] {NOTIFICATION_INFO};
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMBeanRegistrationImpl.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMBeanRegistrationImpl.java
index 9605094fb6..738bca7e05 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMBeanRegistrationImpl.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMBeanRegistrationImpl.java
@@ -23,16 +23,17 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.lang.management.ManagementFactory;
-import java.util.Properties;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
+import java.lang.management.ManagementFactory;
+import java.util.Properties;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Status;
import net.sf.ehcache.event.CacheManagerEventListener;
+
import org.jboss.logging.Logger;
import org.hibernate.SessionFactory;
@@ -48,132 +49,132 @@ import org.hibernate.cfg.Environment;
* @author Abhishek Sanoujam
*/
public class EhcacheHibernateMBeanRegistrationImpl
- implements EhcacheHibernateMBeanRegistration, CacheManagerEventListener {
+ implements EhcacheHibernateMBeanRegistration, CacheManagerEventListener {
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- EhcacheHibernateMBeanRegistrationImpl.class.getName()
- );
- private static final int MAX_MBEAN_REGISTRATION_RETRIES = 50;
- private String cacheManagerClusterUUID;
- private String registeredCacheManagerName;
- private Status status = Status.STATUS_UNINITIALISED;
- private volatile EhcacheHibernate ehcacheHibernate;
- private volatile ObjectName cacheManagerObjectName;
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ EhcacheHibernateMBeanRegistrationImpl.class.getName()
+ );
+ private static final int MAX_MBEAN_REGISTRATION_RETRIES = 50;
+ private String cacheManagerClusterUUID;
+ private String registeredCacheManagerName;
+ private Status status = Status.STATUS_UNINITIALISED;
+ private volatile EhcacheHibernate ehcacheHibernate;
+ private volatile ObjectName cacheManagerObjectName;
- /**
- * {@inheritDoc}
- */
- public synchronized void registerMBeanForCacheManager(final CacheManager manager, final Properties properties)
- throws Exception {
- String sessionFactoryName = properties.getProperty( Environment.SESSION_FACTORY_NAME );
- String name = null;
- if ( sessionFactoryName == null ) {
- name = manager.getName();
- }
- else {
- name = "".equals( sessionFactoryName.trim() ) ? manager.getName() : sessionFactoryName;
- }
- registerBean( name, manager );
- }
+ /**
+ * {@inheritDoc}
+ */
+ public synchronized void registerMBeanForCacheManager(final CacheManager manager, final Properties properties)
+ throws Exception {
+ String sessionFactoryName = properties.getProperty( Environment.SESSION_FACTORY_NAME );
+ String name = null;
+ if ( sessionFactoryName == null ) {
+ name = manager.getName();
+ }
+ else {
+ name = "".equals( sessionFactoryName.trim() ) ? manager.getName() : sessionFactoryName;
+ }
+ registerBean( name, manager );
+ }
- private void registerBean(String name, CacheManager manager) throws Exception {
- ehcacheHibernate = new EhcacheHibernate( manager );
- int tries = 0;
- boolean success = false;
- Exception exception = null;
- cacheManagerClusterUUID = manager.getClusterUUID();
- do {
- this.registeredCacheManagerName = name;
- if ( tries != 0 ) {
- registeredCacheManagerName += "_" + tries;
- }
- try {
- // register the CacheManager MBean
- MBeanServer mBeanServer = getMBeanServer();
- cacheManagerObjectName = EhcacheHibernateMbeanNames.getCacheManagerObjectName(
- cacheManagerClusterUUID,
- registeredCacheManagerName
- );
- mBeanServer.registerMBean( ehcacheHibernate, cacheManagerObjectName );
- success = true;
- break;
- }
- catch ( InstanceAlreadyExistsException e ) {
- success = false;
- exception = e;
- }
- tries++;
- } while ( tries < MAX_MBEAN_REGISTRATION_RETRIES );
- if ( !success ) {
- throw new Exception(
- "Cannot register mbean for CacheManager with name" + manager.getName() + " after "
- + MAX_MBEAN_REGISTRATION_RETRIES + " retries. Last tried name=" + registeredCacheManagerName,
- exception
- );
- }
- status = Status.STATUS_ALIVE;
- }
+ private void registerBean(String name, CacheManager manager) throws Exception {
+ ehcacheHibernate = new EhcacheHibernate( manager );
+ int tries = 0;
+ boolean success = false;
+ Exception exception = null;
+ cacheManagerClusterUUID = manager.getClusterUUID();
+ do {
+ this.registeredCacheManagerName = name;
+ if ( tries != 0 ) {
+ registeredCacheManagerName += "_" + tries;
+ }
+ try {
+ // register the CacheManager MBean
+ MBeanServer mBeanServer = getMBeanServer();
+ cacheManagerObjectName = EhcacheHibernateMbeanNames.getCacheManagerObjectName(
+ cacheManagerClusterUUID,
+ registeredCacheManagerName
+ );
+ mBeanServer.registerMBean( ehcacheHibernate, cacheManagerObjectName );
+ success = true;
+ break;
+ }
+ catch (InstanceAlreadyExistsException e) {
+ success = false;
+ exception = e;
+ }
+ tries++;
+ } while ( tries < MAX_MBEAN_REGISTRATION_RETRIES );
+ if ( !success ) {
+ throw new Exception(
+ "Cannot register mbean for CacheManager with name" + manager.getName() + " after "
+ + MAX_MBEAN_REGISTRATION_RETRIES + " retries. Last tried name=" + registeredCacheManagerName,
+ exception
+ );
+ }
+ status = Status.STATUS_ALIVE;
+ }
- private MBeanServer getMBeanServer() {
- return ManagementFactory.getPlatformMBeanServer();
- }
+ private MBeanServer getMBeanServer() {
+ return ManagementFactory.getPlatformMBeanServer();
+ }
- /**
- * {@inheritDoc}
- */
- public void enableHibernateStatisticsSupport(SessionFactory sessionFactory) {
- ehcacheHibernate.enableHibernateStatistics( sessionFactory );
- }
+ /**
+ * {@inheritDoc}
+ */
+ public void enableHibernateStatisticsSupport(SessionFactory sessionFactory) {
+ ehcacheHibernate.enableHibernateStatistics( sessionFactory );
+ }
- /**
- * {@inheritDoc}
- */
- public synchronized void dispose() throws CacheException {
- if ( status == Status.STATUS_SHUTDOWN ) {
- return;
- }
+ /**
+ * {@inheritDoc}
+ */
+ public synchronized void dispose() throws CacheException {
+ if ( status == Status.STATUS_SHUTDOWN ) {
+ return;
+ }
- try {
- getMBeanServer().unregisterMBean( cacheManagerObjectName );
- }
- catch ( Exception e ) {
- LOG.warn(
- "Error unregistering object instance " + cacheManagerObjectName + " . Error was " + e.getMessage(),
- e
- );
- }
- ehcacheHibernate = null;
- cacheManagerObjectName = null;
- status = Status.STATUS_SHUTDOWN;
- }
+ try {
+ getMBeanServer().unregisterMBean( cacheManagerObjectName );
+ }
+ catch (Exception e) {
+ LOG.warn(
+ "Error unregistering object instance " + cacheManagerObjectName + " . Error was " + e.getMessage(),
+ e
+ );
+ }
+ ehcacheHibernate = null;
+ cacheManagerObjectName = null;
+ status = Status.STATUS_SHUTDOWN;
+ }
- /**
- * {@inheritDoc}
- */
- public synchronized Status getStatus() {
- return status;
- }
+ /**
+ * {@inheritDoc}
+ */
+ public synchronized Status getStatus() {
+ return status;
+ }
- /**
- * No-op in this case
- */
- public void init() throws CacheException {
- // no-op
- }
+ /**
+ * No-op in this case
+ */
+ public void init() throws CacheException {
+ // no-op
+ }
- /**
- * No-op in this case
- */
- public void notifyCacheAdded(String cacheName) {
- // no-op
- }
+ /**
+ * No-op in this case
+ */
+ public void notifyCacheAdded(String cacheName) {
+ // no-op
+ }
- /**
- * No-op in this case
- */
- public void notifyCacheRemoved(String cacheName) {
- // no-op
- }
+ /**
+ * No-op in this case
+ */
+ public void notifyCacheRemoved(String cacheName) {
+ // no-op
+ }
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheStatsImpl.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheStatsImpl.java
index 190c9245a2..b3c90f2727 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheStatsImpl.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheStatsImpl.java
@@ -23,12 +23,12 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
@@ -42,7 +42,7 @@ import net.sf.ehcache.management.sampled.SampledCacheManager;
*
* @author Abhishek Sanoujam
*/
-public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
+public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStats {
private static final long MILLIS_PER_SECOND = 1000;
private static final MBeanNotificationInfo NOTIFICATION_INFO;
@@ -156,7 +156,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
*/
public double getCacheHitRate() {
long now = System.currentTimeMillis();
- double deltaSecs = (double) ( now - statsSince ) / MILLIS_PER_SECOND;
+ double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND;
return getCacheHitCount() / deltaSecs;
}
@@ -193,7 +193,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
*/
public double getCacheMissRate() {
long now = System.currentTimeMillis();
- double deltaSecs = (double) ( now - statsSince ) / MILLIS_PER_SECOND;
+ double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND;
return getCacheMissCount() / deltaSecs;
}
@@ -230,7 +230,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
*/
public double getCachePutRate() {
long now = System.currentTimeMillis();
- double deltaSecs = (double) ( now - statsSince ) / MILLIS_PER_SECOND;
+ double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND;
return getCachePutCount() / deltaSecs;
}
@@ -339,8 +339,8 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
rv.put(
name, new int[] {
(int) cache.getSampledCacheStatistics().getCacheHitMostRecentSample(),
- (int) ( cache.getSampledCacheStatistics().getCacheMissNotFoundMostRecentSample()
- + cache.getSampledCacheStatistics().getCacheMissExpiredMostRecentSample() ),
+ (int) (cache.getSampledCacheStatistics().getCacheMissNotFoundMostRecentSample()
+ + cache.getSampledCacheStatistics().getCacheMissExpiredMostRecentSample()),
(int) cache.getSampledCacheStatistics().getCacheElementPutMostRecentSample(),
}
);
@@ -388,7 +388,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
}
}
}
- return rv.toArray( new String[] { } );
+ return rv.toArray( new String[] {} );
}
/**
@@ -680,10 +680,10 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
}
/**
- * @see BaseEmitterBean#getNotificationInfo()
+ * @see AbstractEmitterBean#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
- return new MBeanNotificationInfo[] { NOTIFICATION_INFO };
+ return new MBeanNotificationInfo[] {NOTIFICATION_INFO};
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EntityStats.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EntityStats.java
index 6ce06f1cee..a121801db3 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EntityStats.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EntityStats.java
@@ -23,10 +23,6 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
@@ -36,6 +32,10 @@ import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
import org.hibernate.stat.EntityStatistics;
@@ -63,7 +63,7 @@ public class EntityStats implements Serializable {
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Entity";
private static final String TABULAR_TYPE_DESCRIPTION = "All Entity Statistics";
- private static final String[] INDEX_NAMES = new String[] { "name", };
+ private static final String[] INDEX_NAMES = new String[] {"name",};
private static final TabularType TABULAR_TYPE;
static {
@@ -74,7 +74,7 @@ public class EntityStats implements Serializable {
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
@@ -142,7 +142,7 @@ public class EntityStats implements Serializable {
this.fetchCount = BeanUtils.getLongBeanProperty( src, "fetchCount" );
this.optimisticFailureCount = BeanUtils.getLongBeanProperty( src, "optimisticFailureCount" );
}
- catch ( Exception e ) {
+ catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
@@ -167,7 +167,7 @@ public class EntityStats implements Serializable {
try {
return Integer.parseInt( s );
}
- catch ( Exception e ) {
+ catch (Exception e) {
return -1;
}
}
@@ -262,7 +262,7 @@ public class EntityStats implements Serializable {
}
);
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/HibernateStatsImpl.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/HibernateStatsImpl.java
index f75bfa3ebe..85eed55b05 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/HibernateStatsImpl.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/HibernateStatsImpl.java
@@ -23,13 +23,13 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.util.ArrayList;
-import java.util.List;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
+import java.util.ArrayList;
+import java.util.List;
import net.sf.ehcache.hibernate.management.api.HibernateStats;
@@ -43,14 +43,14 @@ import org.hibernate.stat.Statistics;
*
* @author Abhishek Sanoujam
*/
-public class HibernateStatsImpl extends BaseEmitterBean implements HibernateStats {
+public class HibernateStatsImpl extends AbstractEmitterBean implements HibernateStats {
private static final double MILLIS_PER_SECOND = 1000;
private static final MBeanNotificationInfo NOTIFICATION_INFO;
private final SessionFactory sessionFactory;
static {
- final String[] notifTypes = new String[] { };
+ final String[] notifTypes = new String[] {};
final String name = Notification.class.getName();
final String description = "Hibernate Statistics Event";
NOTIFICATION_INFO = new MBeanNotificationInfo( notifTypes, name, description );
@@ -172,7 +172,7 @@ public class HibernateStatsImpl extends BaseEmitterBean implements HibernateStat
public double getQueryExecutionRate() {
long startTime = getStatistics().getStartTime();
long now = System.currentTimeMillis();
- double deltaSecs = ( now - startTime ) / MILLIS_PER_SECOND;
+ double deltaSecs = (now - startTime) / MILLIS_PER_SECOND;
return getQueryExecutionCount() / deltaSecs;
}
@@ -321,10 +321,10 @@ public class HibernateStatsImpl extends BaseEmitterBean implements HibernateStat
}
/**
- * @see BaseEmitterBean#getNotificationInfo()
+ * @see AbstractEmitterBean#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
- return new MBeanNotificationInfo[] { NOTIFICATION_INFO };
+ return new MBeanNotificationInfo[] {NOTIFICATION_INFO};
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/ProviderMBeanRegistrationHelper.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/ProviderMBeanRegistrationHelper.java
index 10a4c28caf..648cc17cf6 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/ProviderMBeanRegistrationHelper.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/ProviderMBeanRegistrationHelper.java
@@ -31,6 +31,7 @@ import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import net.sf.ehcache.CacheManager;
+
import org.jboss.logging.Logger;
import org.hibernate.SessionFactory;
@@ -48,141 +49,142 @@ import org.hibernate.internal.SessionFactoryRegistry;
* @author Alex Snaps
*/
public class ProviderMBeanRegistrationHelper {
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- ProviderMBeanRegistrationHelper.class.getName()
- );
- private static final int MILLIS_PER_SECOND = 1000;
- private static final int SLEEP_MILLIS = 500;
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ ProviderMBeanRegistrationHelper.class.getName()
+ );
+ private static final int MILLIS_PER_SECOND = 1000;
+ private static final int SLEEP_MILLIS = 500;
- private volatile EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration;
+ private volatile EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration;
- /**
- * Registers mbean for the input cache manager and the session factory name
- *
- * @param manager the backing cachemanager
- * @param properties session factory config properties
- */
- public void registerMBean(final CacheManager manager, final Properties properties) {
- if ( Boolean.getBoolean( "tc.active" ) ) {
- ehcacheHibernateMBeanRegistration = new EhcacheHibernateMBeanRegistrationImpl();
- manager.getTimer().scheduleAtFixedRate(
- new RegisterMBeansTask( ehcacheHibernateMBeanRegistration, manager, properties ), SLEEP_MILLIS,
- SLEEP_MILLIS
- );
- }
- }
+ /**
+ * Registers mbean for the input cache manager and the session factory name
+ *
+ * @param manager the backing cachemanager
+ * @param properties session factory config properties
+ */
+ public void registerMBean(final CacheManager manager, final Properties properties) {
+ if ( Boolean.getBoolean( "tc.active" ) ) {
+ ehcacheHibernateMBeanRegistration = new EhcacheHibernateMBeanRegistrationImpl();
+ manager.getTimer().scheduleAtFixedRate(
+ new RegisterMBeansTask( ehcacheHibernateMBeanRegistration, manager, properties ), SLEEP_MILLIS,
+ SLEEP_MILLIS
+ );
+ }
+ }
- /**
- * Unregisters previously registered mbean.
- */
- public void unregisterMBean() {
- if ( ehcacheHibernateMBeanRegistration != null ) {
- ehcacheHibernateMBeanRegistration.dispose();
- ehcacheHibernateMBeanRegistration = null;
- }
- }
+ /**
+ * Unregisters previously registered mbean.
+ */
+ public void unregisterMBean() {
+ if ( ehcacheHibernateMBeanRegistration != null ) {
+ ehcacheHibernateMBeanRegistration.dispose();
+ ehcacheHibernateMBeanRegistration = null;
+ }
+ }
- /**
- * Task for running mbean registration that can be scheduled in a timer
- */
- private static class RegisterMBeansTask extends TimerTask {
- private static final int NUM_SECONDS = 30;
- private long startTime;
- private final AtomicBoolean mbeanRegistered = new AtomicBoolean( false );
- private final EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration;
- private final CacheManager manager;
- private final Properties properties;
+ /**
+ * Task for running mbean registration that can be scheduled in a timer
+ */
+ private static class RegisterMBeansTask extends TimerTask {
+ private static final int NUM_SECONDS = 30;
+ private long startTime;
+ private final AtomicBoolean mbeanRegistered = new AtomicBoolean( false );
+ private final EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration;
+ private final CacheManager manager;
+ private final Properties properties;
- public RegisterMBeansTask(EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration,
- CacheManager manager, Properties properties) {
- this.ehcacheHibernateMBeanRegistration = ehcacheHibernateMBeanRegistration;
- this.manager = manager;
- this.properties = properties;
- }
+ public RegisterMBeansTask(
+ EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration,
+ CacheManager manager, Properties properties) {
+ this.ehcacheHibernateMBeanRegistration = ehcacheHibernateMBeanRegistration;
+ this.manager = manager;
+ this.properties = properties;
+ }
- @Override
- public void run() {
- LOG.debug( "Running mbean initializer task for ehcache hibernate..." );
- startTime = System.currentTimeMillis();
- if ( mbeanRegistered.compareAndSet( false, true ) ) {
- try {
- ehcacheHibernateMBeanRegistration.registerMBeanForCacheManager( manager, properties );
- LOG.debug( "Successfully registered bean" );
- }
- catch ( Exception e ) {
- throw new CacheException( e );
- }
- }
- SessionFactory sessionFactory = locateSessionFactory();
- if ( sessionFactory == null ) {
- LOG.debug(
- "SessionFactory is probably still being initialized..."
- + " waiting for it to complete before enabling hibernate statistics monitoring via JMX"
- );
- if ( System.currentTimeMillis() > startTime + ( NUM_SECONDS * MILLIS_PER_SECOND ) ) {
- LOG.info( "Hibernate statistics monitoring through JMX is DISABLED." );
- LOG.info(
- "Failed to look up SessionFactory after " + NUM_SECONDS + " seconds using session-factory properties '"
- + properties + "'"
- );
- this.cancel();
- }
- return;
- }
- else {
- ehcacheHibernateMBeanRegistration.enableHibernateStatisticsSupport( sessionFactory );
- LOG.info( "Hibernate statistics monitoring through JMX is ENABLED. " );
- this.cancel();
- }
- }
+ @Override
+ public void run() {
+ LOG.debug( "Running mbean initializer task for ehcache hibernate..." );
+ startTime = System.currentTimeMillis();
+ if ( mbeanRegistered.compareAndSet( false, true ) ) {
+ try {
+ ehcacheHibernateMBeanRegistration.registerMBeanForCacheManager( manager, properties );
+ LOG.debug( "Successfully registered bean" );
+ }
+ catch (Exception e) {
+ throw new CacheException( e );
+ }
+ }
+ SessionFactory sessionFactory = locateSessionFactory();
+ if ( sessionFactory == null ) {
+ LOG.debug(
+ "SessionFactory is probably still being initialized..."
+ + " waiting for it to complete before enabling hibernate statistics monitoring via JMX"
+ );
+ if ( System.currentTimeMillis() > startTime + (NUM_SECONDS * MILLIS_PER_SECOND) ) {
+ LOG.info( "Hibernate statistics monitoring through JMX is DISABLED." );
+ LOG.info(
+ "Failed to look up SessionFactory after " + NUM_SECONDS + " seconds using session-factory properties '"
+ + properties + "'"
+ );
+ this.cancel();
+ }
+ return;
+ }
+ else {
+ ehcacheHibernateMBeanRegistration.enableHibernateStatisticsSupport( sessionFactory );
+ LOG.info( "Hibernate statistics monitoring through JMX is ENABLED. " );
+ this.cancel();
+ }
+ }
- private SessionFactory locateSessionFactory() {
- String jndiName = properties.getProperty( Environment.SESSION_FACTORY_NAME );
- if ( jndiName != null ) {
- return SessionFactoryRegistry.INSTANCE.getNamedSessionFactory( jndiName );
- }
- try {
- Class factoryType = SessionFactoryRegistry.class;
- Field instancesField = getField( factoryType, "sessionFactoryMap" );
- if ( instancesField == null ) {
- throw new RuntimeException( "Expected 'sessionFactoryMap' field on " + SessionFactoryRegistry.class.getName() );
- }
- instancesField.setAccessible( true );
- Map map = (Map) instancesField.get( SessionFactoryRegistry.INSTANCE );
- if ( map == null ) {
- return null;
- }
- Iterator values = map.values().iterator();
- while ( values.hasNext() ) {
- SessionFactory sessionFactory = (SessionFactory) values.next();
- Class sessionFactoryType = sessionFactory.getClass();
- Field propertiesField = getField( sessionFactoryType, "properties" );
- if ( propertiesField != null ) {
- propertiesField.setAccessible( true );
- Properties props = (Properties) propertiesField.get( sessionFactory );
- if ( props != null && props.equals( properties ) ) {
- return sessionFactory;
- }
- }
- }
- }
- catch ( RuntimeException re ) {
- LOG.error( "Error locating Hibernate Session Factory", re );
- }
- catch ( IllegalAccessException iae ) {
- LOG.error( "Error locating Hibernate Session Factory", iae );
- }
- return null;
- }
- }
+ private SessionFactory locateSessionFactory() {
+ String jndiName = properties.getProperty( Environment.SESSION_FACTORY_NAME );
+ if ( jndiName != null ) {
+ return SessionFactoryRegistry.INSTANCE.getNamedSessionFactory( jndiName );
+ }
+ try {
+ Class factoryType = SessionFactoryRegistry.class;
+ Field instancesField = getField( factoryType, "sessionFactoryMap" );
+ if ( instancesField == null ) {
+ throw new RuntimeException( "Expected 'sessionFactoryMap' field on " + SessionFactoryRegistry.class.getName() );
+ }
+ instancesField.setAccessible( true );
+ Map map = (Map) instancesField.get( SessionFactoryRegistry.INSTANCE );
+ if ( map == null ) {
+ return null;
+ }
+ Iterator values = map.values().iterator();
+ while ( values.hasNext() ) {
+ SessionFactory sessionFactory = (SessionFactory) values.next();
+ Class sessionFactoryType = sessionFactory.getClass();
+ Field propertiesField = getField( sessionFactoryType, "properties" );
+ if ( propertiesField != null ) {
+ propertiesField.setAccessible( true );
+ Properties props = (Properties) propertiesField.get( sessionFactory );
+ if ( props != null && props.equals( properties ) ) {
+ return sessionFactory;
+ }
+ }
+ }
+ }
+ catch (RuntimeException re) {
+ LOG.error( "Error locating Hibernate Session Factory", re );
+ }
+ catch (IllegalAccessException iae) {
+ LOG.error( "Error locating Hibernate Session Factory", iae );
+ }
+ return null;
+ }
+ }
- private static Field getField(Class c, String fieldName) {
- for ( Field field : c.getDeclaredFields() ) {
- if ( field.getName().equals( fieldName ) ) {
- return field;
- }
- }
- throw new NoSuchFieldError( "Type '" + c + "' has no field '" + fieldName + "'" );
- }
+ private static Field getField(Class c, String fieldName) {
+ for ( Field field : c.getDeclaredFields() ) {
+ if ( field.getName().equals( fieldName ) ) {
+ return field;
+ }
+ }
+ throw new NoSuchFieldError( "Type '" + c + "' has no field '" + fieldName + "'" );
+ }
}
\ No newline at end of file
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/QueryStats.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/QueryStats.java
index 594b3f022f..27c33bea14 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/QueryStats.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/QueryStats.java
@@ -23,10 +23,6 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
@@ -36,6 +32,10 @@ import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
import org.hibernate.stat.QueryStatistics;
@@ -75,7 +75,7 @@ public class QueryStats implements Serializable {
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Query";
private static final String TABULAR_TYPE_DESCRIPTION = "All Query Statistics";
- private static final String[] INDEX_NAMES = new String[] { "query", };
+ private static final String[] INDEX_NAMES = new String[] {"query",};
private static final TabularType TABULAR_TYPE;
static {
@@ -86,7 +86,7 @@ public class QueryStats implements Serializable {
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
@@ -161,7 +161,7 @@ public class QueryStats implements Serializable {
this.executionMinTime =
BeanUtils.getLongBeanProperty( src, "executionMinTime" );
}
- catch ( Exception e ) {
+ catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
@@ -187,7 +187,7 @@ public class QueryStats implements Serializable {
try {
return Integer.parseInt( s );
}
- catch ( Exception e ) {
+ catch (Exception e) {
return -1;
}
}
@@ -297,7 +297,7 @@ public class QueryStats implements Serializable {
}
);
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/package-info.java
new file mode 100644
index 0000000000..3724875d2c
--- /dev/null
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines JMX support for the Ehcache integration
+ */
+package org.hibernate.cache.ehcache.management.impl;
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/package-info.java
new file mode 100644
index 0000000000..64d91cc77e
--- /dev/null
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines the integration with Ehcache as a second-level cache service.
+ */
+package org.hibernate.cache.ehcache;
From 20866585f35691fb98b69cff352a4a7ee3f6edcb Mon Sep 17 00:00:00 2001
From: Steve Ebersole
Date: Tue, 30 Apr 2013 14:40:44 -0500
Subject: [PATCH 35/57] HHH-8159 - Apply fixups indicated by analysis tools
---
.../osgi/HibernateBundleActivator.java | 37 ++++-----
.../hibernate/osgi/OsgiArchiveDescriptor.java | 26 ++++---
.../osgi/OsgiArchiveDescriptorFactory.java | 8 +-
.../org/hibernate/osgi/OsgiClassLoader.java | 39 ++++++----
.../org/hibernate/osgi/OsgiJtaPlatform.java | 10 ++-
.../osgi/OsgiPersistenceProvider.java | 60 +++++++++------
.../osgi/OsgiPersistenceProviderService.java | 20 +++--
.../java/org/hibernate/osgi/OsgiScanner.java | 6 +-
.../osgi/{util => }/OsgiServiceUtil.java | 27 +++++--
.../osgi/OsgiSessionFactoryService.java | 76 ++++++++++---------
.../java/org/hibernate/osgi/package-info.java | 4 +
11 files changed, 195 insertions(+), 118 deletions(-)
rename hibernate-osgi/src/main/java/org/hibernate/osgi/{util => }/OsgiServiceUtil.java (72%)
create mode 100644 hibernate-osgi/src/main/java/org/hibernate/osgi/package-info.java
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java
index 8bd6824e48..fdf0d1ea89 100644
--- a/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java
@@ -51,37 +51,40 @@ import org.osgi.framework.FrameworkUtil;
* SessionFactory is registered as an OSGi ServiceFactory -- each requesting
* bundle gets its own instance of a SessionFactory. The use of services,
* rather than direct use of Configuration, is necessary to shield users
- * from ClassLoader issues. See {@link #OsgiSessionFactoryService} for more
+ * from ClassLoader issues. See {@link OsgiSessionFactoryService} for more
* information.
*
* @author Brett Meyer
* @author Tim Ward
*/
+@SuppressWarnings("UnusedDeclaration")
public class HibernateBundleActivator implements BundleActivator {
-
- private OsgiClassLoader osgiClassLoader;
-
- private OsgiJtaPlatform osgiJtaPlatform;
-
@Override
+ @SuppressWarnings("unchecked")
public void start(BundleContext context) throws Exception {
-
- osgiClassLoader = new OsgiClassLoader();
+ // build a ClassLoader that uses all the necessary OSGi bundles, and place it into
+ // a well-known location so internals can access it
+ final OsgiClassLoader osgiClassLoader = new OsgiClassLoader();
osgiClassLoader.addBundle( FrameworkUtil.getBundle( Session.class ) );
osgiClassLoader.addBundle( FrameworkUtil.getBundle( HibernatePersistenceProvider.class ) );
ClassLoaderHelper.overridenClassLoader = osgiClassLoader;
- osgiJtaPlatform = new OsgiJtaPlatform( context );
+ // Build a JtaPlatform specific for this OSGi context
+ final OsgiJtaPlatform osgiJtaPlatform = new OsgiJtaPlatform( context );
- Dictionary properties = new Hashtable();
- // In order to support existing persistence.xml files, register
- // using the legacy provider name.
+ final Dictionary properties = new Hashtable();
+ // In order to support existing persistence.xml files, register using the legacy provider name.
properties.put( "javax.persistence.provider", HibernatePersistenceProvider.class.getName() );
- context.registerService( PersistenceProvider.class.getName(),
- new OsgiPersistenceProviderService( osgiClassLoader, osgiJtaPlatform, context ), properties );
-
- context.registerService( SessionFactory.class.getName(),
- new OsgiSessionFactoryService( osgiClassLoader, osgiJtaPlatform, context ), new Hashtable());
+ context.registerService(
+ PersistenceProvider.class.getName(),
+ new OsgiPersistenceProviderService( osgiClassLoader, osgiJtaPlatform, context ),
+ properties
+ );
+ context.registerService(
+ SessionFactory.class.getName(),
+ new OsgiSessionFactoryService( osgiClassLoader, osgiJtaPlatform, context ),
+ new Hashtable()
+ );
}
@Override
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptor.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptor.java
index 6a73acca0a..fc554e4216 100644
--- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptor.java
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptor.java
@@ -37,18 +37,26 @@ import org.osgi.framework.Bundle;
import org.osgi.framework.wiring.BundleWiring;
/**
+ * ArchiveDescriptor implementation for describing archives in the OSGi sense
+ *
* @author Brett Meyer
* @author Tim Ward
*/
public class OsgiArchiveDescriptor implements ArchiveDescriptor {
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ OsgiArchiveDescriptor.class.getName()
+ );
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class,
- OsgiArchiveDescriptor.class.getName() );
-
- private BundleWiring bundleWiring;
-
- private Bundle persistenceBundle;
+ private final Bundle persistenceBundle;
+ private final BundleWiring bundleWiring;
+ /**
+ * Creates a OsgiArchiveDescriptor
+ *
+ * @param persistenceBundle The bundle being described as an archive
+ */
+ @SuppressWarnings("RedundantCast")
public OsgiArchiveDescriptor(Bundle persistenceBundle) {
this.persistenceBundle = persistenceBundle;
bundleWiring = (BundleWiring) persistenceBundle.adapt( BundleWiring.class );
@@ -56,14 +64,12 @@ public class OsgiArchiveDescriptor implements ArchiveDescriptor {
@Override
public void visitArchive(ArchiveContext context) {
- Collection resources = bundleWiring.listResources( "/", "*", BundleWiring.LISTRESOURCES_RECURSE );
+ final Collection resources = bundleWiring.listResources( "/", "*", BundleWiring.LISTRESOURCES_RECURSE );
for ( final String resource : resources ) {
- // TODO: Is there a better way to check this? Karaf is including
- // directories.
+ // TODO: Is there a better way to check this? Karaf is including directories.
if ( !resource.endsWith( "/" ) ) {
try {
// TODO: Is using resource as the names correct?
-
final InputStreamAccess inputStreamAccess = new InputStreamAccess() {
@Override
public String getStreamName() {
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptorFactory.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptorFactory.java
index 97264cf5b4..81489715a7 100644
--- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptorFactory.java
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptorFactory.java
@@ -27,13 +27,19 @@ import org.hibernate.jpa.boot.archive.spi.ArchiveDescriptorFactory;
import org.osgi.framework.Bundle;
/**
+ * ArchiveDescriptorFactory implementation for OSGi environments
+ *
* @author Brett Meyer
* @author Tim Ward
*/
public class OsgiArchiveDescriptorFactory implements ArchiveDescriptorFactory {
-
private Bundle persistenceBundle;
+ /**
+ * Creates a OsgiArchiveDescriptorFactory
+ *
+ * @param persistenceBundle The OSGi bundle being scanned
+ */
public OsgiArchiveDescriptorFactory(Bundle persistenceBundle) {
this.persistenceBundle = persistenceBundle;
}
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiClassLoader.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiClassLoader.java
index 2088742d53..d8babd732c 100644
--- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiClassLoader.java
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiClassLoader.java
@@ -41,15 +41,11 @@ import org.osgi.framework.Bundle;
* @author Tim Ward
*/
public class OsgiClassLoader extends ClassLoader {
-
private List classLoaders = new ArrayList();
-
private List bundles = new ArrayList();
-
+
private Map> classCache = new HashMap>();
-
private Map resourceCache = new HashMap();
-
private Map> resourceListCache = new HashMap>();
/**
@@ -57,8 +53,8 @@ public class OsgiClassLoader extends ClassLoader {
* TODO: Should this throw a different exception or warn if multiple
* classes were found? Naming collisions can and do happen in OSGi...
*/
- @SuppressWarnings("rawtypes")
@Override
+ @SuppressWarnings("rawtypes")
protected Class> findClass(String name) throws ClassNotFoundException {
if ( classCache.containsKey( name ) ) {
return classCache.get( name );
@@ -66,7 +62,7 @@ public class OsgiClassLoader extends ClassLoader {
for ( Bundle bundle : bundles ) {
try {
- Class clazz = bundle.loadClass( name );
+ final Class clazz = bundle.loadClass( name );
if ( clazz != null ) {
classCache.put( name, clazz );
return clazz;
@@ -78,7 +74,7 @@ public class OsgiClassLoader extends ClassLoader {
for ( ClassLoader classLoader : classLoaders ) {
try {
- Class clazz = classLoader.loadClass( name );
+ final Class clazz = classLoader.loadClass( name );
if ( clazz != null ) {
classCache.put( name, clazz );
return clazz;
@@ -104,7 +100,7 @@ public class OsgiClassLoader extends ClassLoader {
for ( Bundle bundle : bundles ) {
try {
- URL resource = bundle.getResource( name );
+ final URL resource = bundle.getResource( name );
if ( resource != null ) {
resourceCache.put( name, resource );
return resource;
@@ -116,7 +112,7 @@ public class OsgiClassLoader extends ClassLoader {
for ( ClassLoader classLoader : classLoaders ) {
try {
- URL resource = classLoader.getResource( name );
+ final URL resource = classLoader.getResource( name );
if ( resource != null ) {
resourceCache.put( name, resource );
return resource;
@@ -135,8 +131,8 @@ public class OsgiClassLoader extends ClassLoader {
* TODO: Should this throw a different exception or warn if multiple
* classes were found? Naming collisions can and do happen in OSGi...
*/
- @SuppressWarnings("unchecked")
@Override
+ @SuppressWarnings("unchecked")
protected Enumeration findResources(String name) {
if ( resourceListCache.containsKey( name ) ) {
return resourceListCache.get( name );
@@ -146,7 +142,7 @@ public class OsgiClassLoader extends ClassLoader {
for ( Bundle bundle : bundles ) {
try {
- Enumeration resources = bundle.getResources( name );
+ final Enumeration resources = bundle.getResources( name );
if ( resources != null ) {
enumerations.add( resources );
}
@@ -157,7 +153,7 @@ public class OsgiClassLoader extends ClassLoader {
for ( ClassLoader classLoader : classLoaders ) {
try {
- Enumeration resources = classLoader.getResources( name );
+ final Enumeration resources = classLoader.getResources( name );
if ( resources != null ) {
enumerations.add( resources );
}
@@ -166,7 +162,7 @@ public class OsgiClassLoader extends ClassLoader {
}
}
- Enumeration aggEnumeration = new Enumeration() {
+ final Enumeration aggEnumeration = new Enumeration() {
@Override
public boolean hasMoreElements() {
for ( Enumeration enumeration : enumerations ) {
@@ -193,14 +189,27 @@ public class OsgiClassLoader extends ClassLoader {
return aggEnumeration;
}
+ /**
+ * Adds a ClassLoader to the wrapped set of ClassLoaders
+ *
+ * @param classLoader The ClassLoader to add
+ */
public void addClassLoader( ClassLoader classLoader ) {
classLoaders.add( classLoader );
}
+ /**
+ * Adds a Bundle to the wrapped set of Bundles
+ *
+ * @param bundle The Bundle to add
+ */
public void addBundle( Bundle bundle ) {
bundles.add( bundle );
}
-
+
+ /**
+ * Clear all resources.
+ */
public void clear() {
classCache.clear();
resourceCache.clear();
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiJtaPlatform.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiJtaPlatform.java
index 29ae4707d4..5dd4888037 100644
--- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiJtaPlatform.java
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiJtaPlatform.java
@@ -38,24 +38,28 @@ import org.osgi.framework.ServiceReference;
* @author Brett Meyer
*/
public class OsgiJtaPlatform implements JtaPlatform {
-
private static final long serialVersionUID = 1L;
private BundleContext bundleContext;
+ /**
+ * Constructs a OsgiJtaPlatform
+ *
+ * @param bundleContext The OSGi bundle context
+ */
public OsgiJtaPlatform(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
@Override
public TransactionManager retrieveTransactionManager() {
- ServiceReference sr = bundleContext.getServiceReference( TransactionManager.class.getName() );
+ final ServiceReference sr = bundleContext.getServiceReference( TransactionManager.class.getName() );
return (TransactionManager) bundleContext.getService( sr );
}
@Override
public UserTransaction retrieveUserTransaction() {
- ServiceReference sr = bundleContext.getServiceReference( UserTransaction.class.getName() );
+ final ServiceReference sr = bundleContext.getServiceReference( UserTransaction.class.getName() );
return (UserTransaction) bundleContext.getService( sr );
}
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java
index 01ccff48ee..23cc77d8b7 100644
--- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java
@@ -37,27 +37,36 @@ import org.hibernate.jpa.HibernatePersistenceProvider;
import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
import org.hibernate.jpa.boot.spi.IntegratorProvider;
import org.hibernate.jpa.boot.spi.StrategyRegistrationProviderList;
-import org.hibernate.osgi.util.OsgiServiceUtil;
+
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleReference;
/**
+ * Acts as the PersistenceProvider service in OSGi environments
+ *
* @author Brett Meyer
* @author Tim Ward
*/
public class OsgiPersistenceProvider extends HibernatePersistenceProvider {
-
private OsgiClassLoader osgiClassLoader;
-
private OsgiJtaPlatform osgiJtaPlatform;
-
private Bundle requestingBundle;
-
private BundleContext context;
- public OsgiPersistenceProvider(OsgiClassLoader osgiClassLoader, OsgiJtaPlatform osgiJtaPlatform,
- Bundle requestingBundle, BundleContext context) {
+ /**
+ * Constructs a OsgiPersistenceProvider
+ *
+ * @param osgiClassLoader The ClassLoader we built from OSGi Bundles
+ * @param osgiJtaPlatform The OSGi-specific JtaPlatform impl we built
+ * @param requestingBundle The OSGi Bundle requesting the PersistenceProvider
+ * @param context The OSGi context
+ */
+ public OsgiPersistenceProvider(
+ OsgiClassLoader osgiClassLoader,
+ OsgiJtaPlatform osgiJtaPlatform,
+ Bundle requestingBundle,
+ BundleContext context) {
this.osgiClassLoader = osgiClassLoader;
this.osgiJtaPlatform = osgiJtaPlatform;
this.requestingBundle = requestingBundle;
@@ -68,14 +77,15 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider {
// EMFBuilder somehow?
@Override
+ @SuppressWarnings("unchecked")
public EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) {
- properties = generateProperties( properties );
+ final Map settings = generateSettings( properties );
// TODO: This needs tested.
- properties.put( org.hibernate.jpa.AvailableSettings.SCANNER, new OsgiScanner( requestingBundle ) );
+ settings.put( org.hibernate.jpa.AvailableSettings.SCANNER, new OsgiScanner( requestingBundle ) );
// TODO: This is temporary -- for PersistenceXmlParser's use of
// ClassLoaderServiceImpl#fromConfigSettings
- properties.put( AvailableSettings.ENVIRONMENT_CLASSLOADER, osgiClassLoader );
+ settings.put( AvailableSettings.ENVIRONMENT_CLASSLOADER, osgiClassLoader );
osgiClassLoader.addBundle( requestingBundle );
@@ -83,45 +93,49 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider {
}
@Override
+ @SuppressWarnings("unchecked")
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
- properties = generateProperties( properties );
+ final Map settings = generateSettings( properties );
// OSGi ClassLoaders must implement BundleReference
- properties.put( org.hibernate.jpa.AvailableSettings.SCANNER,
- new OsgiScanner( ( (BundleReference) info.getClassLoader() ).getBundle() ) );
+ settings.put(
+ org.hibernate.jpa.AvailableSettings.SCANNER,
+ new OsgiScanner( ( (BundleReference) info.getClassLoader() ).getBundle() )
+ );
osgiClassLoader.addClassLoader( info.getClassLoader() );
return super.createContainerEntityManagerFactory( info, properties );
}
- private Map generateProperties(Map properties) {
- if ( properties == null ) {
- properties = new HashMap();
+ @SuppressWarnings("unchecked")
+ private Map generateSettings(Map properties) {
+ final Map settings = new HashMap();
+ if ( properties != null ) {
+ settings.putAll( properties );
}
- properties.put( AvailableSettings.JTA_PLATFORM, osgiJtaPlatform );
+ settings.put( AvailableSettings.JTA_PLATFORM, osgiJtaPlatform );
final List integrators = OsgiServiceUtil.getServiceImpls( Integrator.class, context );
- IntegratorProvider integratorProvider = new IntegratorProvider() {
+ final IntegratorProvider integratorProvider = new IntegratorProvider() {
@Override
public List getIntegrators() {
return integrators;
}
};
- properties.put( EntityManagerFactoryBuilderImpl.INTEGRATOR_PROVIDER, integratorProvider );
+ settings.put( EntityManagerFactoryBuilderImpl.INTEGRATOR_PROVIDER, integratorProvider );
final List strategyRegistrationProviders = OsgiServiceUtil.getServiceImpls(
StrategyRegistrationProvider.class, context );
- StrategyRegistrationProviderList strategyRegistrationProviderList = new StrategyRegistrationProviderList() {
+ final StrategyRegistrationProviderList strategyRegistrationProviderList = new StrategyRegistrationProviderList() {
@Override
public List getStrategyRegistrationProviders() {
return strategyRegistrationProviders;
}
};
- properties.put( EntityManagerFactoryBuilderImpl.STRATEGY_REGISTRATION_PROVIDERS,
- strategyRegistrationProviderList );
+ settings.put( EntityManagerFactoryBuilderImpl.STRATEGY_REGISTRATION_PROVIDERS, strategyRegistrationProviderList );
- return properties;
+ return settings;
}
}
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java
index 5ab228568f..f3bc51c9a5 100644
--- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java
@@ -26,22 +26,28 @@ import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
/**
- * See the description on {@link #OsgiSessionFactoryService}. This class
- * is similar, providing an PersistenceProvider as an OSGi Service.
+ * See the description on {@link OsgiSessionFactoryService}. This class is similar, providing an
+ * PersistenceProvider as an OSGi Service.
*
* @author Brett Meyer
* @author Tim Ward
*/
public class OsgiPersistenceProviderService implements ServiceFactory {
-
private OsgiClassLoader osgiClassLoader;
-
private OsgiJtaPlatform osgiJtaPlatform;
-
private BundleContext context;
- public OsgiPersistenceProviderService( OsgiClassLoader osgiClassLoader,
- OsgiJtaPlatform osgiJtaPlatform, BundleContext context ) {
+ /**
+ * Constructs a OsgiPersistenceProviderService
+ *
+ * @param osgiClassLoader The OSGi-specific ClassLoader created in HibernateBundleActivator
+ * @param osgiJtaPlatform The OSGi-specific JtaPlatform created in HibernateBundleActivator
+ * @param context The OSGi context
+ */
+ public OsgiPersistenceProviderService(
+ OsgiClassLoader osgiClassLoader,
+ OsgiJtaPlatform osgiJtaPlatform,
+ BundleContext context) {
this.osgiClassLoader = osgiClassLoader;
this.osgiJtaPlatform = osgiJtaPlatform;
this.context = context;
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiScanner.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiScanner.java
index ac753466ae..aa570348b8 100644
--- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiScanner.java
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiScanner.java
@@ -31,7 +31,11 @@ import org.osgi.framework.Bundle;
* @author Tim Ward
*/
public class OsgiScanner extends AbstractScannerImpl {
-
+ /**
+ * Constructs the scanner for finding things in a OSGi bundle
+ *
+ * @param persistenceBundle The OSGi Bundle to scan
+ */
public OsgiScanner(Bundle persistenceBundle) {
super( new OsgiArchiveDescriptorFactory( persistenceBundle ) );
}
diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/util/OsgiServiceUtil.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiServiceUtil.java
similarity index 72%
rename from hibernate-osgi/src/main/java/org/hibernate/osgi/util/OsgiServiceUtil.java
rename to hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiServiceUtil.java
index 0b9ddc0ed4..05e4603d92 100644
--- a/hibernate-osgi/src/main/java/org/hibernate/osgi/util/OsgiServiceUtil.java
+++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiServiceUtil.java
@@ -18,7 +18,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
-package org.hibernate.osgi.util;
+package org.hibernate.osgi;
import java.util.ArrayList;
import java.util.Collection;
@@ -30,17 +30,29 @@ import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
/**
+ * Utilities for dealing with OSGi environments
+ *
* @author Brett Meyer
*/
public class OsgiServiceUtil {
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ OsgiServiceUtil.class.getName()
+ );
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class,
- OsgiServiceUtil.class.getName() );
-
+ /**
+ * Locate all implementors of the given service contract in the given OSGi buindle context
+ *
+ * @param contract The service contract for which to locate implementors
+ * @param context The OSGi bundle context
+ * @param