From 23b6f6ab06a305b72e70c3623fe2404849f36fe5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Galder=20Zamarre=C3=B1o?= Date: Mon, 6 May 2013 11:44:56 +0100 Subject: [PATCH 01/25] Add missing javadocs and fix rest of Checkstyle failures --- .../infinispan/InfinispanRegionFactory.java | 6 + .../cache/infinispan/TypeOverrides.java | 57 ++++++++++ .../access/PutFromLoadValidator.java | 27 ++++- .../access/TransactionalAccessDelegate.java | 106 +++++++++++++----- .../collection/CollectionRegionImpl.java | 11 ++ .../collection/TransactionalAccess.java | 2 +- .../infinispan/entity/EntityRegionImpl.java | 12 +- .../infinispan/entity/ReadOnlyAccess.java | 2 +- .../entity/TransactionalAccess.java | 2 +- .../impl/BaseGeneralDataRegion.java | 9 +- .../cache/infinispan/impl/BaseRegion.java | 18 ++- .../impl/BaseTransactionalDataRegion.java | 10 +- .../naturalid/NaturalIdRegionImpl.java | 8 ++ .../query/QueryResultsRegionImpl.java | 11 +- .../ClusteredTimestampsRegionImpl.java | 7 ++ .../timestamp/TimestampsRegionImpl.java | 9 +- .../tm/HibernateTransactionManagerLookup.java | 9 +- .../infinispan/util/CacheCommandFactory.java | 16 +++ .../util/CacheCommandInitializer.java | 6 + .../cache/infinispan/util/Caches.java | 103 +++++++++++++++++ .../infinispan/util/EvictAllCommand.java | 11 ++ 21 files changed, 402 insertions(+), 40 deletions(-) diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java index baf582ec83..0fe6a36f72 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java @@ -90,6 +90,12 @@ public class InfinispanRegionFactory implements RegionFactory { */ public static final String INFINISPAN_CONFIG_RESOURCE_PROP = "hibernate.cache.infinispan.cfg"; + /** + * Property name that controls whether Infinispan statistics are enabled. + * The property value is expected to be a boolean true or false, and it + * overrides statistic configuration in base Infinispan configuration, + * if provided. + */ public static final String INFINISPAN_GLOBAL_STATISTICS_PROP = "hibernate.cache.infinispan.statistics"; /** diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/TypeOverrides.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/TypeOverrides.java index f6e940171e..5222c5193a 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/TypeOverrides.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/TypeOverrides.java @@ -69,6 +69,12 @@ public class TypeOverrides { return evictionStrategy; } + /** + * Sets eviction strategy for cached type. + * + * @param evictionStrategy String defining eviction strategy allowed. + * Possible values are defined in {@link EvictionStrategy} + */ public void setEvictionStrategy(String evictionStrategy) { markAsOverriden( "evictionStrategy" ); this.evictionStrategy = EvictionStrategy.valueOf( uc( evictionStrategy ) ); @@ -78,6 +84,13 @@ public class TypeOverrides { return evictionWakeUpInterval; } + /** + * Sets how often eviction process should be run for the cached type. + * + * @param evictionWakeUpInterval long representing the frequency for executing + * the eviction process, in milliseconds + * + */ public void setEvictionWakeUpInterval(long evictionWakeUpInterval) { markAsOverriden( "evictionWakeUpInterval" ); this.evictionWakeUpInterval = evictionWakeUpInterval; @@ -87,6 +100,14 @@ public class TypeOverrides { return evictionMaxEntries; } + /** + * Maximum number of entries in a cache for this cached type. Cache size + * is guaranteed not to exceed upper limit specified by max entries. + * However, due to the nature of eviction it is unlikely to ever be + * exactly maximum number of entries specified here. + * + * @param evictionMaxEntries number of maximum cache entries + */ public void setEvictionMaxEntries(int evictionMaxEntries) { markAsOverriden( "evictionMaxEntries" ); this.evictionMaxEntries = evictionMaxEntries; @@ -96,6 +117,14 @@ public class TypeOverrides { return expirationLifespan; } + /** + * Maximum lifespan of a cache entry, after which the entry is expired + * cluster-wide, in milliseconds. -1 means the entries never expire. + * + * @param expirationLifespan long representing the maximum lifespan, + * in milliseconds, for a cached entry before + * it's expired + */ public void setExpirationLifespan(long expirationLifespan) { markAsOverriden( "expirationLifespan" ); this.expirationLifespan = expirationLifespan; @@ -105,6 +134,15 @@ public class TypeOverrides { return expirationMaxIdle; } + /** + * Maximum idle time a cache entry will be maintained in the cache, in + * milliseconds. If the idle time is exceeded, the entry will be expired + * cluster-wide. -1 means the entries never expire. + * + * @param expirationMaxIdle long representing the maximum idle time, in + * milliseconds, for a cached entry before it's + * expired + */ public void setExpirationMaxIdle(long expirationMaxIdle) { markAsOverriden( "expirationMaxIdle" ); this.expirationMaxIdle = expirationMaxIdle; @@ -114,11 +152,24 @@ public class TypeOverrides { return isExposeStatistics; } + /** + * Enable statistics gathering and reporting via JMX. + * + * @param isExposeStatistics boolean indicating whether statistics should + * be enabled or disabled + */ public void setExposeStatistics(boolean isExposeStatistics) { markAsOverriden( "isExposeStatistics" ); this.isExposeStatistics = isExposeStatistics; } + /** + * Apply the configuration overrides in this {@link TypeOverrides} instance + * to the cache configuration builder passed as parameter. + * + * @param builder cache configuration builder on which to apply + * configuration overrides + */ public void applyTo(ConfigurationBuilder builder) { if ( overridden.contains( "evictionStrategy" ) ) { builder.eviction().strategy( evictionStrategy ); @@ -140,6 +191,12 @@ public class TypeOverrides { } } + /** + * Validate the configuration for this cached type. + * + * @param cfg configuration to validate + * @throws CacheException if validation fails + */ public void validateInfinispanConfiguration(Configuration cfg) throws CacheException { // no-op, method overriden } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/PutFromLoadValidator.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/PutFromLoadValidator.java index e9c0e704ed..3ca5b0b289 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/PutFromLoadValidator.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/PutFromLoadValidator.java @@ -89,7 +89,6 @@ public class PutFromLoadValidator { * {@link #acquirePutFromLoadLock(Object)} that hasn't been * {@link #registerPendingPut(Object) pre-registered} (aka a "naked put") * will return false. - * will return false. */ public static final long NAKED_PUT_INVALIDATION_PERIOD = TimeUnit.SECONDS.toMillis( 20 ); @@ -128,15 +127,23 @@ public class PutFromLoadValidator { private volatile long invalidationTimestamp; /** - * Creates a new PutFromLoadValidator. + * Creates a new put from load validator instance. + * + * @param cache Cache instance on which to store pending put information. */ public PutFromLoadValidator(AdvancedCache cache) { this( cache, NAKED_PUT_INVALIDATION_PERIOD ); } - /** - * Constructor variant for use by unit tests; allows control of various timeouts by the test. - */ + /** + * Constructor variant for use by unit tests; allows control of various timeouts by the test. + * + * @param cache Cache instance on which to store pending put information. + * @param nakedPutInvalidationPeriod Period (in ms) after a removal during which a call to + * {@link #acquirePutFromLoadLock(Object)} that hasn't been + * {@link #registerPendingPut(Object) pre-registered} (aka a "naked put") + * will return false. + */ public PutFromLoadValidator( AdvancedCache cache, long nakedPutInvalidationPeriod) { @@ -146,6 +153,16 @@ public class PutFromLoadValidator { ); } + /** + * Creates a new put from load validator instance. + * + * @param cacheManager where to find a cache to store pending put information + * @param tm transaction manager + * @param nakedPutInvalidationPeriod Period (in ms) after a removal during which a call to + * {@link #acquirePutFromLoadLock(Object)} that hasn't been + * {@link #registerPendingPut(Object) pre-registered} (aka a "naked put") + * will return false. + */ public PutFromLoadValidator( EmbeddedCacheManager cacheManager, TransactionManager tm, long nakedPutInvalidationPeriod) { diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java index f3c8490ab2..8069383837 100755 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java @@ -32,7 +32,6 @@ import org.infinispan.util.logging.LogFactory; import org.hibernate.cache.CacheException; import org.hibernate.cache.infinispan.impl.BaseRegion; import org.hibernate.cache.infinispan.util.Caches; -import org.hibernate.cache.spi.access.SoftLock; /** * Defines the strategy for transactional access to entity or collection data in a Infinispan instance. @@ -53,6 +52,12 @@ public class TransactionalAccessDelegate { private final PutFromLoadValidator putValidator; private final AdvancedCache writeCache; + /** + * Create a new transactional access delegate instance. + * + * @param region to control access to + * @param validator put from load validator + */ public TransactionalAccessDelegate(BaseRegion region, PutFromLoadValidator validator) { this.region = region; this.cache = region.getCache(); @@ -60,21 +65,50 @@ public class TransactionalAccessDelegate { this.writeCache = Caches.ignoreReturnValuesCache( cache ); } + /** + * Attempt to retrieve an object from the cache. + * + * @param key The key of the item to be retrieved + * @param txTimestamp a timestamp prior to the transaction start time + * @return the cached object or null + * @throws CacheException if the cache retrieval failed + */ public Object get(Object key, long txTimestamp) throws CacheException { if ( !region.checkValid() ) { return null; } - Object val = cache.get( key ); + final Object val = cache.get( key ); if ( val == null ) { putValidator.registerPendingPut( key ); } return val; } + /** + * Attempt to cache an object, after loading from the database. + * + * @param key The item key + * @param value The item + * @param txTimestamp a timestamp prior to the transaction start time + * @param version the item version number + * @return true if the object was successfully cached + */ public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) { return putFromLoad( key, value, txTimestamp, version, false ); } + /** + * Attempt to cache an object, after loading from the database, explicitly + * specifying the minimalPut behavior. + * + * @param key The item key + * @param value The item + * @param txTimestamp a timestamp prior to the transaction start time + * @param version the item version number + * @param minimalPutOverride Explicit minimalPut flag + * @return true if the object was successfully cached + * @throws CacheException if storing the object failed + */ public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { if ( !region.checkValid() ) { @@ -110,20 +144,16 @@ public class TransactionalAccessDelegate { return true; } - public SoftLock lockItem(Object key, Object version) throws CacheException { - return null; - } - - public SoftLock lockRegion() throws CacheException { - return null; - } - - public void unlockItem(Object key, SoftLock lock) throws CacheException { - } - - public void unlockRegion(SoftLock lock) throws CacheException { - } - + /** + * Called after an item has been inserted (before the transaction completes), + * instead of calling evict(). + * + * @param key The item key + * @param value The item + * @param version The item's version value + * @return Were the contents of the cache actual changed by this operation? + * @throws CacheException if the insert fails + */ public boolean insert(Object key, Object value, Object version) throws CacheException { if ( !region.checkValid() ) { return false; @@ -133,10 +163,17 @@ public class TransactionalAccessDelegate { return true; } - public boolean afterInsert(Object key, Object value, Object version) throws CacheException { - return false; - } - + /** + * Called after an item has been updated (before the transaction completes), + * instead of calling evict(). + * + * @param key The item key + * @param value The item + * @param currentVersion The item's current version value + * @param previousVersion The item's previous version value + * @return Whether the contents of the cache actual changed by this operation + * @throws CacheException if the update fails + */ public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { // We update whether or not the region is valid. Other nodes @@ -146,11 +183,12 @@ public class TransactionalAccessDelegate { return true; } - public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) - throws CacheException { - return false; - } - + /** + * Called after an item has become stale (before the transaction completes). + * + * @param key The key of the item to remove + * @throws CacheException if removing the cached item fails + */ public void remove(Object key) throws CacheException { if ( !putValidator.invalidateKey( key ) ) { throw new CacheException( @@ -163,6 +201,11 @@ public class TransactionalAccessDelegate { writeCache.remove( key ); } + /** + * Called to evict data from the entire region + * + * @throws CacheException if eviction the region fails + */ public void removeAll() throws CacheException { if ( !putValidator.invalidateRegion() ) { throw new CacheException( "Failed to invalidate pending putFromLoad calls for region " + region.getName() ); @@ -170,6 +213,13 @@ public class TransactionalAccessDelegate { cache.clear(); } + /** + * Forcibly evict an item from the cache immediately without regard for transaction + * isolation. + * + * @param key The key of the item to remove + * @throws CacheException if evicting the item fails + */ public void evict(Object key) throws CacheException { if ( !putValidator.invalidateKey( key ) ) { throw new CacheException( @@ -179,6 +229,12 @@ public class TransactionalAccessDelegate { writeCache.remove( key ); } + /** + * Forcibly evict all items from the cache immediately without regard for transaction + * isolation. + * + * @throws CacheException if evicting items fails + */ public void evictAll() throws CacheException { if ( !putValidator.invalidateRegion() ) { throw new CacheException( "Failed to invalidate pending putFromLoad calls for region " + region.getName() ); diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/CollectionRegionImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/CollectionRegionImpl.java index 626575b43e..f3d8c1577d 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/CollectionRegionImpl.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/CollectionRegionImpl.java @@ -35,18 +35,29 @@ import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy; /** + * Collection region implementation + * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ public class CollectionRegionImpl extends BaseTransactionalDataRegion implements CollectionRegion { + /** + * Construct a collection region + * + * @param cache instance to store collection instances + * @param name of collection type + * @param metadata for the collection type + * @param factory for the region + */ public CollectionRegionImpl( AdvancedCache cache, String name, CacheDataDescription metadata, RegionFactory factory) { super( cache, name, metadata, factory ); } + @Override public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { if ( AccessType.READ_ONLY.equals( accessType ) || AccessType.TRANSACTIONAL.equals( accessType ) ) { diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/TransactionalAccess.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/TransactionalAccess.java index 6116f0fe49..1c38d236c2 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/TransactionalAccess.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/TransactionalAccess.java @@ -94,4 +94,4 @@ class TransactionalAccess implements CollectionRegionAccessStrategy { public void unlockRegion(SoftLock lock) throws CacheException { } -} \ No newline at end of file +} diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/EntityRegionImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/EntityRegionImpl.java index 725250a8b8..ba01fdac3e 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/EntityRegionImpl.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/EntityRegionImpl.java @@ -35,12 +35,22 @@ import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.EntityRegionAccessStrategy; /** + * Entity region implementation + * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ public class EntityRegionImpl extends BaseTransactionalDataRegion implements EntityRegion { + /** + * Construct a entity region + * + * @param cache instance to store entity instances + * @param name of entity type + * @param metadata for the entity type + * @param factory for the region + */ public EntityRegionImpl( AdvancedCache cache, String name, CacheDataDescription metadata, RegionFactory factory) { @@ -63,4 +73,4 @@ public class EntityRegionImpl extends BaseTransactionalDataRegion implements Ent return new PutFromLoadValidator( cache ); } -} \ No newline at end of file +} diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/ReadOnlyAccess.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/ReadOnlyAccess.java index 12843abc66..c943be0e0a 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/ReadOnlyAccess.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/ReadOnlyAccess.java @@ -54,4 +54,4 @@ class ReadOnlyAccess extends TransactionalAccess { throw new UnsupportedOperationException( "Illegal attempt to edit read only item" ); } -} \ No newline at end of file +} diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/TransactionalAccess.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/TransactionalAccess.java index ba3cb95ce8..ca935d405d 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/TransactionalAccess.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/TransactionalAccess.java @@ -111,4 +111,4 @@ class TransactionalAccess implements EntityRegionAccessStrategy { throws CacheException { return false; } -} \ No newline at end of file +} diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java index b9b722ecd9..e4bc360c1e 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java @@ -17,6 +17,13 @@ import org.hibernate.cache.spi.RegionFactory; public abstract class BaseGeneralDataRegion extends BaseRegion implements GeneralDataRegion { private final AdvancedCache putCache; + /** + * General data region constructor. + * + * @param cache instance for the region + * @param name of the region + * @param factory for this region + */ public BaseGeneralDataRegion( AdvancedCache cache, String name, RegionFactory factory) { @@ -46,4 +53,4 @@ public abstract class BaseGeneralDataRegion extends BaseRegion implements Genera putCache.put( key, value ); } -} \ No newline at end of file +} diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java index f6d320435e..9b57694ee2 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java @@ -68,6 +68,13 @@ public abstract class BaseRegion implements Region { protected final AdvancedCache cache; + /** + * Base region constructor. + * + * @param cache instance for the region + * @param name of the region + * @param factory for this region + */ public BaseRegion(AdvancedCache cache, String name, RegionFactory factory) { this.cache = cache; this.name = name; @@ -147,6 +154,12 @@ public abstract class BaseRegion implements Region { return checkValid() && cache.containsKey( key ); } + /** + * Checks if the region is valid for operations such as storing new data + * in the region, or retrieving data from the region. + * + * @return true if the region is valid, false otherwise + */ public boolean checkValid() { boolean valid = isValid(); if ( !valid ) { @@ -154,7 +167,7 @@ public abstract class BaseRegion implements Region { if ( invalidateState.compareAndSet( InvalidateState.INVALID, InvalidateState.CLEARING ) ) { - Transaction tx = suspend(); + final Transaction tx = suspend(); try { // Clear region in a separate transaction Caches.withinTx( @@ -228,6 +241,9 @@ public abstract class BaseRegion implements Region { } } + /** + * Invalidates the region. + */ public void invalidateRegion() { if ( log.isTraceEnabled() ) { log.trace( "Invalidate region: " + name ); diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java index 250199458a..7e22a3d5bf 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java @@ -41,6 +41,14 @@ public abstract class BaseTransactionalDataRegion private final CacheDataDescription metadata; + /** + * Base transactional region constructor + * + * @param cache instance to store transactional data + * @param name of the transactional region + * @param metadata for the transactional region + * @param factory for the transactional region + */ public BaseTransactionalDataRegion( AdvancedCache cache, String name, CacheDataDescription metadata, RegionFactory factory) { @@ -53,4 +61,4 @@ public abstract class BaseTransactionalDataRegion return metadata; } -} \ No newline at end of file +} diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/NaturalIdRegionImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/NaturalIdRegionImpl.java index 8486d970a2..8b72a0f1c5 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/NaturalIdRegionImpl.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/NaturalIdRegionImpl.java @@ -43,6 +43,14 @@ import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy; public class NaturalIdRegionImpl extends BaseTransactionalDataRegion implements NaturalIdRegion { + /** + * Constructor for the natural id region. + * + * @param cache instance to store natural ids + * @param name of natural id region + * @param metadata for the natural id region + * @param factory for the natural id region + */ public NaturalIdRegionImpl( AdvancedCache cache, String name, CacheDataDescription metadata, RegionFactory factory) { diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java index 69182290f8..bdfa898e3e 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java @@ -35,6 +35,8 @@ import org.hibernate.cache.spi.QueryResultsRegion; import org.hibernate.cache.spi.RegionFactory; /** + * Region for caching query results. + * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 @@ -45,6 +47,13 @@ public class QueryResultsRegionImpl extends BaseTransactionalDataRegion implemen private final AdvancedCache putCache; private final AdvancedCache getCache; + /** + * Query region constructor + * + * @param cache instance to store queries + * @param name of the query region + * @param factory for the query region + */ public QueryResultsRegionImpl(AdvancedCache cache, String name, RegionFactory factory) { super( cache, name, null, factory ); // If Infinispan is using INVALIDATION for query cache, we don't want to propagate changes. @@ -128,4 +137,4 @@ public class QueryResultsRegionImpl extends BaseTransactionalDataRegion implemen } } -} \ No newline at end of file +} diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/ClusteredTimestampsRegionImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/ClusteredTimestampsRegionImpl.java index 83f490af9c..7658739bdd 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/ClusteredTimestampsRegionImpl.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/ClusteredTimestampsRegionImpl.java @@ -56,6 +56,13 @@ public class ClusteredTimestampsRegionImpl extends TimestampsRegionImpl { */ private final Map localCache = new ConcurrentHashMap(); + /** + * Clustered timestamps region constructor. + * + * @param cache instance to store update timestamps + * @param name of the update timestamps region + * @param factory for the update timestamps region + */ public ClusteredTimestampsRegionImpl( AdvancedCache cache, String name, RegionFactory factory) { diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java index 2d8aca302d..38f737ebdd 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java @@ -46,6 +46,13 @@ public class TimestampsRegionImpl extends BaseGeneralDataRegion implements Times private final AdvancedCache removeCache; private final AdvancedCache timestampsPutCache; + /** + * Local timestamps region constructor. + * + * @param cache instance to store update timestamps + * @param name of the update timestamps region + * @param factory for the update timestamps region + */ public TimestampsRegionImpl( AdvancedCache cache, String name, RegionFactory factory) { @@ -111,4 +118,4 @@ public class TimestampsRegionImpl extends BaseGeneralDataRegion implements Times } } -} \ No newline at end of file +} diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/tm/HibernateTransactionManagerLookup.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/tm/HibernateTransactionManagerLookup.java index 071a827782..230f63f26b 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/tm/HibernateTransactionManagerLookup.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/tm/HibernateTransactionManagerLookup.java @@ -28,7 +28,8 @@ import org.hibernate.cfg.Settings; import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; /** - * HibernateTransactionManagerLookup. + * Hibernate transaction manager lookup class for Infinispan, so that + * Hibernate's transaction manager can be hooked onto Infinispan. * * @author Galder Zamarreño * @since 3.5 @@ -36,6 +37,12 @@ import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; public class HibernateTransactionManagerLookup implements org.infinispan.transaction.lookup.TransactionManagerLookup { private final JtaPlatform jtaPlatform; + /** + * Transaction manager lookup constructor. + * + * @param settings for the Hibernate application + * @param properties for the Hibernate application + */ public HibernateTransactionManagerLookup(Settings settings, Properties properties) { this.jtaPlatform = settings != null ? settings.getJtaPlatform() : null; } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandFactory.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandFactory.java index 158ab4fb9f..9535369d70 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandFactory.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandFactory.java @@ -42,13 +42,29 @@ import org.hibernate.cache.infinispan.impl.BaseRegion; * @since 4.0 */ public class CacheCommandFactory implements ExtendedModuleCommandFactory { + + /** + * Keeps track of regions to which second-level cache specific + * commands have been plugged. + */ private ConcurrentMap allRegions = new ConcurrentHashMap(); + /** + * Add region so that commands can be cleared on shutdown. + * + * @param regionName name of the region + * @param region instance to keep track of + */ public void addRegion(String regionName, BaseRegion region) { allRegions.put( regionName, region ); } + /** + * Clear all regions from this command factory. + * + * @param regionNames collection of regions to clear + */ public void clearRegions(List regionNames) { for ( String regionName : regionNames ) { allRegions.remove( regionName ); diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandInitializer.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandInitializer.java index 78cb46faed..e06230e581 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandInitializer.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandInitializer.java @@ -34,6 +34,12 @@ import org.infinispan.commands.module.ModuleCommandInitializer; */ public class CacheCommandInitializer implements ModuleCommandInitializer { + /** + * Build an instance of {@link EvictAllCommand} for a given region. + * + * @param regionName name of region for {@link EvictAllCommand} + * @return a new instance of {@link EvictAllCommand} + */ public EvictAllCommand buildEvictAllCommand(String regionName) { // No need to pass region factory because no information on that object // is sent around the cluster. However, when the command factory builds diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/Caches.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/Caches.java index 42adb0c333..0013a639f2 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/Caches.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/Caches.java @@ -42,6 +42,17 @@ public class Caches { // Suppresses default constructor, ensuring non-instantiability. } + /** + * Call an operation within a transaction. This method guarantees that the + * right pattern is used to make sure that the transaction is always either + * committed or rollback. + * + * @param cache instance whose transaction manager to use + * @param c callable instance to run within a transaction + * @param type of callable return + * @return returns whatever the callable returns + * @throws Exception if any operation within the transaction fails + */ public static T withinTx( AdvancedCache cache, Callable c) throws Exception { @@ -49,6 +60,17 @@ public class Caches { return withinTx( cache.getTransactionManager(), c ); } + /** + * Call an operation within a transaction. This method guarantees that the + * right pattern is used to make sure that the transaction is always either + * committed or rollbacked. + * + * @param tm transaction manager + * @param c callable instance to run within a transaction + * @param type of callable return + * @return returns whatever the callable returns + * @throws Exception if any operation within the transaction fails + */ public static T withinTx( TransactionManager tm, Callable c) throws Exception { @@ -70,14 +92,36 @@ public class Caches { } } + /** + * Transform a given cache into a local cache + * + * @param cache to be transformed + * @return a cache that operates only in local-mode + */ public static AdvancedCache localCache(AdvancedCache cache) { return cache.withFlags( Flag.CACHE_MODE_LOCAL ); } + /** + * Transform a given cache into a cache that ignores return values for + * operations returning previous values, i.e. {@link AdvancedCache#put(Object, Object)} + * + * @param cache to be transformed + * @return a cache that ignores return values + */ public static AdvancedCache ignoreReturnValuesCache(AdvancedCache cache) { return cache.withFlags( Flag.SKIP_CACHE_LOAD, Flag.SKIP_REMOTE_LOOKUP ); } + /** + * Transform a given cache into a cache that ignores return values for + * operations returning previous values, i.e. {@link AdvancedCache#put(Object, Object)}, + * adding an extra flag. + * + * @param cache to be transformed + * @param extraFlag to add to the returned cache + * @return a cache that ignores return values + */ public static AdvancedCache ignoreReturnValuesCache( AdvancedCache cache, Flag extraFlag) { return cache.withFlags( @@ -85,6 +129,14 @@ public class Caches { ); } + /** + * Transform a given cache into a cache that writes cache entries without + * waiting for them to complete, adding an extra flag. + * + * @param cache to be transformed + * @param extraFlag to add to the returned cache + * @return a cache that writes asynchronously + */ public static AdvancedCache asyncWriteCache( AdvancedCache cache, Flag extraFlag) { @@ -96,6 +148,12 @@ public class Caches { ); } + /** + * Transform a given cache into a cache that fails silently if cache writes fail. + * + * @param cache to be transformed + * @return a cache that fails silently if cache writes fail + */ public static AdvancedCache failSilentWriteCache(AdvancedCache cache) { return cache.withFlags( Flag.FAIL_SILENTLY, @@ -105,6 +163,14 @@ public class Caches { ); } + /** + * Transform a given cache into a cache that fails silently if + * cache writes fail, adding an extra flag. + * + * @param cache to be transformed + * @param extraFlag to be added to returned cache + * @return a cache that fails silently if cache writes fail + */ public static AdvancedCache failSilentWriteCache( AdvancedCache cache, Flag extraFlag) { @@ -117,6 +183,13 @@ public class Caches { ); } + /** + * Transform a given cache into a cache that fails silently if + * cache reads fail. + * + * @param cache to be transformed + * @return a cache that fails silently if cache reads fail + */ public static AdvancedCache failSilentReadCache(AdvancedCache cache) { return cache.withFlags( Flag.FAIL_SILENTLY, @@ -124,6 +197,11 @@ public class Caches { ); } + /** + * Broadcast an evict-all command with the given cache instance. + * + * @param cache instance used to broadcast command + */ public static void broadcastEvictAll(AdvancedCache cache) { final RpcManager rpcManager = cache.getRpcManager(); if ( rpcManager != null ) { @@ -137,16 +215,41 @@ public class Caches { } } + /** + * Indicates whether the given cache is configured with + * {@link org.infinispan.configuration.cache.CacheMode#INVALIDATION_ASYNC} or + * {@link org.infinispan.configuration.cache.CacheMode#INVALIDATION_SYNC}. + * + * @param cache to check for invalidation configuration + * @return true if the cache is configured with invalidation, false otherwise + */ public static boolean isInvalidationCache(AdvancedCache cache) { return cache.getCacheConfiguration() .clustering().cacheMode().isInvalidation(); } + /** + * Indicates whether the given cache is configured with + * {@link org.infinispan.configuration.cache.CacheMode#REPL_SYNC}, + * {@link org.infinispan.configuration.cache.CacheMode#INVALIDATION_SYNC}, or + * {@link org.infinispan.configuration.cache.CacheMode#DIST_SYNC}. + * + * @param cache to check for synchronous configuration + * @return true if the cache is configured with synchronous mode, false otherwise + */ public static boolean isSynchronousCache(AdvancedCache cache) { return cache.getCacheConfiguration() .clustering().cacheMode().isSynchronous(); } + /** + * Indicates whether the given cache is configured to cluster its contents. + * A cache is considered to clustered if it's configured with any cache mode + * except {@link org.infinispan.configuration.cache.CacheMode#LOCAL} + * + * @param cache to check whether it clusters its contents + * @return true if the cache is configured with clustering, false otherwise + */ public static boolean isClustered(AdvancedCache cache) { return cache.getCacheConfiguration() .clustering().cacheMode().isClustered(); diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/EvictAllCommand.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/EvictAllCommand.java index 5ea96d28aa..8a558e0987 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/EvictAllCommand.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/EvictAllCommand.java @@ -38,12 +38,23 @@ public class EvictAllCommand extends BaseRpcCommand { private final BaseRegion region; + /** + * Evict all command constructor. + * + * @param regionName name of the region to evict + * @param region to evict + */ public EvictAllCommand(String regionName, BaseRegion region) { // region name and cache names are the same... super( regionName ); this.region = region; } + /** + * Evict all command constructor. + * + * @param regionName name of the region to evict + */ public EvictAllCommand(String regionName) { this( regionName, null ); } From 77a4c3e52e3b1a369ba8031dcce8e3ea7f7b7e11 Mon Sep 17 00:00:00 2001 From: Gunnar Morling Date: Fri, 3 May 2013 12:33:40 +0200 Subject: [PATCH 02/25] HHH-8219 - Adding Animal Sniffer plug-in to make sure only Java 6 APIs are used --- build.gradle | 26 ++++++++++++++++++++++++-- libraries.gradle | 6 ++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 8788526015..1b254557ae 100644 --- a/build.gradle +++ b/build.gradle @@ -105,6 +105,8 @@ subprojects { subProject -> configurations { all*.exclude group: 'xml-apis', module: 'xml-apis' } + animalSniffer + javaApiSignature } // appropriately inject the common dependencies into each sub-project @@ -133,6 +135,9 @@ subprojects { subProject -> } jaxb( libraries.jaxb2_basics ) jaxb( libraries.jaxb2_ant ) + + animalSniffer ( libraries.animal_sniffer ) + javaApiSignature ( libraries.java16_signature ) } // mac-specific stuff ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -308,8 +313,25 @@ subprojects { subProject -> } } - // eclipseClasspath will not add sources to classpath unless the dirs actually exist. - eclipseClasspath.dependsOn("generateSources") + // eclipseClasspath will not add sources to classpath unless the dirs actually exist. + eclipseClasspath.dependsOn("generateSources") + + task copyJavaApiSignature(type: Copy) { + from configurations.javaApiSignature + into "$buildDir/javaApiSignature/" + rename '.*signature', 'javaApi.signature' + } + + // checks that only types of the target Java version are used + task checkJavaApiSignature << { + ant.taskdef(name: 'animalSniffer', classname: 'org.codehaus.mojo.animal_sniffer.ant.CheckSignatureTask', classpath: configurations.animalSniffer.asPath) + ant.animalSniffer(signature: "$buildDir/javaApiSignature/javaApi.signature", classpath: configurations.compile.asPath + System.properties.'path.separator' + configurations.provided.asPath) { + path(path: "$buildDir/classes/main") + } + } + checkJavaApiSignature.dependsOn compileJava + checkJavaApiSignature.dependsOn copyJavaApiSignature + check.dependsOn checkJavaApiSignature // specialized API/SPI checkstyle tasks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ task checkstylePublicSources(type: Checkstyle) { diff --git a/libraries.gradle b/libraries.gradle index b08e0eefb8..62da4c0b02 100644 --- a/libraries.gradle +++ b/libraries.gradle @@ -67,6 +67,12 @@ ext { jaxb: 'com.sun.xml.bind:jaxb-xjc:2.1.6', jaxb2_basics: 'org.jvnet.jaxb2_commons:jaxb2-basics:0.6.0', jaxb2_ant: 'org.jvnet.jaxb2_commons:jaxb2-basics-ant:0.6.0', + + // Animal Sniffer Ant Task and Java 1.6 API signature file + // not using 1.9 for the time being due to MANIMALSNIFFER-34 + animal_sniffer: 'org.codehaus.mojo:animal-sniffer-ant-tasks:1.8', + java16_signature: 'org.codehaus.mojo.signature:java16:1.0@signature', + // ~~~~~~~~~~~~~~~~~~~~~~~~~~ testing // logging for testing From 196885498bea1e8c9a365c333b9460c2094b2304 Mon Sep 17 00:00:00 2001 From: Gunnar Morling Date: Fri, 3 May 2013 12:59:06 +0200 Subject: [PATCH 03/25] HHH-8219 - Removing references to methods added in Java 7 --- .../org/hibernate/internal/util/collections/JoinedIterator.java | 2 +- .../src/main/java/org/hibernate/mapping/Collection.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/collections/JoinedIterator.java b/hibernate-core/src/main/java/org/hibernate/internal/util/collections/JoinedIterator.java index 28a910d9b7..02831f4dab 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/util/collections/JoinedIterator.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/collections/JoinedIterator.java @@ -76,7 +76,7 @@ public class JoinedIterator implements Iterator { protected void updateCurrentIterator() { if ( currentIterator == null ) { if( wrappedIterators.length == 0 ) { - currentIterator = Collections.emptyIterator(); + currentIterator = Collections.emptyList().iterator(); } else { currentIterator = wrappedIterators[0]; diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Collection.java b/hibernate-core/src/main/java/org/hibernate/mapping/Collection.java index ba1ec4e63d..22cea240b7 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Collection.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Collection.java @@ -367,7 +367,7 @@ public abstract class Collection implements Fetchable, Value, Filterable { } public Iterator getColumnIterator() { - return Collections.emptyIterator(); + return Collections.emptyList().iterator(); } public int getColumnSpan() { From 1bf647b7ebd694caf4366f49c19825ede414b65c Mon Sep 17 00:00:00 2001 From: Gunnar Morling Date: Thu, 2 May 2013 19:11:35 +0200 Subject: [PATCH 04/25] HHH-8218 - Upgrading to BV 1.1.0.Final and HV 5.0.1.Final --- hibernate-core/hibernate-core.gradle | 2 +- libraries.gradle | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/hibernate-core/hibernate-core.gradle b/hibernate-core/hibernate-core.gradle index 4cd791996f..b49ccff347 100644 --- a/hibernate-core/hibernate-core.gradle +++ b/hibernate-core/hibernate-core.gradle @@ -30,7 +30,7 @@ dependencies { testRuntime( 'jaxen:jaxen:1.1' ) testRuntime( libraries.javassist ) - + testRuntime( libraries.unified_el ) } def pomName() { diff --git a/libraries.gradle b/libraries.gradle index 62da4c0b02..2db72b6e4c 100644 --- a/libraries.gradle +++ b/libraries.gradle @@ -56,7 +56,7 @@ ext { // javax jpa: 'org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.0.Draft-16', jta: 'org.jboss.spec.javax.transaction:jboss-transaction-api_1.2_spec:1.0.0.Alpha1', - validation: 'javax.validation:validation-api:1.1.0.CR3', + validation: 'javax.validation:validation-api:1.1.0.Final', jacc: 'org.jboss.spec.javax.security.jacc:jboss-jacc-api_1.4_spec:1.0.2.Final', // logging @@ -90,12 +90,15 @@ ext { jpa_modelgen: 'org.hibernate:hibernate-jpamodelgen:1.1.1.Final', shrinkwrap_api: 'org.jboss.shrinkwrap:shrinkwrap-api:1.0.0-beta-6', shrinkwrap: 'org.jboss.shrinkwrap:shrinkwrap-impl-base:1.0.0-beta-6', - validator: 'org.hibernate:hibernate-validator:5.0.0.CR4', + validator: 'org.hibernate:hibernate-validator:5.0.1.Final', h2: "com.h2database:h2:${h2Version}", jboss_jta: "org.jboss.jbossts:jbossjta:4.16.4.Final", xapool: "com.experlog:xapool:1.5.0", mockito: 'org.mockito:mockito-core:1.9.0', + // required by Hibernate Validator at test runtime + unified_el: "org.glassfish:javax.el:3.0-b07", + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ infinsipan infinispan: "org.infinispan:infinispan-core:${infinispanVersion}", // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ infinispan test From d67a96e813c16a363c7882e27aa773894b97bd83 Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Mon, 6 May 2013 19:56:13 -0400 Subject: [PATCH 05/25] HHH-8225 EMF cannot be created, closed, then re-created in OSGi --- .../org/hibernate/osgi/OsgiClassLoader.java | 19 +++++++++---------- .../osgi/OsgiPersistenceProvider.java | 4 ++-- 2 files changed, 11 insertions(+), 12 deletions(-) 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 d8babd732c..a748770e2c 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiClassLoader.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiClassLoader.java @@ -27,9 +27,11 @@ import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; +import java.util.Set; import org.osgi.framework.Bundle; @@ -41,12 +43,13 @@ import org.osgi.framework.Bundle; * @author Tim Ward */ public class OsgiClassLoader extends ClassLoader { - private List classLoaders = new ArrayList(); - private List bundles = new ArrayList(); + // Leave these as Sets -- addClassLoader or addBundle may be called more + // than once if a SF or EMF is closed and re-created. + private Set classLoaders = new HashSet(); + private Set bundles = new HashSet(); private Map> classCache = new HashMap>(); private Map resourceCache = new HashMap(); - private Map> resourceListCache = new HashMap>(); /** * Load the class and break on first found match. @@ -128,16 +131,15 @@ public class OsgiClassLoader extends ClassLoader { /** * Load the class and break on first found match. + * + * Note: Since they're Enumerations, do not cache these results! + * * TODO: Should this throw a different exception or warn if multiple * classes were found? Naming collisions can and do happen in OSGi... */ @Override @SuppressWarnings("unchecked") protected Enumeration findResources(String name) { - if ( resourceListCache.containsKey( name ) ) { - return resourceListCache.get( name ); - } - final List> enumerations = new ArrayList>(); for ( Bundle bundle : bundles ) { @@ -184,8 +186,6 @@ public class OsgiClassLoader extends ClassLoader { } }; - resourceListCache.put( name, aggEnumeration ); - return aggEnumeration; } @@ -213,7 +213,6 @@ public class OsgiClassLoader extends ClassLoader { public void clear() { classCache.clear(); resourceCache.clear(); - resourceListCache.clear(); } } 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 c99715b8e5..afb8503e06 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java @@ -90,7 +90,7 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider { osgiClassLoader.addBundle( requestingBundle ); - return super.createEntityManagerFactory( persistenceUnitName, properties ); + return super.createEntityManagerFactory( persistenceUnitName, settings ); } @Override @@ -106,7 +106,7 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider { osgiClassLoader.addClassLoader( info.getClassLoader() ); - return super.createContainerEntityManagerFactory( info, properties ); + return super.createContainerEntityManagerFactory( info, settings ); } @SuppressWarnings("unchecked") From 7004914ec0573d15c2e3c5431050131e4de27c34 Mon Sep 17 00:00:00 2001 From: Strong Liu Date: Tue, 7 May 2013 13:30:29 +0800 Subject: [PATCH 06/25] HHH-8159 - Apply fixups indicated by analysis tools --- build.gradle | 4 +- .../hql/internal/ast/QueryTranslatorImpl.java | 44 +++-- .../ast/util/SessionFactoryHelper.java | 50 ++++-- .../org/hibernate/internal/CriteriaImpl.java | 169 +++++++++--------- ...mponentCollectionCriteriaInfoProvider.java | 75 ++++---- .../loader/criteria/CriteriaJoinWalker.java | 21 +-- .../loader/criteria/CriteriaLoader.java | 22 +-- .../criteria/CriteriaQueryTranslator.java | 157 ++++++++-------- .../criteria/EntityCriteriaInfoProvider.java | 40 ++--- .../ScalarCollectionCriteriaInfoProvider.java | 48 ++--- .../main/java/org/hibernate/sql/JoinType.java | 8 +- 11 files changed, 331 insertions(+), 307 deletions(-) diff --git a/build.gradle b/build.gradle index 1b254557ae..72ab09a538 100644 --- a/build.gradle +++ b/build.gradle @@ -177,7 +177,9 @@ subprojects { subProject -> "-encoding", "UTF-8", "-processor", "org.jboss.logging.processor.apt.LoggingToolsProcessor", "-s", "$sourceSets.main.generatedLoggingSrcDir.absolutePath", - "-AloggingVersion=3.0", +// "-AloggingVersion=3.0", + "-Adebug=true", + "-AskipTranslations=true", "-source", rootProject.javaLanguageLevel, "-target", rootProject.javaLanguageLevel, "-AtranslationFilesPath=${project.rootDir}/src/main/resources" diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java index 0e1f176767..d7f7756641 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java @@ -24,6 +24,7 @@ package org.hibernate.hql.internal.ast; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -133,6 +134,7 @@ public class QueryTranslatorImpl implements FilterTranslator { * @throws QueryException There was a problem parsing the query string. * @throws MappingException There was a problem querying defined mappings. */ + @Override public void compile( Map replacements, boolean shallow) throws QueryException, MappingException { @@ -149,6 +151,7 @@ public class QueryTranslatorImpl implements FilterTranslator { * @throws QueryException There was a problem parsing the query string. * @throws MappingException There was a problem querying defined mappings. */ + @Override public void compile( String collectionRole, Map replacements, @@ -304,7 +307,7 @@ public class QueryTranslatorImpl implements FilterTranslator { throw new QueryExecutionRequestException( "Not supported for select queries", hql ); } } - + @Override public String getQueryIdentifier() { return queryIdentifier; } @@ -322,25 +325,27 @@ public class QueryTranslatorImpl implements FilterTranslator { * * @return an array of Types. */ + @Override public Type[] getReturnTypes() { errorIfDML(); return getWalker().getReturnTypes(); } - + @Override public String[] getReturnAliases() { errorIfDML(); return getWalker().getReturnAliases(); } - + @Override public String[][] getColumnNames() { errorIfDML(); return getWalker().getSelectClause().getColumnNames(); } - + @Override public Set getQuerySpaces() { return getWalker().getQuerySpaces(); } + @Override public List list(SessionImplementor session, QueryParameters queryParameters) throws HibernateException { // Delegate to the QueryLoader... @@ -397,6 +402,7 @@ public class QueryTranslatorImpl implements FilterTranslator { /** * Return the query results as an iterator */ + @Override public Iterator iterate(QueryParameters queryParameters, EventSource session) throws HibernateException { // Delegate to the QueryLoader... @@ -407,13 +413,14 @@ public class QueryTranslatorImpl implements FilterTranslator { /** * Return the query results, as an instance of ScrollableResults */ + @Override public ScrollableResults scroll(QueryParameters queryParameters, SessionImplementor session) throws HibernateException { // Delegate to the QueryLoader... errorIfDML(); return queryLoader.scroll( queryParameters, session ); } - + @Override public int executeUpdate(QueryParameters queryParameters, SessionImplementor session) throws HibernateException { errorIfSelect(); @@ -423,17 +430,16 @@ public class QueryTranslatorImpl implements FilterTranslator { /** * The SQL query string to be called; implemented by all subclasses */ + @Override public String getSQLString() { return sql; } - + @Override public List collectSqlStrings() { ArrayList list = new ArrayList(); if ( isManipulationStatement() ) { String[] sqlStatements = statementExecutor.getSqlStatements(); - for ( int i = 0; i < sqlStatements.length; i++ ) { - list.add( sqlStatements[i] ); - } + Collections.addAll( list, sqlStatements ); } else { list.add( sql ); @@ -446,11 +452,11 @@ public class QueryTranslatorImpl implements FilterTranslator { public boolean isShallowQuery() { return shallowQuery; } - + @Override public String getQueryString() { return hql; } - + @Override public Map getEnabledFilters() { return enabledFilters; } @@ -458,17 +464,17 @@ public class QueryTranslatorImpl implements FilterTranslator { public int[] getNamedParameterLocs(String name) { return getWalker().getNamedParameterLocations( name ); } - + @Override public boolean containsCollectionFetches() { errorIfDML(); List collectionFetches = ( ( QueryNode ) sqlAst ).getFromClause().getCollectionFetches(); return collectionFetches != null && collectionFetches.size() > 0; } - + @Override public boolean isManipulationStatement() { return sqlAst.needsExecutor(); } - + @Override public void validateScrollability() throws HibernateException { // Impl Note: allows multiple collection fetches as long as the // entire fecthed graph still "points back" to a single @@ -496,10 +502,9 @@ public class QueryTranslatorImpl implements FilterTranslator { } FromElement owner = null; - Iterator itr = query.getSelectClause().getFromElementsForLoad().iterator(); - while ( itr.hasNext() ) { + for ( Object o : query.getSelectClause().getFromElementsForLoad() ) { // should be the first, but just to be safe... - final FromElement fromElement = ( FromElement ) itr.next(); + final FromElement fromElement = (FromElement) o; if ( fromElement.getOrigin() == null ) { owner = fromElement; break; @@ -560,7 +565,7 @@ public class QueryTranslatorImpl implements FilterTranslator { throw new QueryException( "Unexpected statement type" ); } } - + @Override public ParameterTranslations getParameterTranslations() { if ( paramTranslations == null ) { paramTranslations = new ParameterTranslationsImpl( getWalker().getParameters() ); @@ -581,6 +586,7 @@ public class QueryTranslatorImpl implements FilterTranslator { public static class JavaConstantConverter implements NodeTraverser.VisitationStrategy { private AST dotRoot; + @Override public void visit(AST node) { if ( dotRoot != null ) { // we are already processing a dot-structure @@ -589,7 +595,7 @@ public class QueryTranslatorImpl implements FilterTranslator { dotRoot = null; } - if ( dotRoot == null && node.getType() == HqlTokenTypes.DOT ) { + if ( node.getType() == HqlTokenTypes.DOT ) { dotRoot = node; handleDotStructure( dotRoot ); } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/util/SessionFactoryHelper.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/util/SessionFactoryHelper.java index 22c57349b4..479690cec5 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/util/SessionFactoryHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/util/SessionFactoryHelper.java @@ -23,6 +23,7 @@ * */ package org.hibernate.hql.internal.ast.util; + import java.util.HashMap; import java.util.Map; @@ -58,8 +59,8 @@ import org.hibernate.type.Type; */ public class SessionFactoryHelper { - private SessionFactoryImplementor sfi; - private Map collectionPropertyMappingByRole; + private final SessionFactoryImplementor sfi; + private final Map collectionPropertyMappingByRole; /** * Construct a new SessionFactoryHelper instance. @@ -68,7 +69,7 @@ public class SessionFactoryHelper { */ public SessionFactoryHelper(SessionFactoryImplementor sfi) { this.sfi = sfi; - collectionPropertyMappingByRole = new HashMap(); + this.collectionPropertyMappingByRole = new HashMap(); } /** @@ -85,6 +86,7 @@ public class SessionFactoryHelper { * for the purpose of inheritance discrimination? * * @param persister The persister to be checked. + * * @return True if the persister does define an actual discriminator column. */ public boolean hasPhysicalDiscriminatorColumn(Queryable persister) { @@ -103,6 +105,7 @@ public class SessionFactoryHelper { * Given a (potentially unqualified) class name, locate its imported qualified name. * * @param className The potentially unqualified class name + * * @return The qualified class name. */ public String getImportedClassName(String className) { @@ -113,6 +116,7 @@ public class SessionFactoryHelper { * Given a (potentially unqualified) class name, locate its persister. * * @param className The (potentially unqualified) class name. + * * @return The defined persister for this class, or null if none found. */ public Queryable findQueryableUsingImports(String className) { @@ -125,6 +129,7 @@ public class SessionFactoryHelper { * * @param sfi The session factory implementor. * @param className The (potentially unqualified) class name. + * * @return The defined persister for this class, or null if none found. */ public static Queryable findQueryableUsingImports(SessionFactoryImplementor sfi, String className) { @@ -133,7 +138,7 @@ public class SessionFactoryHelper { return null; } try { - return ( Queryable ) sfi.getEntityPersister( importedClassName ); + return (Queryable) sfi.getEntityPersister( importedClassName ); } catch ( MappingException me ) { return null; @@ -144,7 +149,9 @@ public class SessionFactoryHelper { * Locate the persister by class or entity name. * * @param name The class or entity name + * * @return The defined persister for this entity, or null if none found. + * * @throws MappingException */ private EntityPersister findEntityPersisterByName(String name) throws MappingException { @@ -169,7 +176,9 @@ public class SessionFactoryHelper { * exist. * * @param name The class or entity name + * * @return The defined persister for this entity + * * @throws SemanticException Indicates the persister could not be found */ public EntityPersister requireClassPersister(String name) throws SemanticException { @@ -190,11 +199,12 @@ public class SessionFactoryHelper { * Locate the collection persister by the collection role. * * @param role The collection role name. + * * @return The defined CollectionPersister for this collection role, or null. */ public QueryableCollection getCollectionPersister(String role) { try { - return ( QueryableCollection ) sfi.getCollectionPersister( role ); + return (QueryableCollection) sfi.getCollectionPersister( role ); } catch ( ClassCastException cce ) { throw new QueryException( "collection is not queryable: " + role ); @@ -209,12 +219,14 @@ public class SessionFactoryHelper { * such a persister exist. * * @param role The collection role name. + * * @return The defined CollectionPersister for this collection role. + * * @throws QueryException Indicates that the collection persister could not be found. */ public QueryableCollection requireQueryableCollection(String role) throws QueryException { try { - QueryableCollection queryableCollection = ( QueryableCollection ) sfi.getCollectionPersister( role ); + QueryableCollection queryableCollection = (QueryableCollection) sfi.getCollectionPersister( role ); if ( queryableCollection != null ) { collectionPropertyMappingByRole.put( role, new CollectionPropertyMapping( queryableCollection ) ); } @@ -232,10 +244,11 @@ public class SessionFactoryHelper { * Retrieve a PropertyMapping describing the given collection role. * * @param role The collection role for which to retrieve the property mapping. + * * @return The property mapping. */ public PropertyMapping getCollectionPropertyMapping(String role) { - return ( PropertyMapping ) collectionPropertyMappingByRole.get( role ); + return collectionPropertyMappingByRole.get( role ); } /** @@ -244,6 +257,7 @@ public class SessionFactoryHelper { * * @param role The collection role * @param roleAlias The sql column-qualification alias (i.e., the table alias) + * * @return the collection element columns */ public String[] getCollectionElementColumns(String role, String roleAlias) { @@ -267,11 +281,12 @@ public class SessionFactoryHelper { * @param tableAlias The table alias to use in qualifying the join conditions * @param joinType The type of join to render (inner, outer, etc); see {@link org.hibernate.sql.JoinFragment} * @param columns The columns making up the condition of the join. + * * @return The generated join sequence. */ public JoinSequence createJoinSequence(boolean implicit, AssociationType associationType, String tableAlias, JoinType joinType, String[] columns) { JoinSequence joinSequence = createJoinSequence(); - joinSequence.setUseThetaStyle( implicit ); // Implicit joins use theta style (WHERE pk = fk), explicit joins use JOIN (after from) + joinSequence.setUseThetaStyle( implicit ); // Implicit joins use theta style (WHERE pk = fk), explicit joins use JOIN (after from) joinSequence.addJoin( associationType, tableAlias, joinType, columns ); return joinSequence; } @@ -281,12 +296,13 @@ public class SessionFactoryHelper { * * @param collPersister The persister for the collection at which the join should be rooted. * @param collectionName The alias to use for qualifying column references. + * * @return The generated join sequence. */ public JoinSequence createCollectionJoinSequence(QueryableCollection collPersister, String collectionName) { JoinSequence joinSequence = createJoinSequence(); joinSequence.setRoot( collPersister, collectionName ); - joinSequence.setUseThetaStyle( true ); // TODO: figure out how this should be set. + joinSequence.setUseThetaStyle( true ); // TODO: figure out how this should be set. /////////////////////////////////////////////////////////////////////////////// // This was the reason for failures regarding INDEX_OP and subclass joins on // theta-join dialects; not sure what behavior we were trying to emulate ;) @@ -299,7 +315,9 @@ public class SessionFactoryHelper { * given type which represents the id or unique-key. * * @param entityType The type representing the entity. + * * @return The corresponding property name + * * @throws QueryException Indicates such a property could not be found. */ public String getIdentifierOrUniqueKeyPropertyName(EntityType entityType) { @@ -315,6 +333,7 @@ public class SessionFactoryHelper { * Retrieve the number of columns represented by this type. * * @param type The type. + * * @return The number of columns. */ public int getColumnSpan(Type type) { @@ -326,6 +345,7 @@ public class SessionFactoryHelper { * contained within instance of that collection. * * @param collectionType The collection type to check. + * * @return The entity name of the elements of this collection. */ public String getAssociatedEntityName(CollectionType collectionType) { @@ -337,6 +357,7 @@ public class SessionFactoryHelper { * within instances of that collection. * * @param collectionType The collection type to be checked. + * * @return The Type of the elements of the collection. */ private Type getElementType(CollectionType collectionType) { @@ -348,16 +369,18 @@ public class SessionFactoryHelper { * element type be an association type. * * @param collectionType The collection type to be checked. + * * @return The AssociationType of the elements of the collection. */ public AssociationType getElementAssociationType(CollectionType collectionType) { - return ( AssociationType ) getElementType( collectionType ); + return (AssociationType) getElementType( collectionType ); } /** * Locate a registered sql function by name. * * @param functionName The name of the function to locate + * * @return The sql function, or null if not found. */ public SQLFunction findSQLFunction(String functionName) { @@ -368,7 +391,9 @@ public class SessionFactoryHelper { * Locate a registered sql function by name, requiring that such a registered function exist. * * @param functionName The name of the function to locate + * * @return The sql function. + * * @throws QueryException Indicates no matching sql functions could be found. */ private SQLFunction requireSQLFunction(String functionName) { @@ -383,7 +408,8 @@ public class SessionFactoryHelper { * Find the function return type given the function name and the first argument expression node. * * @param functionName The function name. - * @param first The first argument expression. + * @param first The first argument expression. + * * @return the function return type given the function name and the first argument expression node. */ public Type findFunctionReturnType(String functionName, AST first) { @@ -395,7 +421,7 @@ public class SessionFactoryHelper { // determine the type of the first argument... Type argumentType = null; if ( firstArgument != null ) { - if ( "cast".equals(functionName) ) { + if ( "cast".equals( functionName ) ) { argumentType = sfi.getTypeResolver().heuristicType( firstArgument.getNextSibling().getText() ); } else if ( SqlNode.class.isInstance( firstArgument ) ) { diff --git a/hibernate-core/src/main/java/org/hibernate/internal/CriteriaImpl.java b/hibernate-core/src/main/java/org/hibernate/internal/CriteriaImpl.java index 437d07eab7..9eb2af6835 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/CriteriaImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/CriteriaImpl.java @@ -57,15 +57,15 @@ public class CriteriaImpl implements Criteria, Serializable { private transient SessionImplementor session; private final String rootAlias; - private List criterionEntries = new ArrayList(); - private List orderEntries = new ArrayList(); + private List criterionEntries = new ArrayList(); + private List orderEntries = new ArrayList(); private Projection projection; private Criteria projectionCriteria; - private List subcriteriaList = new ArrayList(); + private List subcriteriaList = new ArrayList(); - private Map fetchModes = new HashMap(); - private Map lockModes = new HashMap(); + private Map fetchModes = new HashMap(); + private Map lockModes = new HashMap(); private Integer maxResults; private Integer firstResult; @@ -98,7 +98,7 @@ public class CriteriaImpl implements Criteria, Serializable { this.cacheable = false; this.rootAlias = alias; } - + @Override public String toString() { return "CriteriaImpl(" + entityOrClassName + ":" + @@ -124,7 +124,7 @@ public class CriteriaImpl implements Criteria, Serializable { return entityOrClassName; } - public Map getLockModes() { + public Map getLockModes() { return lockModes; } @@ -132,15 +132,15 @@ public class CriteriaImpl implements Criteria, Serializable { return projectionCriteria; } - public Iterator iterateSubcriteria() { + public Iterator iterateSubcriteria() { return subcriteriaList.iterator(); } - public Iterator iterateExpressionEntries() { + public Iterator iterateExpressionEntries() { return criterionEntries.iterator(); } - public Iterator iterateOrderings() { + public Iterator iterateOrderings() { return orderEntries.iterator(); } @@ -151,7 +151,7 @@ public class CriteriaImpl implements Criteria, Serializable { // Criteria impl ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - + @Override public String getAlias() { return rootAlias; } @@ -159,46 +159,45 @@ public class CriteriaImpl implements Criteria, Serializable { public Projection getProjection() { return projection; } - + @Override public Criteria setProjection(Projection projection) { this.projection = projection; this.projectionCriteria = this; setResultTransformer( PROJECTION ); return this; } - + @Override public Criteria add(Criterion expression) { add( this, expression ); return this; } - + @Override public Criteria addOrder(Order ordering) { orderEntries.add( new OrderEntry( ordering, this ) ); return this; } - public FetchMode getFetchMode(String path) { - return (FetchMode) fetchModes.get(path); + return fetchModes.get(path); } - + @Override public Criteria setFetchMode(String associationPath, FetchMode mode) { fetchModes.put( associationPath, mode ); return this; } - + @Override public Criteria setLockMode(LockMode lockMode) { return setLockMode( getAlias(), lockMode ); } - + @Override public Criteria setLockMode(String alias, LockMode lockMode) { lockModes.put( alias, lockMode ); return this; } - + @Override public Criteria createAlias(String associationPath, String alias) { return createAlias( associationPath, alias, JoinType.INNER_JOIN ); } - + @Override public Criteria createAlias(String associationPath, String alias, JoinType joinType) { new Subcriteria( this, associationPath, alias, joinType ); return this; @@ -208,7 +207,7 @@ public class CriteriaImpl implements Criteria, Serializable { public Criteria createAlias(String associationPath, String alias, int joinType) throws HibernateException { return createAlias( associationPath, alias, JoinType.parse( joinType ) ); } - + @Override public Criteria createAlias(String associationPath, String alias, JoinType joinType, Criterion withClause) { new Subcriteria( this, associationPath, alias, joinType, withClause ); return this; @@ -219,11 +218,11 @@ public class CriteriaImpl implements Criteria, Serializable { throws HibernateException { return createAlias( associationPath, alias, JoinType.parse( joinType ), withClause ); } - + @Override public Criteria createCriteria(String associationPath) { return createCriteria( associationPath, JoinType.INNER_JOIN ); } - + @Override public Criteria createCriteria(String associationPath, JoinType joinType) { return new Subcriteria( this, associationPath, joinType ); } @@ -232,11 +231,11 @@ public class CriteriaImpl implements Criteria, Serializable { public Criteria createCriteria(String associationPath, int joinType) throws HibernateException { return createCriteria(associationPath, JoinType.parse( joinType )); } - + @Override public Criteria createCriteria(String associationPath, String alias) { return createCriteria( associationPath, alias, JoinType.INNER_JOIN ); } - + @Override public Criteria createCriteria(String associationPath, String alias, JoinType joinType) { return new Subcriteria( this, associationPath, alias, joinType ); } @@ -245,7 +244,7 @@ public class CriteriaImpl implements Criteria, Serializable { public Criteria createCriteria(String associationPath, String alias, int joinType) throws HibernateException { return createCriteria( associationPath, alias, JoinType.parse( joinType ) ); } - + @Override public Criteria createCriteria(String associationPath, String alias, JoinType joinType, Criterion withClause) { return new Subcriteria( this, associationPath, alias, joinType, withClause ); } @@ -259,7 +258,7 @@ public class CriteriaImpl implements Criteria, Serializable { public ResultTransformer getResultTransformer() { return resultTransformer; } - + @Override public Criteria setResultTransformer(ResultTransformer tupleMapper) { this.resultTransformer = tupleMapper; return this; @@ -268,7 +267,7 @@ public class CriteriaImpl implements Criteria, Serializable { public Integer getMaxResults() { return maxResults; } - + @Override public Criteria setMaxResults(int maxResults) { this.maxResults = maxResults; return this; @@ -277,7 +276,7 @@ public class CriteriaImpl implements Criteria, Serializable { public Integer getFirstResult() { return firstResult; } - + @Override public Criteria setFirstResult(int firstResult) { this.firstResult = firstResult; return this; @@ -286,7 +285,7 @@ public class CriteriaImpl implements Criteria, Serializable { public Integer getFetchSize() { return fetchSize; } - + @Override public Criteria setFetchSize(int fetchSize) { this.fetchSize = fetchSize; return this; @@ -295,22 +294,18 @@ public class CriteriaImpl implements Criteria, Serializable { public Integer getTimeout() { return timeout; } - + @Override public Criteria setTimeout(int timeout) { this.timeout = timeout; return this; } - /** - * {@inheritDoc} - */ + @Override public boolean isReadOnlyInitialized() { return readOnly != null; } - /** - * {@inheritDoc} - */ + @Override public boolean isReadOnly() { if ( ! isReadOnlyInitialized() && getSession() == null ) { throw new IllegalStateException( @@ -318,23 +313,21 @@ public class CriteriaImpl implements Criteria, Serializable { ); } return ( isReadOnlyInitialized() ? - readOnly.booleanValue() : + readOnly : getSession().getPersistenceContext().isDefaultReadOnly() ); } - /** - * {@inheritDoc} - */ + @Override public Criteria setReadOnly(boolean readOnly) { - this.readOnly = Boolean.valueOf( readOnly ); + this.readOnly = readOnly; return this; } public boolean getCacheable() { return this.cacheable; } - + @Override public Criteria setCacheable(boolean cacheable) { this.cacheable = cacheable; return this; @@ -343,7 +336,7 @@ public class CriteriaImpl implements Criteria, Serializable { public String getCacheRegion() { return this.cacheRegion; } - + @Override public Criteria setCacheRegion(String cacheRegion) { this.cacheRegion = cacheRegion.trim(); return this; @@ -352,22 +345,22 @@ public class CriteriaImpl implements Criteria, Serializable { public String getComment() { return comment; } - + @Override public Criteria setComment(String comment) { this.comment = comment; return this; } - + @Override public Criteria setFlushMode(FlushMode flushMode) { this.flushMode = flushMode; return this; } - + @Override public Criteria setCacheMode(CacheMode cacheMode) { this.cacheMode = cacheMode; return this; } - + @Override public List list() throws HibernateException { before(); try { @@ -377,11 +370,11 @@ public class CriteriaImpl implements Criteria, Serializable { after(); } } - + @Override public ScrollableResults scroll() { return scroll( ScrollMode.SCROLL_INSENSITIVE ); } - + @Override public ScrollableResults scroll(ScrollMode scrollMode) { before(); try { @@ -391,7 +384,7 @@ public class CriteriaImpl implements Criteria, Serializable { after(); } } - + @Override public Object uniqueResult() throws HibernateException { return AbstractQueryImpl.uniqueElement( list() ); } @@ -428,7 +421,7 @@ public class CriteriaImpl implements Criteria, Serializable { if ( criterionEntries.size() != 1 ) { return false; } - CriterionEntry ce = (CriterionEntry) criterionEntries.get(0); + CriterionEntry ce = criterionEntries.get(0); return ce.getCriterion() instanceof NaturalIdentifier; } @@ -464,7 +457,7 @@ public class CriteriaImpl implements Criteria, Serializable { private Subcriteria(Criteria parent, String path, JoinType joinType) { this( parent, path, null, joinType ); } - + @Override public String toString() { return "Subcriteria(" + path + ":" @@ -474,7 +467,7 @@ public class CriteriaImpl implements Criteria, Serializable { // State ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - + @Override public String getAlias() { return alias; } @@ -494,7 +487,7 @@ public class CriteriaImpl implements Criteria, Serializable { public LockMode getLockMode() { return lockMode; } - + @Override public Criteria setLockMode(LockMode lockMode) { this.lockMode = lockMode; return this; @@ -513,22 +506,22 @@ public class CriteriaImpl implements Criteria, Serializable { } // Criteria impl ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - + @Override public Criteria add(Criterion expression) { hasRestriction = true; CriteriaImpl.this.add(this, expression); return this; } - + @Override public Criteria addOrder(Order order) { CriteriaImpl.this.orderEntries.add( new OrderEntry(order, this) ); return this; } - + @Override public Criteria createAlias(String associationPath, String alias) { return createAlias( associationPath, alias, JoinType.INNER_JOIN ); } - + @Override public Criteria createAlias(String associationPath, String alias, JoinType joinType) throws HibernateException { new Subcriteria( this, associationPath, alias, joinType ); return this; @@ -538,7 +531,7 @@ public class CriteriaImpl implements Criteria, Serializable { public Criteria createAlias(String associationPath, String alias, int joinType) throws HibernateException { return createAlias( associationPath, alias, JoinType.parse( joinType ) ); } - + @Override public Criteria createAlias(String associationPath, String alias, JoinType joinType, Criterion withClause) throws HibernateException { new Subcriteria( this, associationPath, alias, joinType, withClause ); return this; @@ -549,11 +542,11 @@ public class CriteriaImpl implements Criteria, Serializable { throws HibernateException { return createAlias( associationPath, alias, JoinType.parse( joinType ), withClause ); } - + @Override public Criteria createCriteria(String associationPath) { return createCriteria( associationPath, JoinType.INNER_JOIN ); } - + @Override public Criteria createCriteria(String associationPath, JoinType joinType) throws HibernateException { return new Subcriteria( Subcriteria.this, associationPath, joinType ); } @@ -562,11 +555,11 @@ public class CriteriaImpl implements Criteria, Serializable { public Criteria createCriteria(String associationPath, int joinType) throws HibernateException { return createCriteria( associationPath, JoinType.parse( joinType ) ); } - + @Override public Criteria createCriteria(String associationPath, String alias) { return createCriteria( associationPath, alias, JoinType.INNER_JOIN ); } - + @Override public Criteria createCriteria(String associationPath, String alias, JoinType joinType) throws HibernateException { return new Subcriteria( Subcriteria.this, associationPath, alias, joinType ); } @@ -575,7 +568,7 @@ public class CriteriaImpl implements Criteria, Serializable { public Criteria createCriteria(String associationPath, String alias, int joinType) throws HibernateException { return createCriteria( associationPath, alias, JoinType.parse( joinType ) ); } - + @Override public Criteria createCriteria(String associationPath, String alias, JoinType joinType, Criterion withClause) throws HibernateException { return new Subcriteria( this, associationPath, alias, joinType, withClause ); } @@ -585,96 +578,96 @@ public class CriteriaImpl implements Criteria, Serializable { throws HibernateException { return createCriteria( associationPath, alias, JoinType.parse( joinType ), withClause ); } - + @Override public boolean isReadOnly() { return CriteriaImpl.this.isReadOnly(); } - + @Override public boolean isReadOnlyInitialized() { return CriteriaImpl.this.isReadOnlyInitialized(); } - + @Override public Criteria setReadOnly(boolean readOnly) { CriteriaImpl.this.setReadOnly( readOnly ); return this; } - + @Override public Criteria setCacheable(boolean cacheable) { CriteriaImpl.this.setCacheable(cacheable); return this; } - + @Override public Criteria setCacheRegion(String cacheRegion) { CriteriaImpl.this.setCacheRegion(cacheRegion); return this; } - + @Override public List list() throws HibernateException { return CriteriaImpl.this.list(); } - + @Override public ScrollableResults scroll() throws HibernateException { return CriteriaImpl.this.scroll(); } - + @Override public ScrollableResults scroll(ScrollMode scrollMode) throws HibernateException { return CriteriaImpl.this.scroll(scrollMode); } - + @Override public Object uniqueResult() throws HibernateException { return CriteriaImpl.this.uniqueResult(); } - + @Override public Criteria setFetchMode(String associationPath, FetchMode mode) { CriteriaImpl.this.setFetchMode( StringHelper.qualify(path, associationPath), mode); return this; } - + @Override public Criteria setFlushMode(FlushMode flushMode) { CriteriaImpl.this.setFlushMode(flushMode); return this; } - + @Override public Criteria setCacheMode(CacheMode cacheMode) { CriteriaImpl.this.setCacheMode(cacheMode); return this; } - + @Override public Criteria setFirstResult(int firstResult) { CriteriaImpl.this.setFirstResult(firstResult); return this; } - + @Override public Criteria setMaxResults(int maxResults) { CriteriaImpl.this.setMaxResults(maxResults); return this; } - + @Override public Criteria setTimeout(int timeout) { CriteriaImpl.this.setTimeout(timeout); return this; } - + @Override public Criteria setFetchSize(int fetchSize) { CriteriaImpl.this.setFetchSize(fetchSize); return this; } - + @Override public Criteria setLockMode(String alias, LockMode lockMode) { CriteriaImpl.this.setLockMode(alias, lockMode); return this; } - + @Override public Criteria setResultTransformer(ResultTransformer resultProcessor) { CriteriaImpl.this.setResultTransformer(resultProcessor); return this; } - + @Override public Criteria setComment(String comment) { CriteriaImpl.this.setComment(comment); return this; } - + @Override public Criteria setProjection(Projection projection) { CriteriaImpl.this.projection = projection; CriteriaImpl.this.projectionCriteria = this; @@ -699,7 +692,7 @@ public class CriteriaImpl implements Criteria, Serializable { public Criteria getCriteria() { return criteria; } - + @Override public String toString() { return criterion.toString(); } @@ -721,7 +714,7 @@ public class CriteriaImpl implements Criteria, Serializable { public Criteria getCriteria() { return criteria; } - + @Override public String toString() { return order.toString(); } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/criteria/ComponentCollectionCriteriaInfoProvider.java b/hibernate-core/src/main/java/org/hibernate/loader/criteria/ComponentCollectionCriteriaInfoProvider.java index 2f86b55431..48de159769 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/criteria/ComponentCollectionCriteriaInfoProvider.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/criteria/ComponentCollectionCriteriaInfoProvider.java @@ -38,47 +38,50 @@ import org.hibernate.type.Type; */ class ComponentCollectionCriteriaInfoProvider implements CriteriaInfoProvider { - QueryableCollection persister; - Map /* */ subTypes = new HashMap /* */(); + private final QueryableCollection persister; + private final Map subTypes = new HashMap(); + + ComponentCollectionCriteriaInfoProvider(QueryableCollection persister) { + this.persister = persister; + if ( !persister.getElementType().isComponentType() ) { + throw new IllegalArgumentException( "persister for role " + persister.getRole() + " is not a collection-of-component" ); + } + + ComponentType componentType = (ComponentType) persister.getElementType(); + String[] names = componentType.getPropertyNames(); + Type[] types = componentType.getSubtypes(); + + for ( int i = 0; i < names.length; i++ ) { + subTypes.put( names[i], types[i] ); + } - ComponentCollectionCriteriaInfoProvider(QueryableCollection persister) { - this.persister = persister; - if (!persister.getElementType().isComponentType()) { - throw new IllegalArgumentException("persister for role "+persister.getRole()+" is not a collection-of-component"); } - ComponentType componentType = (ComponentType)persister.getElementType(); - String[] names = componentType.getPropertyNames(); - Type[] types = componentType.getSubtypes(); - - for (int i = 0; i < names.length; i++) { - subTypes.put(names[i], types[i]); + @Override + public String getName() { + return persister.getRole(); } - } + @Override + public Serializable[] getSpaces() { + return persister.getCollectionSpaces(); + } - public String getName() { - return persister.getRole(); - } + @Override + public PropertyMapping getPropertyMapping() { + return persister; + } - public Serializable[] getSpaces() { - return persister.getCollectionSpaces(); - } - - public PropertyMapping getPropertyMapping() { - return persister; - } - - public Type getType(String relativePath) { - // TODO: can a component have a nested component? then we may need to do something more here... - if (relativePath.indexOf('.') >= 0) - throw new IllegalArgumentException("dotted paths not handled (yet?!) for collection-of-component"); - - Type type = (Type)subTypes.get(relativePath); - - if (type == null) - throw new IllegalArgumentException("property "+relativePath+" not found in component of collection "+getName()); - - return type; - } + @Override + public Type getType(String relativePath) { + // TODO: can a component have a nested component? then we may need to do something more here... + if ( relativePath.indexOf( '.' ) >= 0 ) { + throw new IllegalArgumentException( "dotted paths not handled (yet?!) for collection-of-component" ); + } + Type type = subTypes.get( relativePath ); + if ( type == null ) { + throw new IllegalArgumentException( "property " + relativePath + " not found in component of collection " + getName() ); + } + return type; + } } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaJoinWalker.java b/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaJoinWalker.java index 1b009ce860..871cd3e122 100755 --- a/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaJoinWalker.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaJoinWalker.java @@ -66,9 +66,9 @@ public class CriteriaJoinWalker extends AbstractEntityJoinWalker { //the user visible aliases, which are unknown to the superclass, //these are not the actual "physical" SQL aliases private final String[] userAliases; - private final List userAliasList = new ArrayList(); - private final List resultTypeList = new ArrayList(); - private final List includeInResultRowList = new ArrayList(); + private final List userAliasList = new ArrayList(); + private final List resultTypeList = new ArrayList(); + private final List includeInResultRowList = new ArrayList(); public Type[] getResultTypes() { return resultTypes; @@ -130,7 +130,7 @@ public class CriteriaJoinWalker extends AbstractEntityJoinWalker { includeInResultRow = ArrayHelper.toBooleanArray( includeInResultRowList ); } } - + @Override protected JoinType getJoinType( OuterJoinLoadable persister, final PropertyPath path, @@ -207,7 +207,7 @@ public class CriteriaJoinWalker extends AbstractEntityJoinWalker { } return resolvedJoinType; } - + @Override protected JoinType getJoinType( AssociationType associationType, FetchMode config, @@ -239,11 +239,12 @@ public class CriteriaJoinWalker extends AbstractEntityJoinWalker { * Use the discriminator, to narrow the select to instances * of the queried subclass, also applying any filters. */ + @Override protected String getWhereFragment() throws MappingException { return super.getWhereFragment() + ( (Queryable) getPersister() ).filterFragment( getAlias(), getLoadQueryInfluencers().getEnabledFilters() ); } - + @Override protected String generateTableAlias(int n, PropertyPath path, Joinable joinable) { // TODO: deal with side-effects (changes to includeInResultRowList, userAliasList, resultTypeList)!!! @@ -288,7 +289,7 @@ public class CriteriaJoinWalker extends AbstractEntityJoinWalker { return sqlAlias; } - + @Override protected String generateRootAlias(String tableName) { return CriteriaQueryTranslator.ROOT_SQL_ALIAS; } @@ -296,15 +297,15 @@ public class CriteriaJoinWalker extends AbstractEntityJoinWalker { public Set getQuerySpaces() { return querySpaces; } - + @Override public String getComment() { return "criteria query"; } - + @Override protected String getWithClause(PropertyPath path) { return translator.getWithClause( path.getFullPath() ); } - + @Override protected boolean hasRestriction(PropertyPath path) { return translator.hasRestriction( path.getFullPath() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaLoader.java index 0b7093bc0e..d973d9c9ae 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaLoader.java @@ -125,23 +125,23 @@ public class CriteriaLoader extends OuterJoinLoader { return list( session, translator.getQueryParameters(), querySpaces, resultTypes ); } - + @Override protected String[] getResultRowAliases() { return userAliases; } - + @Override protected ResultTransformer resolveResultTransformer(ResultTransformer resultTransformer) { return translator.getRootCriteria().getResultTransformer(); } - + @Override protected boolean areResultSetRowsTransformedImmediately() { return true; } - + @Override protected boolean[] includeInResultRow() { return includeInResultRow; } - + @Override protected Object getResultColumnOrRow(Object[] row, ResultTransformer transformer, ResultSet rs, SessionImplementor session) throws SQLException, HibernateException { return resolveResultTransformer( transformer ).transformTuple( @@ -149,7 +149,7 @@ public class CriteriaLoader extends OuterJoinLoader { getResultRowAliases() ); } - + @Override protected Object[] getResultRow(Object[] row, ResultSet rs, SessionImplementor session) throws SQLException, HibernateException { final Object[] result; @@ -249,7 +249,7 @@ public class CriteriaLoader extends OuterJoinLoader { } - + @Override protected LockMode determineFollowOnLockMode(LockOptions lockOptions) { final LockMode lockModeToUse = lockOptions.findGreatestLockMode(); @@ -260,7 +260,7 @@ public class CriteriaLoader extends OuterJoinLoader { return lockModeToUse; } - + @Override protected LockMode[] getLockModes(LockOptions lockOptions) { final String[] entityAliases = getAliases(); if ( entityAliases == null ) { @@ -274,15 +274,15 @@ public class CriteriaLoader extends OuterJoinLoader { } return lockModesArray; } - + @Override protected boolean isSubselectLoadingEnabled() { return hasSubselectLoadableCollections(); } - + @Override protected List getResultList(List results, ResultTransformer resultTransformer) { return resolveResultTransformer( resultTransformer ).transformList( results ); } - + @Override protected String getQueryIdentifier() { return "[CRITERIA] " + getSQLString(); } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaQueryTranslator.java b/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaQueryTranslator.java index 2f0ede7069..30a8047368 100755 --- a/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaQueryTranslator.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaQueryTranslator.java @@ -23,6 +23,7 @@ * */ package org.hibernate.loader.criteria; +import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -74,15 +75,14 @@ public class CriteriaQueryTranslator implements CriteriaQuery { private final CriteriaImpl rootCriteria; private final String rootEntityName; private final String rootSQLAlias; - private int aliasCount = 0; - private final Map /* */ criteriaInfoMap = new LinkedHashMap(); - private final Map /* */ nameCriteriaInfoMap = new LinkedHashMap(); - private final Map criteriaSQLAliasMap = new HashMap(); - private final Map aliasCriteriaMap = new HashMap(); - private final Map associationPathCriteriaMap = new LinkedHashMap(); - private final Map associationPathJoinTypesMap = new LinkedHashMap(); - private final Map withClauseMap = new HashMap(); + private final Map criteriaInfoMap = new LinkedHashMap(); + private final Map nameCriteriaInfoMap = new LinkedHashMap(); + private final Map criteriaSQLAliasMap = new HashMap(); + private final Map aliasCriteriaMap = new HashMap(); + private final Map associationPathCriteriaMap = new LinkedHashMap(); + private final Map associationPathJoinTypesMap = new LinkedHashMap(); + private final Map withClauseMap = new HashMap(); private final SessionFactoryImplementor sessionFactory; private final SessionFactoryHelper helper; @@ -112,8 +112,9 @@ public class CriteriaQueryTranslator implements CriteriaQuery { createCriteriaEntityNameMap(); createCriteriaSQLAliasMap(); } - + @Override public String generateSQLAlias() { + int aliasCount = 0; return StringHelper.generateAlias( Criteria.ROOT_ALIAS, aliasCount ) + '_'; } @@ -122,7 +123,7 @@ public class CriteriaQueryTranslator implements CriteriaQuery { } private Criteria getAliasedCriteria(String alias) { - return ( Criteria ) aliasCriteriaMap.get( alias ); + return aliasCriteriaMap.get( alias ); } public boolean isJoin(String path) { @@ -135,14 +136,12 @@ public class CriteriaQueryTranslator implements CriteriaQuery { } public Criteria getCriteria(String path) { - return ( Criteria ) associationPathCriteriaMap.get( path ); + return associationPathCriteriaMap.get( path ); } - public Set getQuerySpaces() { - Set result = new HashSet(); - Iterator iter = criteriaInfoMap.values().iterator(); - while ( iter.hasNext() ) { - CriteriaInfoProvider info = ( CriteriaInfoProvider )iter.next(); + public Set getQuerySpaces() { + Set result = new HashSet(); + for ( CriteriaInfoProvider info : criteriaInfoMap.values() ) { result.addAll( Arrays.asList( info.getSpaces() ) ); } return result; @@ -150,9 +149,9 @@ public class CriteriaQueryTranslator implements CriteriaQuery { private void createAliasCriteriaMap() { aliasCriteriaMap.put( rootCriteria.getAlias(), rootCriteria ); - Iterator iter = rootCriteria.iterateSubcriteria(); + Iterator iter = rootCriteria.iterateSubcriteria(); while ( iter.hasNext() ) { - Criteria subcriteria = ( Criteria ) iter.next(); + Criteria subcriteria = iter.next(); if ( subcriteria.getAlias() != null ) { Object old = aliasCriteriaMap.put( subcriteria.getAlias(), subcriteria ); if ( old != null ) { @@ -163,9 +162,9 @@ public class CriteriaQueryTranslator implements CriteriaQuery { } private void createAssociationPathCriteriaMap() { - Iterator iter = rootCriteria.iterateSubcriteria(); + final Iterator iter = rootCriteria.iterateSubcriteria(); while ( iter.hasNext() ) { - CriteriaImpl.Subcriteria crit = ( CriteriaImpl.Subcriteria ) iter.next(); + CriteriaImpl.Subcriteria crit = iter.next(); String wholeAssociationPath = getWholeAssociationPath( crit ); Object old = associationPathCriteriaMap.put( wholeAssociationPath, crit ); if ( old != null ) { @@ -197,7 +196,7 @@ public class CriteriaQueryTranslator implements CriteriaQuery { // and the qualifier is not the alias of this criteria // -> check to see if we belong to some criteria other // than the one that created us - parent = ( Criteria ) aliasCriteriaMap.get( testAlias ); + parent = aliasCriteriaMap.get( testAlias ); } } if ( parent == null ) { @@ -224,16 +223,10 @@ public class CriteriaQueryTranslator implements CriteriaQuery { criteriaInfoMap.put( rootCriteria, rootProvider); nameCriteriaInfoMap.put ( rootProvider.getName(), rootProvider ); - Iterator iter = associationPathCriteriaMap.entrySet().iterator(); - while ( iter.hasNext() ) { - Map.Entry me = ( Map.Entry ) iter.next(); - CriteriaInfoProvider info = getPathInfo((String)me.getKey()); - - criteriaInfoMap.put( - me.getValue(), //the criteria instance - info - ); - + for(final String key : associationPathCriteriaMap.keySet() ){ + Criteria value = associationPathCriteriaMap.get( key ); + CriteriaInfoProvider info = getPathInfo( key ); + criteriaInfoMap.put( value, info ); nameCriteriaInfoMap.put( info.getName(), info ); } } @@ -244,7 +237,7 @@ public class CriteriaQueryTranslator implements CriteriaQuery { String componentPath = ""; // start with the 'rootProvider' - CriteriaInfoProvider provider = ( CriteriaInfoProvider )nameCriteriaInfoMap.get( rootEntityName ); + CriteriaInfoProvider provider = nameCriteriaInfoMap.get( rootEntityName ); while ( tokens.hasMoreTokens() ) { componentPath += tokens.nextToken(); @@ -290,16 +283,15 @@ public class CriteriaQueryTranslator implements CriteriaQuery { private void createCriteriaSQLAliasMap() { int i = 0; - Iterator criteriaIterator = criteriaInfoMap.entrySet().iterator(); - while ( criteriaIterator.hasNext() ) { - Map.Entry me = ( Map.Entry ) criteriaIterator.next(); - Criteria crit = ( Criteria ) me.getKey(); + for(final Criteria crit : criteriaInfoMap.keySet()){ + CriteriaInfoProvider value = criteriaInfoMap.get( crit ); String alias = crit.getAlias(); if ( alias == null ) { - alias = (( CriteriaInfoProvider ) me.getValue()).getName(); // the entity name + alias = value.getName(); // the entity name } criteriaSQLAliasMap.put( crit, StringHelper.generateAlias( alias, i++ ) ); } + criteriaSQLAliasMap.put( rootCriteria, rootSQLAlias ); } @@ -314,18 +306,16 @@ public class CriteriaQueryTranslator implements CriteriaQuery { selection.setMaxRows( rootCriteria.getMaxResults() ); selection.setTimeout( rootCriteria.getTimeout() ); selection.setFetchSize( rootCriteria.getFetchSize() ); - - Iterator iter = rootCriteria.getLockModes().entrySet().iterator(); - while ( iter.hasNext() ) { - Map.Entry me = ( Map.Entry ) iter.next(); - final Criteria subcriteria = getAliasedCriteria( ( String ) me.getKey() ); - lockOptions.setAliasSpecificLockMode( getSQLAlias( subcriteria ), (LockMode)me.getValue() ); + final Map lockModeMap = rootCriteria.getLockModes(); + for ( final String key : lockModeMap.keySet() ) { + final Criteria subcriteria = getAliasedCriteria( key ); + lockOptions.setAliasSpecificLockMode( getSQLAlias( subcriteria ), lockModeMap.get( key ) ); } - List values = new ArrayList(); - List types = new ArrayList(); - iter = rootCriteria.iterateSubcriteria(); - while ( iter.hasNext() ) { - CriteriaImpl.Subcriteria subcriteria = ( CriteriaImpl.Subcriteria ) iter.next(); + final List values = new ArrayList(); + final List types = new ArrayList(); + final Iterator subcriteriaIterator = rootCriteria.iterateSubcriteria(); + while ( subcriteriaIterator.hasNext() ) { + CriteriaImpl.Subcriteria subcriteria = subcriteriaIterator.next(); LockMode lm = subcriteria.getLockMode(); if ( lm != null ) { lockOptions.setAliasSpecificLockMode( getSQLAlias( subcriteria ), lm ); @@ -333,9 +323,9 @@ public class CriteriaQueryTranslator implements CriteriaQuery { if ( subcriteria.getWithClause() != null ) { TypedValue[] tv = subcriteria.getWithClause().getTypedValues( subcriteria, this ); - for ( int i = 0; i < tv.length; i++ ) { - values.add( tv[i].getValue() ); - types.add( tv[i].getType() ); + for ( TypedValue aTv : tv ) { + values.add( aTv.getValue() ); + types.add( aTv.getType() ); } } } @@ -343,13 +333,13 @@ public class CriteriaQueryTranslator implements CriteriaQuery { // Type and value gathering for the WHERE clause needs to come AFTER lock mode gathering, // because the lock mode gathering loop now contains join clauses which can contain // parameter bindings (as in the HQL WITH clause). - iter = rootCriteria.iterateExpressionEntries(); + Iterator iter = rootCriteria.iterateExpressionEntries(); while ( iter.hasNext() ) { - CriteriaImpl.CriterionEntry ce = ( CriteriaImpl.CriterionEntry ) iter.next(); + CriteriaImpl.CriterionEntry ce = iter.next(); TypedValue[] tv = ce.getCriterion().getTypedValues( ce.getCriteria(), this ); - for ( int i = 0; i < tv.length; i++ ) { - values.add( tv[i].getValue() ); - types.add( tv[i].getType() ); + for ( TypedValue aTv : tv ) { + values.add( aTv.getValue() ); + types.add( aTv.getType() ); } } @@ -361,7 +351,7 @@ public class CriteriaQueryTranslator implements CriteriaQuery { lockOptions, selection, rootCriteria.isReadOnlyInitialized(), - ( rootCriteria.isReadOnlyInitialized() ? rootCriteria.isReadOnly() : false ), + ( rootCriteria.isReadOnlyInitialized() && rootCriteria.isReadOnly() ), rootCriteria.getCacheable(), rootCriteria.getCacheRegion(), rootCriteria.getComment(), @@ -413,9 +403,9 @@ public class CriteriaQueryTranslator implements CriteriaQuery { public String getWhereCondition() { StringBuilder condition = new StringBuilder( 30 ); - Iterator criterionIterator = rootCriteria.iterateExpressionEntries(); + Iterator criterionIterator = rootCriteria.iterateExpressionEntries(); while ( criterionIterator.hasNext() ) { - CriteriaImpl.CriterionEntry entry = ( CriteriaImpl.CriterionEntry ) criterionIterator.next(); + CriteriaImpl.CriterionEntry entry = criterionIterator.next(); String sqlString = entry.getCriterion().toSqlString( entry.getCriteria(), this ); condition.append( sqlString ); if ( criterionIterator.hasNext() ) { @@ -427,9 +417,9 @@ public class CriteriaQueryTranslator implements CriteriaQuery { public String getOrderBy() { StringBuilder orderBy = new StringBuilder( 30 ); - Iterator criterionIterator = rootCriteria.iterateOrderings(); + Iterator criterionIterator = rootCriteria.iterateOrderings(); while ( criterionIterator.hasNext() ) { - CriteriaImpl.OrderEntry oe = ( CriteriaImpl.OrderEntry ) criterionIterator.next(); + CriteriaImpl.OrderEntry oe = criterionIterator.next(); orderBy.append( oe.getOrder().toSqlString( oe.getCriteria(), this ) ); if ( criterionIterator.hasNext() ) { orderBy.append( ", " ); @@ -437,20 +427,20 @@ public class CriteriaQueryTranslator implements CriteriaQuery { } return orderBy.toString(); } - + @Override public SessionFactoryImplementor getFactory() { return sessionFactory; } - + @Override public String getSQLAlias(Criteria criteria) { - return ( String ) criteriaSQLAliasMap.get( criteria ); + return criteriaSQLAliasMap.get( criteria ); } - + @Override public String getEntityName(Criteria criteria) { - final CriteriaInfoProvider infoProvider = ( CriteriaInfoProvider ) criteriaInfoMap.get( criteria ); + final CriteriaInfoProvider infoProvider = criteriaInfoMap.get( criteria ); return infoProvider != null ? infoProvider.getName() : null; } - + @Override public String getColumn(Criteria criteria, String propertyName) { String[] cols = getColumns( propertyName, criteria ); if ( cols.length != 1 ) { @@ -463,6 +453,7 @@ public class CriteriaQueryTranslator implements CriteriaQuery { * Get the names of the columns constrained * by this criterion. */ + @Override public String[] getColumnsUsingProjection( Criteria subcriteria, String propertyName) throws HibernateException { @@ -497,26 +488,22 @@ public class CriteriaQueryTranslator implements CriteriaQuery { return projectionColumns; } } - + @Override public String[] getIdentifierColumns(Criteria criteria) { String[] idcols = ( ( Loadable ) getPropertyMapping( getEntityName( criteria ) ) ).getIdentifierColumnNames(); return StringHelper.qualify( getSQLAlias( criteria ), idcols ); } - + @Override public Type getIdentifierType(Criteria criteria) { return ( ( Loadable ) getPropertyMapping( getEntityName( criteria ) ) ).getIdentifierType(); } - + @Override public TypedValue getTypedIdentifierValue(Criteria criteria, Object value) { final Loadable loadable = ( Loadable ) getPropertyMapping( getEntityName( criteria ) ); - return new TypedValue( - loadable.getIdentifierType(), - value, - EntityMode.POJO - ); + return new TypedValue( loadable.getIdentifierType(), value ); } - + @Override public String[] getColumns( String propertyName, Criteria subcriteria) throws HibernateException { @@ -532,6 +519,7 @@ public class CriteriaQueryTranslator implements CriteriaQuery { * property path is not found in subcriteria, try the "outer" query. * Projection aliases are ignored. */ + @Override public String[] findColumns(String propertyName, Criteria subcriteria ) throws HibernateException { try { @@ -547,7 +535,7 @@ public class CriteriaQueryTranslator implements CriteriaQuery { } } } - + @Override public Type getTypeUsingProjection(Criteria subcriteria, String propertyName) throws HibernateException { @@ -581,7 +569,7 @@ public class CriteriaQueryTranslator implements CriteriaQuery { return projectionTypes[0]; } } - + @Override public Type getType(Criteria subcriteria, String propertyName) throws HibernateException { return getPropertyMapping( getEntityName( subcriteria, propertyName ) ) @@ -591,6 +579,7 @@ public class CriteriaQueryTranslator implements CriteriaQuery { /** * Get the a typed value for the given property value. */ + @Override public TypedValue getTypedValue(Criteria subcriteria, String propertyName, Object value) throws HibernateException { // Detect discriminator values... @@ -625,7 +614,7 @@ public class CriteriaQueryTranslator implements CriteriaQuery { private PropertyMapping getPropertyMapping(String entityName) throws MappingException { - CriteriaInfoProvider info = ( CriteriaInfoProvider )nameCriteriaInfoMap.get(entityName); + CriteriaInfoProvider info = nameCriteriaInfoMap.get(entityName); if (info==null) { throw new HibernateException( "Unknown entity: " + entityName ); } @@ -633,7 +622,7 @@ public class CriteriaQueryTranslator implements CriteriaQuery { } //TODO: use these in methods above - + @Override public String getEntityName(Criteria subcriteria, String propertyName) { if ( propertyName.indexOf( '.' ) > 0 ) { String root = StringHelper.root( propertyName ); @@ -644,7 +633,7 @@ public class CriteriaQueryTranslator implements CriteriaQuery { } return getEntityName( subcriteria ); } - + @Override public String getSQLAlias(Criteria criteria, String propertyName) { if ( propertyName.indexOf( '.' ) > 0 ) { String root = StringHelper.root( propertyName ); @@ -655,7 +644,7 @@ public class CriteriaQueryTranslator implements CriteriaQuery { } return getSQLAlias( criteria ); } - + @Override public String getPropertyName(String propertyName) { if ( propertyName.indexOf( '.' ) > 0 ) { String root = StringHelper.root( propertyName ); @@ -669,14 +658,14 @@ public class CriteriaQueryTranslator implements CriteriaQuery { public String getWithClause(String path) { - final Criterion crit = (Criterion)this.withClauseMap.get(path); + final Criterion crit = withClauseMap.get(path); return crit == null ? null : crit.toSqlString(getCriteria(path), this); } public boolean hasRestriction(String path) { final CriteriaImpl.Subcriteria crit = ( CriteriaImpl.Subcriteria ) getCriteria( path ); - return crit == null ? false : crit.hasRestriction(); + return crit != null && crit.hasRestriction(); } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/criteria/EntityCriteriaInfoProvider.java b/hibernate-core/src/main/java/org/hibernate/loader/criteria/EntityCriteriaInfoProvider.java index 5eb354844a..67ea8a6d02 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/criteria/EntityCriteriaInfoProvider.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/criteria/EntityCriteriaInfoProvider.java @@ -35,25 +35,25 @@ import org.hibernate.type.Type; */ class EntityCriteriaInfoProvider implements CriteriaInfoProvider { - Queryable persister; + private final Queryable persister; - EntityCriteriaInfoProvider(Queryable persister) { - this.persister = persister; - } - - public String getName() { - return persister.getEntityName(); - } - - public Serializable[] getSpaces() { - return persister.getQuerySpaces(); - } - - public PropertyMapping getPropertyMapping() { - return persister; - } - - public Type getType(String relativePath) { - return persister.toType(relativePath); - } + EntityCriteriaInfoProvider(Queryable persister) { + this.persister = persister; + } + @Override + public String getName() { + return persister.getEntityName(); + } + @Override + public Serializable[] getSpaces() { + return persister.getQuerySpaces(); + } + @Override + public PropertyMapping getPropertyMapping() { + return persister; + } + @Override + public Type getType(String relativePath) { + return persister.toType( relativePath ); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/criteria/ScalarCollectionCriteriaInfoProvider.java b/hibernate-core/src/main/java/org/hibernate/loader/criteria/ScalarCollectionCriteriaInfoProvider.java index b132312b17..a20df71df2 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/criteria/ScalarCollectionCriteriaInfoProvider.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/criteria/ScalarCollectionCriteriaInfoProvider.java @@ -36,32 +36,36 @@ import org.hibernate.type.Type; */ class ScalarCollectionCriteriaInfoProvider implements CriteriaInfoProvider { - String role; - QueryableCollection persister; - SessionFactoryHelper helper; + private final String role; + private final QueryableCollection persister; + private final SessionFactoryHelper helper; - ScalarCollectionCriteriaInfoProvider(SessionFactoryHelper helper, String role) { - this.role = role; - this.helper = helper; - this.persister = helper.requireQueryableCollection(role); - } + ScalarCollectionCriteriaInfoProvider(SessionFactoryHelper helper, String role) { + this.role = role; + this.helper = helper; + this.persister = helper.requireQueryableCollection( role ); + } - public String getName() { - return role; - } + @Override + public String getName() { + return role; + } - public Serializable[] getSpaces() { - return persister.getCollectionSpaces(); - } + @Override + public Serializable[] getSpaces() { + return persister.getCollectionSpaces(); + } - public PropertyMapping getPropertyMapping() { - return helper.getCollectionPropertyMapping(role); - } + @Override + public PropertyMapping getPropertyMapping() { + return helper.getCollectionPropertyMapping( role ); + } - public Type getType(String relativePath) { - //not sure what things are going to be passed here, how about 'id', maybe 'index' or 'key' or 'elements' ??? - // todo: wtf! - return getPropertyMapping().toType(relativePath); - } + @Override + public Type getType(String relativePath) { + //not sure what things are going to be passed here, how about 'id', maybe 'index' or 'key' or 'elements' ??? + // todo: wtf! + return getPropertyMapping().toType( relativePath ); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/JoinType.java b/hibernate-core/src/main/java/org/hibernate/sql/JoinType.java index 1505a7eb38..1efcf41e79 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/JoinType.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/JoinType.java @@ -22,11 +22,11 @@ public enum JoinType { return joinTypeValue; } - public static JoinType parse(int joinType){ - if(joinType<0){ + public static JoinType parse(int joinType) { + if ( joinType < 0 ) { return NONE; } - switch ( joinType ){ + switch ( joinType ) { case 0: return INNER_JOIN; case 1: @@ -36,7 +36,7 @@ public enum JoinType { case 4: return FULL_JOIN; default: - throw new HibernateException( "unknown join type: "+joinType ); + throw new HibernateException( "unknown join type: " + joinType ); } } } From 2bc63badead578f90bcc269c9b56a25ab983f80b Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Tue, 7 May 2013 08:02:00 -0500 Subject: [PATCH 07/25] HHH-8220 - pom dependencies scope changed from compile to runtime --- build.gradle | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/build.gradle b/build.gradle index 72ab09a538..88203944a1 100644 --- a/build.gradle +++ b/build.gradle @@ -430,6 +430,16 @@ subprojects { subProject -> dev.appendNode( 'name', 'The Hibernate Development Team' ) dev.appendNode( 'organization', 'Hibernate.org' ) dev.appendNode( 'organizationUrl', 'http://hibernate.org' ) + + final String runtimeScope = 'runtime'; + final int replacementLength = runtimeScope.length(); + final String compileScope = 'compile'; + final StringBuilder stringBuilder = asString(); + int index = stringBuilder.indexOf( runtimeScope ); + while ( index > -1 ) { + stringBuilder.replace( index, index+replacementLength, compileScope ); + index = stringBuilder.indexOf( runtimeScope ); + } } } } From 51b9248c4bd91a6130825b50a30a41c11216a9fa Mon Sep 17 00:00:00 2001 From: Lukasz Antoniak Date: Mon, 15 Apr 2013 21:08:23 +0200 Subject: [PATCH 08/25] HHH-6875 - Fix and test --- .../cfg/annotations/CollectionBinder.java | 7 +- .../ordered/ElementCollectionSortingTest.java | 76 ++++++++++++++++++- .../collectionelement/ordered/Person.java | 2 +- 3 files changed, 78 insertions(+), 7 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java index cf3cdd2e4c..b087052506 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java @@ -1389,12 +1389,9 @@ public abstract class CollectionBinder { private String extractHqlOrderBy(javax.persistence.OrderBy jpaOrderBy) { if ( jpaOrderBy != null ) { - final String jpaOrderByFragment = jpaOrderBy.value(); - return StringHelper.isNotEmpty( jpaOrderByFragment ) - ? jpaOrderByFragment - : null; + return jpaOrderBy.value(); // Null not possible. In case of empty expression, apply default ordering. } - return null; + return null; // @OrderBy not found. } private static void checkFilterConditions(Collection collValue) { diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/ElementCollectionSortingTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/ElementCollectionSortingTest.java index ceed69dca6..08873fa06d 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/ElementCollectionSortingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/ElementCollectionSortingTest.java @@ -23,14 +23,21 @@ */ package org.hibernate.test.annotations.collectionelement.ordered; -import org.hibernate.Session; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.Assert; import org.junit.Test; +import org.hibernate.Session; +import org.hibernate.persister.collection.BasicCollectionPersister; +import org.hibernate.testing.TestForIssue; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; /** * @author Steve Ebersole + * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class ElementCollectionSortingTest extends BaseCoreFunctionalTestCase { @Override @@ -54,4 +61,71 @@ public class ElementCollectionSortingTest extends BaseCoreFunctionalTestCase { session.getTransaction().commit(); session.close(); } + + @Test + @TestForIssue( jiraKey = "HHH-6875" ) + public void testSortingEmbeddableCollectionOfPrimitives() { + final Session session = openSession(); + session.beginTransaction(); + + final Person steve = new Person(); + steve.setName( "Steve" ); + steve.getNickNamesAscendingNaturalSort().add( "sebersole" ); + steve.getNickNamesAscendingNaturalSort().add( "ebersole" ); + steve.getNickNamesDescendingNaturalSort().add( "ebersole" ); + steve.getNickNamesDescendingNaturalSort().add( "sebersole" ); + + final Person lukasz = new Person(); + lukasz.setName( "Lukasz" ); + lukasz.getNickNamesAscendingNaturalSort().add( "antoniak" ); + lukasz.getNickNamesAscendingNaturalSort().add( "lantoniak" ); + lukasz.getNickNamesDescendingNaturalSort().add( "lantoniak" ); + lukasz.getNickNamesDescendingNaturalSort().add( "antoniak" ); + + session.save( steve ); + session.save( lukasz ); + session.flush(); + + session.clear(); + + final List lukaszNamesAsc = Arrays.asList( "antoniak", "lantoniak" ); + final List lukaszNamesDesc = Arrays.asList( "lantoniak", "antoniak" ); + final List steveNamesAsc = Arrays.asList( "ebersole", "sebersole" ); + final List steveNamesDesc = Arrays.asList( "sebersole", "ebersole" ); + + // Testing object graph navigation. Lazy loading collections. + checkPersonNickNames( lukaszNamesAsc, lukaszNamesDesc, (Person) session.get( Person.class, lukasz.getId() ) ); + checkPersonNickNames( steveNamesAsc, steveNamesDesc, (Person) session.get( Person.class, steve.getId() ) ); + + session.clear(); + + // Testing HQL query. Eagerly fetching nicknames. + final List result = session.createQuery( + "select distinct p from Person p join fetch p.nickNamesAscendingNaturalSort join fetch p.nickNamesDescendingNaturalSort order by p.name" + ).list(); + Assert.assertEquals( 2, result.size() ); + checkPersonNickNames( lukaszNamesAsc, lukaszNamesDesc, result.get( 0 ) ); + checkPersonNickNames( steveNamesAsc, steveNamesDesc, result.get( 1 ) ); + + // Metadata verification. + checkSQLOrderBy( session, Person.class.getName(), "nickNamesAscendingNaturalSort", "asc" ); + checkSQLOrderBy( session, Person.class.getName(), "nickNamesDescendingNaturalSort", "desc" ); + + session.getTransaction().rollback(); + session.close(); + } + + private void checkSQLOrderBy(Session session, String entityName, String propertyName, String order) { + String roleName = entityName + "." + propertyName; + String alias = "alias1"; + BasicCollectionPersister collectionPersister = (BasicCollectionPersister) session.getSessionFactory().getCollectionMetadata( roleName ); + Assert.assertTrue( collectionPersister.hasOrdering() ); + Assert.assertEquals( alias + "." + propertyName + " " + order, collectionPersister.getSQLOrderByString( alias ) ); + } + + private void checkPersonNickNames(List expectedAscending, List expectedDescending, Person person) { + // Comparing lists to verify ordering. + Assert.assertEquals( expectedAscending, new ArrayList( person.getNickNamesAscendingNaturalSort() ) ); + Assert.assertEquals( expectedDescending, new ArrayList( person.getNickNamesDescendingNaturalSort() ) ); + } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/Person.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/Person.java index 1894d9b96b..32176d73d9 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/Person.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/ordered/Person.java @@ -76,7 +76,7 @@ public class Person { @ElementCollection @JoinColumn @JoinTable(name = "T_NICKNAMES_A") - @OrderBy + @OrderBy // testing default @OrderBy mapping public Set getNickNamesAscendingNaturalSort() { return nickNamesAscendingNaturalSort; } From 9fc22a49be07b1699e6b70cbe0a38d83dd50682d Mon Sep 17 00:00:00 2001 From: Lukasz Antoniak Date: Thu, 18 Apr 2013 11:10:08 +0200 Subject: [PATCH 09/25] HHH-7214 - Validation of duplicated discriminator values --- .../entity/SingleTableEntityPersister.java | 26 ++++-- .../DuplicatedDiscriminatorValueTest.java | 91 +++++++++++++++++++ 2 files changed, 109 insertions(+), 8 deletions(-) create mode 100644 hibernate-core/src/test/java/org/hibernate/test/annotations/inheritance/singletable/DuplicatedDiscriminatorValueTest.java diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/SingleTableEntityPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/SingleTableEntityPersister.java index e66822ed56..d5f62787c6 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/SingleTableEntityPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/SingleTableEntityPersister.java @@ -410,7 +410,7 @@ public class SingleTableEntityPersister extends AbstractEntityPersister { subclassClosure = new String[subclassSpan]; subclassClosure[0] = getEntityName(); if ( persistentClass.isPolymorphic() ) { - subclassesByDiscriminatorValue.put( discriminatorValue, getEntityName() ); + addSubclassByDiscriminatorValue( discriminatorValue, getEntityName() ); } // SUBCLASSES @@ -421,15 +421,15 @@ public class SingleTableEntityPersister extends AbstractEntityPersister { Subclass sc = (Subclass) iter.next(); subclassClosure[k++] = sc.getEntityName(); if ( sc.isDiscriminatorValueNull() ) { - subclassesByDiscriminatorValue.put( NULL_DISCRIMINATOR, sc.getEntityName() ); + addSubclassByDiscriminatorValue( NULL_DISCRIMINATOR, sc.getEntityName() ); } else if ( sc.isDiscriminatorValueNotNull() ) { - subclassesByDiscriminatorValue.put( NOT_NULL_DISCRIMINATOR, sc.getEntityName() ); + addSubclassByDiscriminatorValue( NOT_NULL_DISCRIMINATOR, sc.getEntityName() ); } else { try { DiscriminatorType dtype = (DiscriminatorType) discriminatorType; - subclassesByDiscriminatorValue.put( + addSubclassByDiscriminatorValue( dtype.stringToObject( sc.getDiscriminatorValue() ), sc.getEntityName() ); @@ -452,6 +452,16 @@ public class SingleTableEntityPersister extends AbstractEntityPersister { } + private void addSubclassByDiscriminatorValue(Object discriminatorValue, String entityName) { + String mappedEntityName = (String) subclassesByDiscriminatorValue.put( discriminatorValue, entityName ); + if ( mappedEntityName != null ) { + throw new MappingException( + "Entities [" + entityName + "] and [" + mappedEntityName + + "] are mapped with the same discriminator value '" + discriminatorValue + "'." + ); + } + } + public SingleTableEntityPersister( final EntityBinding entityBinding, final EntityRegionAccessStrategy cacheAccessStrategy, @@ -674,7 +684,7 @@ public class SingleTableEntityPersister extends AbstractEntityPersister { subclassClosure = new String[subclassSpan]; subclassClosure[0] = getEntityName(); if ( entityBinding.isPolymorphic() ) { - subclassesByDiscriminatorValue.put( discriminatorValue, getEntityName() ); + addSubclassByDiscriminatorValue( discriminatorValue, getEntityName() ); } // SUBCLASSES @@ -683,15 +693,15 @@ public class SingleTableEntityPersister extends AbstractEntityPersister { for ( EntityBinding subEntityBinding : entityBinding.getPostOrderSubEntityBindingClosure() ) { subclassClosure[k++] = subEntityBinding.getEntity().getName(); if ( subEntityBinding.isDiscriminatorMatchValueNull() ) { - subclassesByDiscriminatorValue.put( NULL_DISCRIMINATOR, subEntityBinding.getEntity().getName() ); + addSubclassByDiscriminatorValue( NULL_DISCRIMINATOR, subEntityBinding.getEntity().getName() ); } else if ( subEntityBinding.isDiscriminatorMatchValueNotNull() ) { - subclassesByDiscriminatorValue.put( NOT_NULL_DISCRIMINATOR, subEntityBinding.getEntity().getName() ); + addSubclassByDiscriminatorValue( NOT_NULL_DISCRIMINATOR, subEntityBinding.getEntity().getName() ); } else { try { DiscriminatorType dtype = (DiscriminatorType) discriminatorType; - subclassesByDiscriminatorValue.put( + addSubclassByDiscriminatorValue( dtype.stringToObject( subEntityBinding.getDiscriminatorMatchValue() ), subEntityBinding.getEntity().getName() ); diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/inheritance/singletable/DuplicatedDiscriminatorValueTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/inheritance/singletable/DuplicatedDiscriminatorValueTest.java new file mode 100644 index 0000000000..fc68f75034 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/inheritance/singletable/DuplicatedDiscriminatorValueTest.java @@ -0,0 +1,91 @@ +package org.hibernate.test.annotations.inheritance.singletable; + +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +import org.junit.Assert; +import org.junit.Test; + +import org.hibernate.MappingException; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; +import org.hibernate.service.ServiceRegistry; +import org.hibernate.testing.ServiceRegistryBuilder; +import org.hibernate.testing.TestForIssue; +import org.hibernate.testing.junit4.BaseUnitTestCase; + +/** + * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) + */ +@TestForIssue( jiraKey = "HHH-7214" ) +public class DuplicatedDiscriminatorValueTest extends BaseUnitTestCase { + private static final String DISCRIMINATOR_VALUE = "D"; + + @Test + public void testDuplicatedDiscriminatorValueSameHierarchy() { + try { + tryBuildingSessionFactory( Building.class, Building1.class, Building2.class ); + Assert.fail( MappingException.class.getName() + " expected when two subclasses are mapped with the same discriminator value." ); + } + catch ( MappingException e ) { + final String errorMsg = e.getCause().getMessage(); + // Check if error message contains descriptive information. + Assert.assertTrue( errorMsg.contains( Building1.class.getName() ) ); + Assert.assertTrue( errorMsg.contains( Building2.class.getName() ) ); + Assert.assertTrue( errorMsg.contains( "discriminator value '" + DISCRIMINATOR_VALUE + "'." ) ); + } + } + + @Test + public void testDuplicatedDiscriminatorValueDifferentHierarchy() { + tryBuildingSessionFactory( Building.class, Building1.class, Furniture.class, Chair.class ); + } + + private void tryBuildingSessionFactory(Class... annotatedClasses) { + Configuration cfg = new Configuration(); + for ( Class annotatedClass : annotatedClasses ) { + cfg.addAnnotatedClass( annotatedClass ); + } + ServiceRegistry serviceRegistry = null; + SessionFactory sessionFactory = null; + try { + serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( cfg.getProperties() ); + sessionFactory = cfg.buildSessionFactory( serviceRegistry ); + } + finally { + if ( sessionFactory != null ) { + sessionFactory.close(); + } + if ( serviceRegistry != null ) { + ServiceRegistryBuilder.destroy( serviceRegistry ); + } + } + } + + @Entity + @DiscriminatorValue(DISCRIMINATOR_VALUE) // Duplicated discriminator value in single hierarchy. + private static class Building1 extends Building { + } + + @Entity + @DiscriminatorValue(DISCRIMINATOR_VALUE) // Duplicated discriminator value in single hierarchy. + private static class Building2 extends Building { + } + + @Entity + @DiscriminatorColumn(name = "entity_type") + @DiscriminatorValue("F") + private static class Furniture { + @Id + @GeneratedValue + private Integer id; + } + + @Entity + @DiscriminatorValue(DISCRIMINATOR_VALUE) // Duplicated discriminator value in different hierarchy. + private static class Chair extends Furniture { + } +} From 9030fa015edfd7a3937cf186f8dd68519a7b2c32 Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Fri, 3 May 2013 17:24:44 -0400 Subject: [PATCH 10/25] HHH-8217 Make generated constraint names short and non-random --- .../org/hibernate/cfg/AnnotationBinder.java | 17 +- .../java/org/hibernate/cfg/Configuration.java | 21 +- .../java/org/hibernate/cfg/HbmBinder.java | 4 +- .../hibernate/internal/util/StringHelper.java | 15 -- .../org/hibernate/mapping/Constraint.java | 94 ++++++++- .../org/hibernate/mapping/ForeignKey.java | 4 + .../org/hibernate/mapping/PrimaryKey.java | 4 + .../java/org/hibernate/mapping/Table.java | 41 ++-- .../java/org/hibernate/mapping/UniqueKey.java | 4 + .../SynonymValidationTest.java | 187 ++++++++++++++++++ 10 files changed, 330 insertions(+), 61 deletions(-) create mode 100644 hibernate-core/src/test/java/org/hibernate/test/schemavalidation/SynonymValidationTest.java diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java index ba368b43c2..0414122b4f 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java @@ -35,6 +35,7 @@ import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; + import javax.persistence.Basic; import javax.persistence.Cacheable; import javax.persistence.CollectionTable; @@ -81,8 +82,6 @@ import javax.persistence.TableGenerator; import javax.persistence.UniqueConstraint; import javax.persistence.Version; -import org.jboss.logging.Logger; - import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; import org.hibernate.EntityMode; @@ -151,7 +150,6 @@ import org.hibernate.cfg.annotations.QueryBinder; import org.hibernate.cfg.annotations.SimpleValueBinder; import org.hibernate.cfg.annotations.TableBinder; import org.hibernate.engine.OptimisticLockStyle; -import org.hibernate.engine.internal.Versioning; import org.hibernate.engine.spi.FilterDefinition; import org.hibernate.id.MultipleHiLoPerTableGenerator; import org.hibernate.id.PersistentIdentifierGenerator; @@ -159,9 +157,9 @@ import org.hibernate.id.SequenceHiLoGenerator; import org.hibernate.id.TableHiLoGenerator; import org.hibernate.id.enhanced.SequenceStyleGenerator; import org.hibernate.internal.CoreMessageLogger; -import org.hibernate.internal.util.StringHelper; import org.hibernate.mapping.Any; import org.hibernate.mapping.Component; +import org.hibernate.mapping.Constraint; import org.hibernate.mapping.DependantValue; import org.hibernate.mapping.IdGenerator; import org.hibernate.mapping.Join; @@ -175,6 +173,7 @@ import org.hibernate.mapping.SingleTableSubclass; import org.hibernate.mapping.Subclass; import org.hibernate.mapping.ToOne; import org.hibernate.mapping.UnionSubclass; +import org.jboss.logging.Logger; /** * JSR 175 annotation binder which reads the annotations from classes, applies the @@ -2104,16 +2103,22 @@ public final class AnnotationBinder { } } + // Natural ID columns must reside in one single UniqueKey within the Table. + // For now, simply ensure consistent naming. + // TODO: AFAIK, there really isn't a reason for these UKs to be created + // on the secondPass. This whole area should go away... NaturalId naturalIdAnn = property.getAnnotation( NaturalId.class ); if ( naturalIdAnn != null ) { if ( joinColumns != null ) { for ( Ejb3Column column : joinColumns ) { - column.addUniqueKey( column.getTable().getNaturalIdUniqueKeyName(), inSecondPass ); + String keyName = "UK_" + Constraint.hashedName( column.getTable().getName() + "_NaturalID" ); + column.addUniqueKey( keyName, inSecondPass ); } } else { for ( Ejb3Column column : columns ) { - column.addUniqueKey( column.getTable().getNaturalIdUniqueKeyName(), inSecondPass ); + String keyName = "UK_" + Constraint.hashedName( column.getTable().getName() + "_NaturalID" ); + column.addUniqueKey( keyName, inSecondPass ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java index 5f770cb4f0..cc6139a56a 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java @@ -119,6 +119,7 @@ import org.hibernate.internal.util.xml.XmlDocumentImpl; import org.hibernate.mapping.AuxiliaryDatabaseObject; import org.hibernate.mapping.Collection; import org.hibernate.mapping.Column; +import org.hibernate.mapping.Constraint; import org.hibernate.mapping.DenormalizedTable; import org.hibernate.mapping.FetchProfile; import org.hibernate.mapping.ForeignKey; @@ -1398,22 +1399,14 @@ public class Configuration implements Serializable { final Table table = tableListEntry.getKey(); final List uniqueConstraints = tableListEntry.getValue(); for ( UniqueConstraintHolder holder : uniqueConstraints ) { - final String keyName = StringHelper.isEmpty( holder.getName() ) - ? StringHelper.randomFixedLengthHex("UK_") - : holder.getName(); - buildUniqueKeyFromColumnNames( table, keyName, holder.getColumns() ); + buildUniqueKeyFromColumnNames( table, holder.getName(), holder.getColumns() ); } } for(Table table : jpaIndexHoldersByTable.keySet()){ final List jpaIndexHolders = jpaIndexHoldersByTable.get( table ); - int uniqueIndexPerTable = 0; for ( JPAIndexHolder holder : jpaIndexHolders ) { - uniqueIndexPerTable++; - final String keyName = StringHelper.isEmpty( holder.getName() ) - ? "idx_"+table.getName()+"_" + uniqueIndexPerTable - : holder.getName(); - buildUniqueKeyFromColumnNames( table, keyName, holder.getColumns(), holder.getOrdering(), holder.isUnique() ); + buildUniqueKeyFromColumnNames( table, holder.getName(), holder.getColumns(), holder.getOrdering(), holder.isUnique() ); } } @@ -1576,8 +1569,6 @@ public class Configuration implements Serializable { } private void buildUniqueKeyFromColumnNames(Table table, String keyName, String[] columnNames, String[] orderings, boolean unique) { - keyName = normalizer.normalizeIdentifierQuoting( keyName ); - int size = columnNames.length; Column[] columns = new Column[size]; Set unbound = new HashSet(); @@ -1594,6 +1585,12 @@ public class Configuration implements Serializable { unboundNoLogical.add( new Column( column ) ); } } + + if ( StringHelper.isEmpty( keyName ) ) { + keyName = Constraint.generateName( "UK_", table, columns ); + } + keyName = normalizer.normalizeIdentifierQuoting( keyName ); + if ( unique ) { UniqueKey uk = table.getOrCreateUniqueKey( keyName ); for ( int i = 0; i < columns.length; i++ ) { diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java index f3ac7b91eb..c721a072e7 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java @@ -59,6 +59,7 @@ import org.hibernate.mapping.Bag; import org.hibernate.mapping.Collection; import org.hibernate.mapping.Column; import org.hibernate.mapping.Component; +import org.hibernate.mapping.Constraint; import org.hibernate.mapping.DependantValue; import org.hibernate.mapping.FetchProfile; import org.hibernate.mapping.Fetchable; @@ -2246,7 +2247,6 @@ public final class HbmBinder { } else if ( "natural-id".equals( name ) ) { UniqueKey uk = new UniqueKey(); - uk.setName(StringHelper.randomFixedLengthHex("UK_")); uk.setTable(table); //by default, natural-ids are "immutable" (constant) boolean mutableId = "true".equals( subnode.attributeValue("mutable") ); @@ -2260,6 +2260,8 @@ public final class HbmBinder { false, true ); + uk.setName( Constraint.generateName( uk.generatedConstraintNamePrefix(), + table, uk.getColumns() ) ); table.addUniqueKey(uk); } else if ( "query".equals(name) ) { diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/StringHelper.java b/hibernate-core/src/main/java/org/hibernate/internal/util/StringHelper.java index 0e4ff5ab48..bf5107a635 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/util/StringHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/StringHelper.java @@ -30,7 +30,6 @@ import java.util.Arrays; import java.util.BitSet; import java.util.Iterator; import java.util.StringTokenizer; -import java.util.UUID; import org.hibernate.dialect.Dialect; import org.hibernate.internal.util.collections.ArrayHelper; @@ -758,18 +757,4 @@ public final class StringHelper { public static String[] toArrayElement(String s) { return ( s == null || s.length() == 0 ) ? new String[0] : new String[] { s }; } - - // Oracle restricts identifier lengths to 30. Rather than tie this to - // Dialect, simply restrict randomly-generated constrain names across - // the board. - private static final int MAX_NAME_LENGTH = 30; - public static String randomFixedLengthHex(String prefix) { - int length = MAX_NAME_LENGTH - prefix.length(); - String s = UUID.randomUUID().toString(); - s = s.replace( "-", "" ); - if (s.length() > length) { - s = s.substring( 0, length ); - } - return prefix + s; - } } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Constraint.java b/hibernate-core/src/main/java/org/hibernate/mapping/Constraint.java index be846eaf46..e11fbdd9dd 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Constraint.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Constraint.java @@ -23,10 +23,16 @@ */ package org.hibernate.mapping; import java.io.Serializable; +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; import java.util.Iterator; import java.util.List; +import org.hibernate.HibernateException; import org.hibernate.dialect.Dialect; import org.hibernate.engine.spi.Mapping; @@ -34,11 +40,12 @@ import org.hibernate.engine.spi.Mapping; * A relational constraint. * * @author Gavin King + * @author Brett Meyer */ public abstract class Constraint implements RelationalModel, Serializable { private String name; - private final List columns = new ArrayList(); + private final ArrayList columns = new ArrayList(); private Table table; public String getName() { @@ -48,6 +55,85 @@ public abstract class Constraint implements RelationalModel, Serializable { public void setName(String name) { this.name = name; } + + /** + * If a constraint is not explicitly named, this is called to generate + * a unique hash using the table and column names. + * Static so the name can be generated prior to creating the Constraint. + * They're cached, keyed by name, in multiple locations. + * + * @param prefix + * Appended to the beginning of the generated name + * @param table + * @param columns + * @return String The generated name + */ + public static String generateName(String prefix, Table table, Column... columns) { + // Use a concatenation that guarantees uniqueness, even if identical names + // exist between all table and column identifiers. + + StringBuilder sb = new StringBuilder( "table`" + table.getName() + "`" ); + + // Ensure a consistent ordering of columns, regardless of the order + // they were bound. + // Clone the list, as sometimes a set of order-dependent Column + // bindings are given. + Column[] alphabeticalColumns = columns.clone(); + Arrays.sort( alphabeticalColumns, ColumnComparator.INSTANCE ); + for ( Column column : alphabeticalColumns ) { + String columnName = column == null ? "" : column.getName(); + sb.append( "column`" + columnName + "`" ); + } + return prefix + hashedName( sb.toString() ); + } + + /** + * Helper method for {@link #generateName(String, Table, Column...)}. + * + * @param prefix + * Appended to the beginning of the generated name + * @param table + * @param columns + * @return String The generated name + */ + public static String generateName(String prefix, Table table, List columns) { + return generateName( prefix, table, columns.toArray( new Column[columns.size()] ) ); + } + + /** + * Hash a constraint name using MD5. Convert the MD5 digest to base 35 + * (full alphanumeric), guaranteeing + * that the length of the name will always be smaller than the 30 + * character identifier restriction enforced by a few dialects. + * + * @param s + * The name to be hashed. + * @return String The hased name. + */ + public static String hashedName(String s) { + try { + MessageDigest md = MessageDigest.getInstance( "MD5" ); + md.reset(); + md.update( s.getBytes() ); + byte[] digest = md.digest(); + BigInteger bigInt = new BigInteger( 1, digest ); + // By converting to base 35 (full alphanumeric), we guarantee + // that the length of the name will always be smaller than the 30 + // character identifier restriction enforced by a few dialects. + return bigInt.toString( 35 ); + } + catch ( NoSuchAlgorithmException e ) { + throw new HibernateException( "Unable to generate a hashed Constraint name!", e ); + } + } + + private static class ColumnComparator implements Comparator { + public static ColumnComparator INSTANCE = new ColumnComparator(); + + public int compare(Column col1, Column col2) { + return col1.getName().compareTo( col2.getName() ); + } + } public void addColumn(Column column) { if ( !columns.contains( column ) ) columns.add( column ); @@ -133,4 +219,10 @@ public abstract class Constraint implements RelationalModel, Serializable { public String toString() { return getClass().getName() + '(' + getTable().getName() + getColumns() + ") as " + name; } + + /** + * @return String The prefix to use in generated constraint names. Examples: + * "UK_", "FK_", and "PK_". + */ + public abstract String generatedConstraintNamePrefix(); } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/ForeignKey.java b/hibernate-core/src/main/java/org/hibernate/mapping/ForeignKey.java index 4e63dd012b..02caf61783 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/ForeignKey.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/ForeignKey.java @@ -180,4 +180,8 @@ public class ForeignKey extends Constraint { } } + + public String generatedConstraintNamePrefix() { + return "FK_"; + } } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/PrimaryKey.java b/hibernate-core/src/main/java/org/hibernate/mapping/PrimaryKey.java index 7df07997ba..4e7585bea2 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/PrimaryKey.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/PrimaryKey.java @@ -53,4 +53,8 @@ public class PrimaryKey extends Constraint { } return buf.append(')').toString(); } + + public String generatedConstraintNamePrefix() { + return "PK_"; + } } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Table.java b/hibernate-core/src/main/java/org/hibernate/mapping/Table.java index 6c3eee99c0..c5d5fb490a 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Table.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Table.java @@ -35,7 +35,6 @@ import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.dialect.Dialect; import org.hibernate.engine.spi.Mapping; -import org.hibernate.internal.util.StringHelper; import org.hibernate.tool.hbm2ddl.ColumnMetadata; import org.hibernate.tool.hbm2ddl.TableMetadata; @@ -69,15 +68,6 @@ public class Table implements RelationalModel, Serializable { private boolean hasDenormalizedTables = false; private String comment; - /** - * Natural ID columns must reside in one single UniqueKey within the Table. - * To prevent separate UniqueKeys from being created, this keeps track of - * a sole name used for all of them. It's necessary since - * AnnotationBinder#processElementAnnotations (static) creates the - * UniqueKeys on a second pass using randomly-generated names. - */ - private final String naturalIdUniqueKeyName = StringHelper.randomFixedLengthHex( "UK_" ); - static class ForeignKeyKey implements Serializable { String referencedClassName; List columns; @@ -430,8 +420,8 @@ public class Table implements RelationalModel, Serializable { } if ( column.isUnique() ) { - UniqueKey uk = getOrCreateUniqueKey( - StringHelper.randomFixedLengthHex("UK_")); + String keyName = Constraint.generateName( "UK_", this, column ); + UniqueKey uk = getOrCreateUniqueKey( keyName ); uk.addColumn( column ); alter.append( dialect.getUniqueDelegate() .getColumnDefinitionUniquenessFragment( column ) ); @@ -533,8 +523,8 @@ public class Table implements RelationalModel, Serializable { } if ( col.isUnique() ) { - UniqueKey uk = getOrCreateUniqueKey( - StringHelper.randomFixedLengthHex("UK_")); + String keyName = Constraint.generateName( "UK_", this, col ); + UniqueKey uk = getOrCreateUniqueKey( keyName ); uk.addColumn( col ); buf.append( dialect.getUniqueDelegate() .getColumnDefinitionUniquenessFragment( col ) ); @@ -630,7 +620,7 @@ public class Table implements RelationalModel, Serializable { } public UniqueKey createUniqueKey(List keyColumns) { - String keyName = StringHelper.randomFixedLengthHex("UK_"); + String keyName = Constraint.generateName( "UK_", this, keyColumns ); UniqueKey uk = getOrCreateUniqueKey( keyName ); uk.addColumns( keyColumns.iterator() ); return uk; @@ -666,19 +656,22 @@ public class Table implements RelationalModel, Serializable { ForeignKey fk = (ForeignKey) foreignKeys.get( key ); if ( fk == null ) { fk = new ForeignKey(); - if ( keyName != null ) { - fk.setName( keyName ); - } - else { - fk.setName( StringHelper.randomFixedLengthHex("FK_") ); - } fk.setTable( this ); - foreignKeys.put( key, fk ); fk.setReferencedEntityName( referencedEntityName ); fk.addColumns( keyColumns.iterator() ); if ( referencedColumns != null ) { fk.addReferencedColumns( referencedColumns.iterator() ); } + + if ( keyName != null ) { + fk.setName( keyName ); + } + else { + fk.setName( Constraint.generateName( fk.generatedConstraintNamePrefix(), + this, keyColumns ) ); + } + + foreignKeys.put( key, fk ); } if ( keyName != null ) { @@ -827,10 +820,6 @@ public class Table implements RelationalModel, Serializable { public Iterator getCheckConstraintsIterator() { return checkConstraints.iterator(); } - - public String getNaturalIdUniqueKeyName() { - return naturalIdUniqueKeyName; - } public Iterator sqlCommentStrings(Dialect dialect, String defaultCatalog, String defaultSchema) { List comments = new ArrayList(); diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/UniqueKey.java b/hibernate-core/src/main/java/org/hibernate/mapping/UniqueKey.java index 06ee87093a..5e36fc202a 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/UniqueKey.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/UniqueKey.java @@ -74,4 +74,8 @@ public class UniqueKey extends Constraint { public Map getColumnOrderMap() { return columnOrderMap; } + + public String generatedConstraintNamePrefix() { + return "UK_"; + } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/schemavalidation/SynonymValidationTest.java b/hibernate-core/src/test/java/org/hibernate/test/schemavalidation/SynonymValidationTest.java new file mode 100644 index 0000000000..b04b4eba98 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/test/schemavalidation/SynonymValidationTest.java @@ -0,0 +1,187 @@ +/* + * 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.test.schemavalidation; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.Configuration; +import org.hibernate.dialect.Oracle9iDialect; +import org.hibernate.testing.RequiresDialect; +import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.tool.hbm2ddl.SchemaValidator; +import org.junit.Test; + +/** + * @author Brett Meyer + */ +@RequiresDialect( Oracle9iDialect.class ) +public class SynonymValidationTest extends BaseUnitTestCase { + + @Test + public void testSynonymValidation() { +// Session s = openSession(); +// s.getTransaction().begin(); +// s.createSQLQuery( "CREATE SYNONYM test_synonym FOR test_entity" ).executeUpdate(); +// s.getTransaction().commit(); +// s.close(); + + Configuration cfg = new Configuration(); +// cfg.addAnnotatedClass( TestEntityWithSynonym.class ); + cfg.addAnnotatedClass( TestEntity.class ); + cfg.setProperty( AvailableSettings.ENABLE_SYNONYMS, "true" ); + cfg.setProperty( "hibernate.connection.includeSynonyms", "true" ); + cfg.getProperties().put( "includeSynonyms", true ); + +// SchemaValidator schemaValidator = new SchemaValidator( serviceRegistry(), cfg ); + SchemaValidator schemaValidator = new SchemaValidator( cfg ); + schemaValidator.validate(); + +// s = openSession(); +// s.getTransaction().begin(); +// s.createSQLQuery( "DROP SYNONYM test_synonym FORCE" ).executeUpdate(); +// s.getTransaction().commit(); +// s.close(); + } + +// protected Class[] getAnnotatedClasses() { +// return new Class[] { TestEntity.class }; +// } + + @Entity + @Table(name = "TEST_SYN") + private static class TestEntity implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue + private Long id; + + @Column(nullable = false) + private String key; + private String value; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } + +// @Entity +// @Table(name = "test_entity") +// private static class TestEntity { +// @Id +// @GeneratedValue +// private Long id; +// +// @Column(nullable = false) +// private String key; +// +// private String value; +// +// public Long getId() { +// return id; +// } +// +// public void setId(Long id) { +// this.id = id; +// } +// +// public String getKey() { +// return key; +// } +// +// public void setKey(String key) { +// this.key = key; +// } +// +// public String getValue() { +// return value; +// } +// +// public void setValue(String value) { +// this.value = value; +// } +// } +// +// @Entity +// @Table(name = "test_synonym") +// private static class TestEntityWithSynonym { +// @Id +// @GeneratedValue +// private Long id; +// +// @Column(nullable = false) +// private String key; +// +// private String value; +// +// public Long getId() { +// return id; +// } +// +// public void setId(Long id) { +// this.id = id; +// } +// +// public String getKey() { +// return key; +// } +// +// public void setKey(String key) { +// this.key = key; +// } +// +// public String getValue() { +// return value; +// } +// +// public void setValue(String value) { +// this.value = value; +// } +// } +} From 4c47ba13e3f96f9170d2d05f028ae2cf10cf1006 Mon Sep 17 00:00:00 2001 From: Christian Beikov Date: Wed, 1 May 2013 22:50:34 +0200 Subject: [PATCH 11/25] HHH-5465 - HQL left join fetch of an element collection following a left join fetch of a one-to-one relationship causes NullPointerException (testcase) --- .../test/collection/set/hhh8206/Contact.java | 97 +++++++++++++++++++ .../collection/set/hhh8206/EmailAddress.java | 57 +++++++++++ .../JoinFetchElementCollectionTest.java | 61 ++++++++++++ .../test/collection/set/hhh8206/User.java | 87 +++++++++++++++++ 4 files changed, 302 insertions(+) create mode 100644 hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/Contact.java create mode 100644 hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/EmailAddress.java create mode 100644 hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/JoinFetchElementCollectionTest.java create mode 100644 hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/User.java diff --git a/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/Contact.java b/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/Contact.java new file mode 100644 index 0000000000..cb63418055 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/Contact.java @@ -0,0 +1,97 @@ +package org.hibernate.test.collection.set.hhh8206; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; +import javax.persistence.Basic; +import javax.persistence.CollectionTable; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToMany; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name="contact") +public class Contact implements Serializable { + + private static final long serialVersionUID = 1L; + private Long id; + private String name; + private Set emailAddresses = new HashSet(); + private Set emailAddresses2 = new HashSet(); + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + @Basic + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @ElementCollection + @CollectionTable(name = "user_email_addresses2", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")) + public Set getEmailAddresses2() { + return emailAddresses2; + } + + public void setEmailAddresses2(Set emailAddresses2) { + this.emailAddresses2 = emailAddresses2; + } + + @ElementCollection + @CollectionTable(name = "user_email_addresses", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")) + public Set getEmailAddresses() { + return emailAddresses; + } + + public void setEmailAddresses(Set emailAddresses) { + this.emailAddresses = emailAddresses; + } + + @Override + public int hashCode() { + int hash = 0; + hash += (id != null ? id.hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof Contact)) { + return false; + } + final Contact other = (Contact) obj; + if (this.id == null || other.id == null) { + return this == obj; + } + if(!this.id.equals(other.id)) { + return this == obj; + } + return true; + } + + @Override + public String toString() { + return "com.clevercure.web.hibernateissuecache.User[ id=" + id + " ]"; + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/EmailAddress.java b/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/EmailAddress.java new file mode 100644 index 0000000000..50fcf5a0dc --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/EmailAddress.java @@ -0,0 +1,57 @@ +package org.hibernate.test.collection.set.hhh8206; + +import java.io.Serializable; +import java.util.Set; +import javax.persistence.*; + +@Embeddable +public class EmailAddress implements Serializable { + + private static final long serialVersionUID = 1L; + private String email; + + public EmailAddress() { + } + + public EmailAddress(String email) { + this.email = email; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public int hashCode() { + int hash = 0; + hash += (email != null ? email.hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof EmailAddress)) { + return false; + } + final EmailAddress other = (EmailAddress) obj; + if (this.email == null || other.email == null) { + return this == obj; + } + if(!this.email.equals(other.email)) { + return this == obj; + } + return true; + } + + @Override + public String toString() { + return "com.clevercure.web.hibernateissuecache.EmailAddress[ email=" + email + " ]"; + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/JoinFetchElementCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/JoinFetchElementCollectionTest.java new file mode 100644 index 0000000000..2870a88517 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/JoinFetchElementCollectionTest.java @@ -0,0 +1,61 @@ +package org.hibernate.test.collection.set.hhh8206; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.junit.Assert; +import org.junit.Test; + +public class JoinFetchElementCollectionTest extends BaseCoreFunctionalTestCase { + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {Contact.class, EmailAddress.class, User.class}; + } + + @Test + public void test(){ + Set emailAddresses = new HashSet(); + emailAddresses.add(new EmailAddress("test1@test.com")); + emailAddresses.add(new EmailAddress("test2@test.com")); + emailAddresses.add(new EmailAddress("test3@test.com")); + + { + // Session 1: Insert a user with email addresses but no emailAddresses2 + Session session = openSession(); + session.beginTransaction(); + + User user = new User(); + user.setName("john"); + Contact contact = new Contact(); + contact.setName("John Doe"); + contact.setEmailAddresses(emailAddresses); + contact = (Contact) session.merge(contact); + user.setContact(contact); + user = (User) session.merge(user); + + session.getTransaction().commit(); + session.close(); + } + { + // Session 2: Retrieve the user object and check if the sets have the expected values + Session session = openSession(); + session.beginTransaction(); + User user = (User) session.createQuery("SELECT user " + + "FROM User user " + + "LEFT OUTER JOIN FETCH user.contact " + + "LEFT OUTER JOIN FETCH user.contact.emailAddresses2 " + + "LEFT OUTER JOIN FETCH user.contact.emailAddresses") + .uniqueResult(); + session.getTransaction().commit(); + session.close(); + + Assert.assertEquals(emailAddresses, user.getContact().getEmailAddresses()); + Assert.assertTrue(user.getContact().getEmailAddresses2().isEmpty()); + } + + } + +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/User.java b/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/User.java new file mode 100644 index 0000000000..315195a168 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/User.java @@ -0,0 +1,87 @@ +package org.hibernate.test.collection.set.hhh8206; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; +import javax.persistence.Basic; +import javax.persistence.CollectionTable; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name="users") +public class User implements Serializable { + + private static final long serialVersionUID = 1L; + private Long id; + private String name; + private Contact contact; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + @Basic + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @ManyToOne(optional = true) + @JoinColumn(name = "contact_id", nullable = true, unique = true) + public Contact getContact() { + return contact; + } + + public void setContact(Contact contact) { + this.contact = contact; + } + + @Override + public int hashCode() { + int hash = 0; + hash += (id != null ? id.hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof User)) { + return false; + } + final User other = (User) obj; + if (this.id == null || other.id == null) { + return this == obj; + } + if(!this.id.equals(other.id)) { + return this == obj; + } + return true; + } + + @Override + public String toString() { + return "com.clevercure.web.hibernateissuecache.User[ id=" + id + " ]"; + } +} From f09a33760132a96d8836aa4fc17c393d8c03e20a Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Tue, 7 May 2013 14:13:54 -0500 Subject: [PATCH 12/25] HHH-5465 - HQL left join fetch of an element collection following a left join fetch of a one-to-one relationship causes NullPointerException --- .../hql/internal/ast/tree/SelectClause.java | 15 +- .../{set/hhh8206 => basic}/Contact.java | 5 +- .../{set/hhh8206 => basic}/EmailAddress.java | 3 +- .../basic/JoinFetchElementCollectionTest.java | 133 ++++++++++++++++++ .../{set/hhh8206 => basic}/User.java | 9 +- .../JoinFetchElementCollectionTest.java | 61 -------- 6 files changed, 143 insertions(+), 83 deletions(-) rename hibernate-core/src/test/java/org/hibernate/test/collection/{set/hhh8206 => basic}/Contact.java (93%) rename hibernate-core/src/test/java/org/hibernate/test/collection/{set/hhh8206 => basic}/EmailAddress.java (94%) create mode 100644 hibernate-core/src/test/java/org/hibernate/test/collection/basic/JoinFetchElementCollectionTest.java rename hibernate-core/src/test/java/org/hibernate/test/collection/{set/hhh8206 => basic}/User.java (85%) delete mode 100644 hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/JoinFetchElementCollectionTest.java diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/SelectClause.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/SelectClause.java index 15873916c7..1624155587 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/SelectClause.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/SelectClause.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.hql.internal.ast.tree; import java.util.ArrayList; @@ -139,7 +138,7 @@ public class SelectClause extends SelectExpressionList { // NOTE: This must be done *before* invoking setScalarColumnText() because setScalarColumnText() // changes the AST!!! SelectExpression[] selectExpressions = collectSelectExpressions(); - + for ( int i = 0; i < selectExpressions.length; i++ ) { SelectExpression selectExpression = selectExpressions[i]; @@ -176,14 +175,14 @@ public class SelectClause extends SelectExpressionList { if ( !getWalker().isShallowQuery() ) { // add the fetched entities List fromElements = fromClause.getProjectionList(); - + ASTAppender appender = new ASTAppender( getASTFactory(), this ); // Get ready to start adding nodes. int size = fromElements.size(); Iterator iterator = fromElements.iterator(); for ( int k = 0; iterator.hasNext(); k++ ) { FromElement fromElement = ( FromElement ) iterator.next(); - + if ( fromElement.isFetch() ) { FromElement origin = null; if ( fromElement.getRealOrigin() == null ) { @@ -226,7 +225,7 @@ public class SelectClause extends SelectExpressionList { } } } - + // generate id select fragment and then property select fragment for // each expression, just like generateSelectFragments(). renderNonScalarSelects( collectSelectExpressions(), fromClause ); @@ -326,7 +325,7 @@ public class SelectClause extends SelectExpressionList { private void addCollectionFromElement(FromElement fromElement) { if ( fromElement.isFetch() ) { - if ( fromElement.isCollectionJoin() || fromElement.getQueryableCollection() != null ) { + if ( fromElement.getQueryableCollection() != null ) { String suffix; if (collectionFromElements==null) { collectionFromElements = new ArrayList(); diff --git a/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/Contact.java b/hibernate-core/src/test/java/org/hibernate/test/collection/basic/Contact.java similarity index 93% rename from hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/Contact.java rename to hibernate-core/src/test/java/org/hibernate/test/collection/basic/Contact.java index cb63418055..7706fe2225 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/Contact.java +++ b/hibernate-core/src/test/java/org/hibernate/test/collection/basic/Contact.java @@ -1,4 +1,4 @@ -package org.hibernate.test.collection.set.hhh8206; +package org.hibernate.test.collection.basic; import java.io.Serializable; import java.util.HashSet; @@ -7,13 +7,10 @@ import javax.persistence.Basic; import javax.persistence.CollectionTable; import javax.persistence.ElementCollection; import javax.persistence.Entity; -import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; -import javax.persistence.ManyToMany; -import javax.persistence.OneToMany; import javax.persistence.Table; @Entity diff --git a/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/EmailAddress.java b/hibernate-core/src/test/java/org/hibernate/test/collection/basic/EmailAddress.java similarity index 94% rename from hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/EmailAddress.java rename to hibernate-core/src/test/java/org/hibernate/test/collection/basic/EmailAddress.java index 50fcf5a0dc..5611b868c6 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/EmailAddress.java +++ b/hibernate-core/src/test/java/org/hibernate/test/collection/basic/EmailAddress.java @@ -1,7 +1,6 @@ -package org.hibernate.test.collection.set.hhh8206; +package org.hibernate.test.collection.basic; import java.io.Serializable; -import java.util.Set; import javax.persistence.*; @Embeddable diff --git a/hibernate-core/src/test/java/org/hibernate/test/collection/basic/JoinFetchElementCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/test/collection/basic/JoinFetchElementCollectionTest.java new file mode 100644 index 0000000000..f728aeb9df --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/test/collection/basic/JoinFetchElementCollectionTest.java @@ -0,0 +1,133 @@ +/* + * 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 + */ +package org.hibernate.test.collection.basic; + +import java.util.HashSet; +import java.util.Set; + +import org.hibernate.Session; + +import org.junit.Assert; +import org.junit.Test; + +import org.hibernate.testing.FailureExpected; +import org.hibernate.testing.TestForIssue; +import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; + +public class JoinFetchElementCollectionTest extends BaseCoreFunctionalTestCase { + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {Contact.class, EmailAddress.class, User.class}; + } + + @Test + @TestForIssue(jiraKey = "HHH-8206") + @FailureExpected(jiraKey = "HHH-8206", message = "This is not explicitly supported, however should arguably throw an exception") + public void testJoinFetchesByPath() { + Set emailAddresses = new HashSet(); + emailAddresses.add( new EmailAddress( "test1@test.com" ) ); + emailAddresses.add( new EmailAddress( "test2@test.com" ) ); + emailAddresses.add( new EmailAddress( "test3@test.com" ) ); + + { + // Session 1: Insert a user with email addresses but no emailAddresses2 + Session session = openSession(); + session.beginTransaction(); + + User user = new User(); + user.setName( "john" ); + Contact contact = new Contact(); + contact.setName( "John Doe" ); + contact.setEmailAddresses( emailAddresses ); + contact = (Contact) session.merge( contact ); + user.setContact( contact ); + user = (User) session.merge( user ); + + session.getTransaction().commit(); + session.close(); + } + { + // Session 2: Retrieve the user object and check if the sets have the expected values + Session session = openSession(); + session.beginTransaction(); + final String qry = "SELECT user " + + "FROM User user " + + "LEFT OUTER JOIN FETCH user.contact " + + "LEFT OUTER JOIN FETCH user.contact.emailAddresses2 " + + "LEFT OUTER JOIN FETCH user.contact.emailAddresses"; + User user = (User) session.createQuery( qry ).uniqueResult(); + session.getTransaction().commit(); + session.close(); + + Assert.assertEquals( emailAddresses, user.getContact().getEmailAddresses() ); + Assert.assertTrue( user.getContact().getEmailAddresses2().isEmpty() ); + } + + } + + @Test + @TestForIssue(jiraKey = "HHH-5465") + public void testJoinFetchElementCollection() { + Set emailAddresses = new HashSet(); + emailAddresses.add( new EmailAddress( "test1@test.com" ) ); + emailAddresses.add( new EmailAddress( "test2@test.com" ) ); + emailAddresses.add( new EmailAddress( "test3@test.com" ) ); + + { + // Session 1: Insert a user with email addresses but no emailAddresses2 + Session session = openSession(); + session.beginTransaction(); + + User user = new User(); + user.setName( "john" ); + Contact contact = new Contact(); + contact.setName( "John Doe" ); + contact.setEmailAddresses( emailAddresses ); + contact = (Contact) session.merge( contact ); + user.setContact( contact ); + user = (User) session.merge( user ); + + session.getTransaction().commit(); + session.close(); + } + { + // Session 2: Retrieve the user object and check if the sets have the expected values + Session session = openSession(); + session.beginTransaction(); + final String qry = "SELECT user " + + "FROM User user " + + "LEFT OUTER JOIN FETCH user.contact c " + + "LEFT OUTER JOIN FETCH c.emailAddresses2 " + + "LEFT OUTER JOIN FETCH c.emailAddresses"; + User user = (User) session.createQuery( qry ).uniqueResult(); + session.getTransaction().commit(); + session.close(); + + Assert.assertEquals( emailAddresses, user.getContact().getEmailAddresses() ); + Assert.assertTrue( user.getContact().getEmailAddresses2().isEmpty() ); + } + + } + +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/User.java b/hibernate-core/src/test/java/org/hibernate/test/collection/basic/User.java similarity index 85% rename from hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/User.java rename to hibernate-core/src/test/java/org/hibernate/test/collection/basic/User.java index 315195a168..ab244a4a31 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/User.java +++ b/hibernate-core/src/test/java/org/hibernate/test/collection/basic/User.java @@ -1,20 +1,13 @@ -package org.hibernate.test.collection.set.hhh8206; +package org.hibernate.test.collection.basic; import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; import javax.persistence.Basic; -import javax.persistence.CollectionTable; -import javax.persistence.ElementCollection; import javax.persistence.Entity; -import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; -import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; import javax.persistence.Table; @Entity diff --git a/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/JoinFetchElementCollectionTest.java b/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/JoinFetchElementCollectionTest.java deleted file mode 100644 index 2870a88517..0000000000 --- a/hibernate-core/src/test/java/org/hibernate/test/collection/set/hhh8206/JoinFetchElementCollectionTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.hibernate.test.collection.set.hhh8206; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; - -import org.hibernate.Session; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; - -public class JoinFetchElementCollectionTest extends BaseCoreFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {Contact.class, EmailAddress.class, User.class}; - } - - @Test - public void test(){ - Set emailAddresses = new HashSet(); - emailAddresses.add(new EmailAddress("test1@test.com")); - emailAddresses.add(new EmailAddress("test2@test.com")); - emailAddresses.add(new EmailAddress("test3@test.com")); - - { - // Session 1: Insert a user with email addresses but no emailAddresses2 - Session session = openSession(); - session.beginTransaction(); - - User user = new User(); - user.setName("john"); - Contact contact = new Contact(); - contact.setName("John Doe"); - contact.setEmailAddresses(emailAddresses); - contact = (Contact) session.merge(contact); - user.setContact(contact); - user = (User) session.merge(user); - - session.getTransaction().commit(); - session.close(); - } - { - // Session 2: Retrieve the user object and check if the sets have the expected values - Session session = openSession(); - session.beginTransaction(); - User user = (User) session.createQuery("SELECT user " - + "FROM User user " - + "LEFT OUTER JOIN FETCH user.contact " - + "LEFT OUTER JOIN FETCH user.contact.emailAddresses2 " - + "LEFT OUTER JOIN FETCH user.contact.emailAddresses") - .uniqueResult(); - session.getTransaction().commit(); - session.close(); - - Assert.assertEquals(emailAddresses, user.getContact().getEmailAddresses()); - Assert.assertTrue(user.getContact().getEmailAddresses2().isEmpty()); - } - - } - -} From 1df4b2ea3c98c74f3b6bbd42e266ee5c7ad60d27 Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Tue, 7 May 2013 16:02:37 -0400 Subject: [PATCH 13/25] HHH-8226 table synonyms cannot find columns on Oracle --- .../internal/ConnectionProviderInitiator.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) 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 b458dd2ce3..7e684f02f3 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 @@ -268,6 +268,9 @@ public class ConnectionProviderInitiator implements StandardServiceInitiator CONDITIONAL_PROPERTIES; + + static { + CONDITIONAL_PROPERTIES = new HashMap(); + // Oracle requires that includeSynonyms=true in order for getColumns to work using a table synonym name. + CONDITIONAL_PROPERTIES.put( Environment.ENABLE_SYNONYMS, "includeSynonyms" ); } } From 40373412e05e91ad0aaf0feca06bc8515c6358b4 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Tue, 7 May 2013 21:18:40 -0500 Subject: [PATCH 14/25] HHH-8220 - pom dependencies scope changed from compile to runtime --- build.gradle | 75 ++++++++++++++++++++++++++++++---------------------- 1 file changed, 43 insertions(+), 32 deletions(-) diff --git a/build.gradle b/build.gradle index 88203944a1..79e36532ae 100644 --- a/build.gradle +++ b/build.gradle @@ -406,39 +406,50 @@ subprojects { subProject -> } pom.withXml { - def root = asNode(); - root.appendNode( 'name', subProject.pomName() ) - root.appendNode( 'description', subProject.pomDescription() ) - root.appendNode( 'url', 'http://hibernate.org' ) - def org = root.appendNode( 'organization' ) - org.appendNode( 'name', 'Hibernate.org' ) - org.appendNode( 'url', 'http://hibernate.org' ) - def jira = root.appendNode( 'issueManagement' ) - jira.appendNode( 'system', 'jira' ) - jira.appendNode( 'url', 'https://hibernate.atlassian.net/browse/HHH' ) - def scm = root.appendNode( 'scm' ) - scm.appendNode( 'url', 'http://github.com/hibernate/hibernate-orm' ) - scm.appendNode( 'connection', 'scm:git:http://github.com/hibernate/hibernate-orm.git' ) - scm.appendNode( 'developerConnection', 'scm:git:git@github.com:hibernate/hibernate-orm.git' ) - def license = root.appendNode( 'licenses' ).appendNode( 'license' ); - license.appendNode( 'name', 'GNU Lesser General Public License' ) - license.appendNode( 'url', 'http://www.gnu.org/licenses/lgpl-2.1.html' ) - license.appendNode( 'comments', 'See discussion at http://hibernate.org/license for more details.' ) - license.appendNode( 'distribution', 'repo' ) - def dev = root.appendNode( 'developers' ).appendNode( 'developer' ); - dev.appendNode( 'id', 'hibernate-team' ) - dev.appendNode( 'name', 'The Hibernate Development Team' ) - dev.appendNode( 'organization', 'Hibernate.org' ) - dev.appendNode( 'organizationUrl', 'http://hibernate.org' ) +// sadly for some reason it is not working within the closure above to define the descritpion... + asNode().appendNode( 'description', subProject.pomDescription() ) - final String runtimeScope = 'runtime'; - final int replacementLength = runtimeScope.length(); - final String compileScope = 'compile'; - final StringBuilder stringBuilder = asString(); - int index = stringBuilder.indexOf( runtimeScope ); - while ( index > -1 ) { - stringBuilder.replace( index, index+replacementLength, compileScope ); - index = stringBuilder.indexOf( runtimeScope ); + // append additional metadata + asNode().children().last() + { + name subProject.pomName() +// ugh, see above +// description subProject.pomDescription() + url 'http://hibernate.org' + organization { + name 'Hibernate.org' + url 'http://hibernate.org' + } + issueManagement { + system 'jira' + url 'https://hibernate.atlassian.net/browse/HHH' + } + scm { + url 'http://github.com/hibernate/hibernate-orm' + connection 'scm:git:http://github.com/hibernate/hibernate-orm.git' + developerConnection 'scm:git:git@github.com:hibernate/hibernate-orm.git' + } + licenses { + license { + name 'GNU Lesser General Public License' + url 'http://www.gnu.org/licenses/lgpl-2.1.html' + comments 'See discussion at http://hibernate.org/license for more details.' + distribution 'repo' + } + } + developers { + developer { + id 'hibernate-team' + name 'The Hibernate Development Team' + organization 'Hibernate.org' + organizationUrl 'http://hibernate.org' + } + } + } + + // TEMPORARY : currently Gradle Publishing feature is exporting dependencies as 'runtime' scope, + // rather than 'compile'; fix that. + asNode().dependencies[0].dependency.each { + it.scope[0].value = 'compile' } } } From 8c95a6077a523c47482fbae14ab54b763fa73a23 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Thu, 9 May 2013 14:47:58 -0500 Subject: [PATCH 15/25] HHH-8222 - Implement @NamedStoredProcedureQuery binding --- .../org/hibernate/SharedSessionContract.java | 13 +- .../org/hibernate/cfg/AnnotationBinder.java | 42 +++ .../java/org/hibernate/cfg/Configuration.java | 18 +- .../main/java/org/hibernate/cfg/Mappings.java | 10 + .../NamedProcedureCallDefinition.java | 237 ++++++++++++++++ .../cfg/annotations/QueryBinder.java | 15 ++ .../engine/spi/SessionDelegatorBaseImpl.java | 83 ++++++ .../engine/spi/SessionFactoryImplementor.java | 1 + .../internal/AbstractSessionImpl.java | 36 ++- .../internal/NamedQueryRepository.java | 29 +- .../internal/SessionFactoryImpl.java | 21 +- .../util/collections/CollectionHelper.java | 12 + .../custom/sql/SQLQueryReturnProcessor.java | 31 ++- .../hibernate/procedure/ProcedureCall.java | 17 ++ .../procedure/ProcedureCallMemento.java | 63 +++++ .../AbstractParameterRegistrationImpl.java | 72 ++++- .../internal/NamedParameterRegistration.java | 19 +- .../ParameterRegistrationImplementor.java | 30 +++ .../procedure/internal/ParameterStrategy.java | 9 + .../PositionalParameterRegistration.java | 19 +- .../procedure/internal/ProcedureCallImpl.java | 253 ++++++++++++++---- .../internal/ProcedureCallMementoImpl.java | 169 ++++++++++++ .../hibernate/procedure/internal/Util.java | 116 ++++++++ .../internal/EntityManagerFactoryImpl.java | 27 +- .../internal/StoredProcedureQueryImpl.java | 4 + .../jpa/spi/AbstractEntityManagerImpl.java | 40 ++- 26 files changed, 1275 insertions(+), 111 deletions(-) create mode 100644 hibernate-core/src/main/java/org/hibernate/cfg/annotations/NamedProcedureCallDefinition.java create mode 100644 hibernate-core/src/main/java/org/hibernate/procedure/ProcedureCallMemento.java create mode 100644 hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallMementoImpl.java create mode 100644 hibernate-core/src/main/java/org/hibernate/procedure/internal/Util.java diff --git a/hibernate-core/src/main/java/org/hibernate/SharedSessionContract.java b/hibernate-core/src/main/java/org/hibernate/SharedSessionContract.java index 33f76243cf..d847c28a4a 100644 --- a/hibernate-core/src/main/java/org/hibernate/SharedSessionContract.java +++ b/hibernate-core/src/main/java/org/hibernate/SharedSessionContract.java @@ -26,6 +26,7 @@ package org.hibernate; import java.io.Serializable; import org.hibernate.procedure.ProcedureCall; +import org.hibernate.procedure.ProcedureCallMemento; /** * Contract methods shared between {@link Session} and {@link StatelessSession}. @@ -86,6 +87,17 @@ public interface SharedSessionContract extends Serializable { */ public SQLQuery createSQLQuery(String queryString); + /** + * Gets a ProcedureCall based on a named template + * + * @param name The name given to the template + * + * @return The ProcedureCall + * + * @see javax.persistence.NamedStoredProcedureQuery + */ + public ProcedureCall getNamedProcedureCall(String name); + /** * Creates a call to a stored procedure. * @@ -154,5 +166,4 @@ public interface SharedSessionContract extends Serializable { * @return The criteria instance for manipulation and execution */ public Criteria createCriteria(String entityName, String alias); - } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java index 0414122b4f..77034482f6 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java @@ -68,6 +68,8 @@ import javax.persistence.NamedNativeQueries; import javax.persistence.NamedNativeQuery; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; +import javax.persistence.NamedStoredProcedureQueries; +import javax.persistence.NamedStoredProcedureQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.OrderColumn; @@ -253,6 +255,28 @@ public final class AnnotationBinder { } } } + + { + final List annotations = + (List) defaults.get( NamedStoredProcedureQuery.class ); + if ( annotations != null ) { + for ( NamedStoredProcedureQuery annotation : annotations ) { + QueryBinder.bindNamedStoredProcedureQuery( annotation, mappings ); + } + } + } + + { + final List annotations = + (List) defaults.get( NamedStoredProcedureQueries.class ); + if ( annotations != null ) { + for ( NamedStoredProcedureQueries annotation : annotations ) { + for ( NamedStoredProcedureQuery queryAnnotation : annotation.value() ) { + QueryBinder.bindNamedStoredProcedureQuery( queryAnnotation, mappings ); + } + } + } + } } public static void bindPackage(String packageName, Mappings mappings) { @@ -358,6 +382,24 @@ public final class AnnotationBinder { ); QueryBinder.bindNativeQueries( ann, mappings ); } + + // NamedStoredProcedureQuery handling ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + { + final NamedStoredProcedureQuery annotation = annotatedElement.getAnnotation( NamedStoredProcedureQuery.class ); + if ( annotation != null ) { + QueryBinder.bindNamedStoredProcedureQuery( annotation, mappings ); + } + } + + // NamedStoredProcedureQueries handling ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + { + final NamedStoredProcedureQueries annotation = annotatedElement.getAnnotation( NamedStoredProcedureQueries.class ); + if ( annotation != null ) { + for ( NamedStoredProcedureQuery queryAnnotation : annotation.value() ) { + QueryBinder.bindNamedStoredProcedureQuery( queryAnnotation, mappings ); + } + } + } } private static IdGenerator buildIdGenerator(java.lang.annotation.Annotation ann, Mappings mappings) { diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java index cc6139a56a..ea3f4b8a2b 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java @@ -81,6 +81,7 @@ import org.hibernate.annotations.common.reflection.java.JavaReflectionManager; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl; +import org.hibernate.cfg.annotations.NamedProcedureCallDefinition; import org.hibernate.cfg.annotations.reflection.JPAMetadataProvider; import org.hibernate.context.spi.CurrentTenantIdentifierResolver; import org.hibernate.dialect.Dialect; @@ -214,6 +215,7 @@ public class Configuration implements Serializable { protected Map namedQueries; protected Map namedSqlQueries; + protected Map namedProcedureCallMap; protected Map sqlResultSetMappings; protected Map typeDefs; @@ -1772,6 +1774,10 @@ public class Configuration implements Serializable { return namedQueries; } + public Map getNamedProcedureCallMap() { + return namedProcedureCallMap; + } + /** * Create a {@link SessionFactory} using the properties and mappings in this configuration. The * {@link SessionFactory} will be immutable, so changes made to {@code this} {@link Configuration} after @@ -2764,7 +2770,7 @@ public class Configuration implements Serializable { public Table getTable(String schema, String catalog, String name) { String key = Table.qualify(catalog, schema, name); - return tables.get(key); + return tables.get( key ); } public Iterator iterateTables() { @@ -2870,6 +2876,16 @@ public class Configuration implements Serializable { namedSqlQueries.put( name.intern(), query ); } + @Override + public void addNamedProcedureCallDefinition(NamedProcedureCallDefinition definition) + throws DuplicateMappingException { + final String name = definition.getRegisteredName(); + final NamedProcedureCallDefinition previous = namedProcedureCallMap.put( name, definition ); + if ( previous != null ) { + throw new DuplicateMappingException( "named stored procedure query", name ); + } + } + public void addDefaultSQLQuery(String name, NamedSQLQueryDefinition query) { applySQLQuery( name, query ); defaultNamedNativeQueryNames.add( name ); diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Mappings.java b/hibernate-core/src/main/java/org/hibernate/cfg/Mappings.java index a0d6543fc6..4b49851563 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Mappings.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Mappings.java @@ -37,6 +37,7 @@ import org.hibernate.MappingException; import org.hibernate.annotations.AnyMetaDef; import org.hibernate.annotations.common.reflection.ReflectionManager; import org.hibernate.annotations.common.reflection.XClass; +import org.hibernate.cfg.annotations.NamedProcedureCallDefinition; import org.hibernate.engine.ResultSetMappingDefinition; import org.hibernate.engine.spi.FilterDefinition; import org.hibernate.engine.spi.NamedQueryDefinition; @@ -338,6 +339,15 @@ public interface Mappings { */ public void addSQLQuery(String name, NamedSQLQueryDefinition query) throws DuplicateMappingException; + /** + * Adds metadata for a named stored procedure call to this repository. + * + * @param definition The procedure call information + * + * @throws DuplicateMappingException If a query already exists with that name. + */ + public void addNamedProcedureCallDefinition(NamedProcedureCallDefinition definition) throws DuplicateMappingException; + /** * Get the metadata for a named SQL result set mapping. * diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/NamedProcedureCallDefinition.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/NamedProcedureCallDefinition.java new file mode 100644 index 0000000000..b50173c016 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/NamedProcedureCallDefinition.java @@ -0,0 +1,237 @@ +/* + * 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 + */ +package org.hibernate.cfg.annotations; + +import javax.persistence.NamedStoredProcedureQuery; +import javax.persistence.ParameterMode; +import javax.persistence.QueryHint; +import javax.persistence.StoredProcedureParameter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.hibernate.LockMode; +import org.hibernate.MappingException; +import org.hibernate.engine.ResultSetMappingDefinition; +import org.hibernate.engine.query.spi.sql.NativeSQLQueryReturn; +import org.hibernate.engine.query.spi.sql.NativeSQLQueryRootReturn; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.internal.SessionFactoryImpl; +import org.hibernate.internal.util.StringHelper; +import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.procedure.ProcedureCallMemento; +import org.hibernate.procedure.internal.ParameterStrategy; +import org.hibernate.procedure.internal.ProcedureCallMementoImpl; +import org.hibernate.procedure.internal.Util; + +import static org.hibernate.procedure.internal.ProcedureCallMementoImpl.ParameterMemento; + +/** + * Holds all the information needed from a named procedure call declaration in order to create a + * {@link org.hibernate.procedure.internal.ProcedureCallImpl} + * + * @author Steve Ebersole + * + * @see javax.persistence.NamedStoredProcedureQuery + */ +public class NamedProcedureCallDefinition { + private final String registeredName; + private final String procedureName; + private final Class[] resultClasses; + private final String[] resultSetMappings; + private final ParameterDefinitions parameterDefinitions; + private final Map hints; + + NamedProcedureCallDefinition(NamedStoredProcedureQuery annotation) { + this.registeredName = annotation.name(); + this.procedureName = annotation.procedureName(); + this.resultClasses = annotation.resultClasses(); + this.resultSetMappings = annotation.resultSetMappings(); + this.parameterDefinitions = new ParameterDefinitions( annotation.parameters() ); + this.hints = extract( annotation.hints() ); + + final boolean specifiesResultClasses = resultClasses != null && resultClasses.length > 0; + final boolean specifiesResultSetMappings = resultSetMappings != null && resultSetMappings.length > 0; + + if ( specifiesResultClasses && specifiesResultSetMappings ) { + throw new MappingException( + String.format( + "NamedStoredProcedureQuery [%s] specified both resultClasses and resultSetMappings", + registeredName + ) + ); + } + } + + private Map extract(QueryHint[] hints) { + if ( hints == null || hints.length == 0 ) { + return Collections.emptyMap(); + } + final Map hintsMap = new HashMap(); + for ( QueryHint hint : hints ) { + hintsMap.put( hint.name(), hint.value() ); + } + return hintsMap; + } + + public String getRegisteredName() { + return registeredName; + } + + public String getProcedureName() { + return procedureName; + } + + public ProcedureCallMemento toMemento( + final SessionFactoryImpl sessionFactory, + final Map resultSetMappingDefinitions) { + final List collectedQueryReturns = new ArrayList(); + final Set collectedQuerySpaces = new HashSet(); + + final boolean specifiesResultClasses = resultClasses != null && resultClasses.length > 0; + final boolean specifiesResultSetMappings = resultSetMappings != null && resultSetMappings.length > 0; + + if ( specifiesResultClasses ) { + Util.resolveResultClasses( + new Util.ResultClassesResolutionContext() { + @Override + public SessionFactoryImplementor getSessionFactory() { + return sessionFactory; + } + + @Override + public void addQueryReturns(NativeSQLQueryReturn... queryReturns) { + Collections.addAll( collectedQueryReturns, queryReturns ); + } + + @Override + public void addQuerySpaces(String... spaces) { + Collections.addAll( collectedQuerySpaces, spaces ); + } + }, + resultClasses + ); + } + else if ( specifiesResultSetMappings ) { + Util.resolveResultSetMappings( + new Util.ResultSetMappingResolutionContext() { + @Override + public SessionFactoryImplementor getSessionFactory() { + return sessionFactory; + } + + @Override + public ResultSetMappingDefinition findResultSetMapping(String name) { + return resultSetMappingDefinitions.get( name ); + } + + @Override + public void addQueryReturns(NativeSQLQueryReturn... queryReturns) { + Collections.addAll( collectedQueryReturns, queryReturns ); + } + + @Override + public void addQuerySpaces(String... spaces) { + Collections.addAll( collectedQuerySpaces, spaces ); + } + }, + resultSetMappings + ); + } + + return new ProcedureCallMementoImpl( + procedureName, + collectedQueryReturns.toArray( new NativeSQLQueryReturn[ collectedQueryReturns.size() ] ), + parameterDefinitions.getParameterStrategy(), + parameterDefinitions.toMementos( sessionFactory ), + collectedQuerySpaces, + hints + ); + } + + static class ParameterDefinitions { + private final ParameterStrategy parameterStrategy; + private final ParameterDefinition[] parameterDefinitions; + + ParameterDefinitions(StoredProcedureParameter[] parameters) { + if ( parameters == null || parameters.length == 0 ) { + parameterStrategy = ParameterStrategy.POSITIONAL; + parameterDefinitions = new ParameterDefinition[0]; + } + else { + parameterStrategy = StringHelper.isNotEmpty( parameters[0].name() ) + ? ParameterStrategy.NAMED + : ParameterStrategy.POSITIONAL; + parameterDefinitions = new ParameterDefinition[ parameters.length ]; + for ( int i = 0; i < parameters.length; i++ ) { + parameterDefinitions[i] = new ParameterDefinition( i, parameters[i] ); + } + } + } + + public ParameterStrategy getParameterStrategy() { + return parameterStrategy; + } + + public List toMementos(SessionFactoryImpl sessionFactory) { + final List mementos = new ArrayList(); + for ( ParameterDefinition definition : parameterDefinitions ) { + definition.toMemento( sessionFactory ); + } + return mementos; + } + } + + static class ParameterDefinition { + private final Integer position; + private final String name; + private final ParameterMode parameterMode; + private final Class type; + + ParameterDefinition(int position, StoredProcedureParameter annotation) { + this.position = position; + this.name = normalize( annotation.name() ); + this.parameterMode = annotation.mode(); + this.type = annotation.type(); + } + + public ParameterMemento toMemento(SessionFactoryImpl sessionFactory) { + return new ParameterMemento( + position, + name, + parameterMode, + type, + sessionFactory.getTypeResolver().heuristicType( type.getName() ) + ); + } + } + + private static String normalize(String name) { + return StringHelper.isNotEmpty( name ) ? name : null; + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/QueryBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/QueryBinder.java index 1299636ba5..2c21637b04 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/QueryBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/QueryBinder.java @@ -28,6 +28,7 @@ import javax.persistence.NamedNativeQueries; import javax.persistence.NamedNativeQuery; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; +import javax.persistence.NamedStoredProcedureQuery; import javax.persistence.QueryHint; import javax.persistence.SqlResultSetMapping; import javax.persistence.SqlResultSetMappings; @@ -331,6 +332,20 @@ public abstract class QueryBinder { } } + public static void bindNamedStoredProcedureQuery(NamedStoredProcedureQuery annotation, Mappings mappings) { + if ( annotation == null ) { + return; + } + + if ( BinderHelper.isEmptyAnnotationValue( annotation.name() ) ) { + throw new AnnotationException( "A named query must have a name when used in class or package level" ); + } + + final NamedProcedureCallDefinition def = new NamedProcedureCallDefinition( annotation ); + mappings.addNamedProcedureCallDefinition( def ); + LOG.debugf( "Bound named stored procedure query : %s => %s", def.getRegisteredName(), def.getProcedureName() ); + } + public static void bindSqlResultsetMappings(SqlResultSetMappings ann, Mappings mappings, boolean isDefault) { if ( ann == null ) return; for (SqlResultSetMapping rs : ann.value()) { diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/SessionDelegatorBaseImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/SessionDelegatorBaseImpl.java index 9e2686574c..d9c1908465 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/SessionDelegatorBaseImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/SessionDelegatorBaseImpl.java @@ -380,22 +380,31 @@ public class SessionDelegatorBaseImpl implements SessionImplementor, Session { // Delegates to Session + @Override public Transaction beginTransaction() { return session.beginTransaction(); } + @Override public Transaction getTransaction() { return session.getTransaction(); } + @Override public Query createQuery(String queryString) { return session.createQuery( queryString ); } + @Override public SQLQuery createSQLQuery(String queryString) { return session.createSQLQuery( queryString ); } + @Override + public ProcedureCall getNamedProcedureCall(String name) { + return session.getNamedProcedureCall( name ); + } + @Override public ProcedureCall createStoredProcedureCall(String procedureName) { return session.createStoredProcedureCall( procedureName ); @@ -411,298 +420,372 @@ public class SessionDelegatorBaseImpl implements SessionImplementor, Session { return session.createStoredProcedureCall( procedureName, resultSetMappings ); } + @Override public Criteria createCriteria(Class persistentClass) { return session.createCriteria( persistentClass ); } + @Override public Criteria createCriteria(Class persistentClass, String alias) { return session.createCriteria( persistentClass, alias ); } + @Override public Criteria createCriteria(String entityName) { return session.createCriteria( entityName ); } + @Override public Criteria createCriteria(String entityName, String alias) { return session.createCriteria( entityName, alias ); } + @Override public SharedSessionBuilder sessionWithOptions() { return session.sessionWithOptions(); } + @Override public SessionFactory getSessionFactory() { return session.getSessionFactory(); } + @Override public Connection close() throws HibernateException { return session.close(); } + @Override public void cancelQuery() throws HibernateException { session.cancelQuery(); } + @Override public boolean isDirty() throws HibernateException { return session.isDirty(); } + @Override public boolean isDefaultReadOnly() { return session.isDefaultReadOnly(); } + @Override public void setDefaultReadOnly(boolean readOnly) { session.setDefaultReadOnly( readOnly ); } + @Override public Serializable getIdentifier(Object object) { return session.getIdentifier( object ); } + @Override public boolean contains(Object object) { return session.contains( object ); } + @Override public void evict(Object object) { session.evict( object ); } + @Override public Object load(Class theClass, Serializable id, LockMode lockMode) { return session.load( theClass, id, lockMode ); } + @Override public Object load(Class theClass, Serializable id, LockOptions lockOptions) { return session.load( theClass, id, lockOptions ); } + @Override public Object load(String entityName, Serializable id, LockMode lockMode) { return session.load( entityName, id, lockMode ); } + @Override public Object load(String entityName, Serializable id, LockOptions lockOptions) { return session.load( entityName, id, lockOptions ); } + @Override public Object load(Class theClass, Serializable id) { return session.load( theClass, id ); } + @Override public Object load(String entityName, Serializable id) { return session.load( entityName, id ); } + @Override public void load(Object object, Serializable id) { session.load( object, id ); } + @Override public void replicate(Object object, ReplicationMode replicationMode) { session.replicate( object, replicationMode ); } + @Override public void replicate(String entityName, Object object, ReplicationMode replicationMode) { session.replicate( entityName, object, replicationMode ); } + @Override public Serializable save(Object object) { return session.save( object ); } + @Override public Serializable save(String entityName, Object object) { return session.save( entityName, object ); } + @Override public void saveOrUpdate(Object object) { session.saveOrUpdate( object ); } + @Override public void saveOrUpdate(String entityName, Object object) { session.saveOrUpdate( entityName, object ); } + @Override public void update(Object object) { session.update( object ); } + @Override public void update(String entityName, Object object) { session.update( entityName, object ); } + @Override public Object merge(Object object) { return session.merge( object ); } + @Override public Object merge(String entityName, Object object) { return session.merge( entityName, object ); } + @Override public void persist(Object object) { session.persist( object ); } + @Override public void persist(String entityName, Object object) { session.persist( entityName, object ); } + @Override public void delete(Object object) { session.delete( object ); } + @Override public void delete(String entityName, Object object) { session.delete( entityName, object ); } + @Override public void lock(Object object, LockMode lockMode) { session.lock( object, lockMode ); } + @Override public void lock(String entityName, Object object, LockMode lockMode) { session.lock( entityName, object, lockMode ); } + @Override public LockRequest buildLockRequest(LockOptions lockOptions) { return session.buildLockRequest( lockOptions ); } + @Override public void refresh(Object object) { session.refresh( object ); } + @Override public void refresh(String entityName, Object object) { session.refresh( entityName, object ); } + @Override public void refresh(Object object, LockMode lockMode) { session.refresh( object, lockMode ); } + @Override public void refresh(Object object, LockOptions lockOptions) { session.refresh( object, lockOptions ); } + @Override public void refresh(String entityName, Object object, LockOptions lockOptions) { session.refresh( entityName, object, lockOptions ); } + @Override public LockMode getCurrentLockMode(Object object) { return session.getCurrentLockMode( object ); } + @Override public Query createFilter(Object collection, String queryString) { return session.createFilter( collection, queryString ); } + @Override public void clear() { session.clear(); } + @Override public Object get(Class clazz, Serializable id) { return session.get( clazz, id ); } + @Override public Object get(Class clazz, Serializable id, LockMode lockMode) { return session.get( clazz, id, lockMode ); } + @Override public Object get(Class clazz, Serializable id, LockOptions lockOptions) { return session.get( clazz, id, lockOptions ); } + @Override public Object get(String entityName, Serializable id) { return session.get( entityName, id ); } + @Override public Object get(String entityName, Serializable id, LockMode lockMode) { return session.get( entityName, id, lockMode ); } + @Override public Object get(String entityName, Serializable id, LockOptions lockOptions) { return session.get( entityName, id, lockOptions ); } + @Override public String getEntityName(Object object) { return session.getEntityName( object ); } + @Override public IdentifierLoadAccess byId(String entityName) { return session.byId( entityName ); } + @Override public IdentifierLoadAccess byId(Class entityClass) { return session.byId( entityClass ); } + @Override public NaturalIdLoadAccess byNaturalId(String entityName) { return session.byNaturalId( entityName ); } + @Override public NaturalIdLoadAccess byNaturalId(Class entityClass) { return session.byNaturalId( entityClass ); } + @Override public SimpleNaturalIdLoadAccess bySimpleNaturalId(String entityName) { return session.bySimpleNaturalId( entityName ); } + @Override public SimpleNaturalIdLoadAccess bySimpleNaturalId(Class entityClass) { return session.bySimpleNaturalId( entityClass ); } + @Override public Filter enableFilter(String filterName) { return session.enableFilter( filterName ); } + @Override public Filter getEnabledFilter(String filterName) { return session.getEnabledFilter( filterName ); } + @Override public void disableFilter(String filterName) { session.disableFilter( filterName ); } + @Override public SessionStatistics getStatistics() { return session.getStatistics(); } + @Override public boolean isReadOnly(Object entityOrProxy) { return session.isReadOnly( entityOrProxy ); } + @Override public void setReadOnly(Object entityOrProxy, boolean readOnly) { session.setReadOnly( entityOrProxy, readOnly ); } + @Override public void doWork(Work work) throws HibernateException { session.doWork( work ); } + @Override public T doReturningWork(ReturningWork work) throws HibernateException { return session.doReturningWork( work ); } + @Override public Connection disconnect() { return session.disconnect(); } + @Override public void reconnect(Connection connection) { session.reconnect( connection ); } + @Override public boolean isFetchProfileEnabled(String name) throws UnknownProfileException { return session.isFetchProfileEnabled( name ); } + @Override public void enableFetchProfile(String name) throws UnknownProfileException { session.enableFetchProfile( name ); } + @Override public void disableFetchProfile(String name) throws UnknownProfileException { session.disableFetchProfile( name ); } + @Override public TypeHelper getTypeHelper() { return session.getTypeHelper(); } + @Override public LobHelper getLobHelper() { return session.getLobHelper(); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/SessionFactoryImplementor.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/SessionFactoryImplementor.java index 0e997fc478..aee333ad27 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/SessionFactoryImplementor.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/SessionFactoryImplementor.java @@ -51,6 +51,7 @@ import org.hibernate.id.IdentifierGenerator; import org.hibernate.internal.NamedQueryRepository; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.procedure.ProcedureCallMemento; import org.hibernate.proxy.EntityNotFoundDelegate; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.service.spi.ServiceRegistryImplementor; diff --git a/hibernate-core/src/main/java/org/hibernate/internal/AbstractSessionImpl.java b/hibernate-core/src/main/java/org/hibernate/internal/AbstractSessionImpl.java index c6b0153c74..4ed1481626 100755 --- a/hibernate-core/src/main/java/org/hibernate/internal/AbstractSessionImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/AbstractSessionImpl.java @@ -27,6 +27,7 @@ import java.io.Serializable; import java.sql.Connection; import java.sql.SQLException; import java.util.List; +import java.util.Map; import java.util.UUID; import org.hibernate.HibernateException; @@ -59,6 +60,7 @@ import org.hibernate.jdbc.WorkExecutorVisitable; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider; +import org.hibernate.procedure.ProcedureCallMemento; import org.hibernate.procedure.internal.ProcedureCallImpl; import org.hibernate.type.Type; @@ -67,11 +69,11 @@ import org.hibernate.type.Type; * * @author Gavin King */ -public abstract class AbstractSessionImpl implements Serializable, SharedSessionContract, - SessionImplementor, TransactionContext { +public abstract class AbstractSessionImpl + implements Serializable, SharedSessionContract, SessionImplementor, TransactionContext { protected transient SessionFactoryImpl factory; private final String tenantIdentifier; - private boolean closed = false; + private boolean closed; protected AbstractSessionImpl(SessionFactoryImpl factory, String tenantIdentifier) { this.factory = factory; @@ -218,10 +220,10 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession @Override public Query createQuery(String queryString) { errorIfClosed(); - QueryImpl query = new QueryImpl( + final QueryImpl query = new QueryImpl( queryString, - this, - getHQLQueryPlan( queryString, false ).getParameterMetadata() + this, + getHQLQueryPlan( queryString, false ).getParameterMetadata() ); query.setComment( queryString ); return query; @@ -230,15 +232,31 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession @Override public SQLQuery createSQLQuery(String sql) { errorIfClosed(); - SQLQueryImpl query = new SQLQueryImpl( + final SQLQueryImpl query = new SQLQueryImpl( sql, - this, - factory.getQueryPlanCache().getSQLParameterMetadata( sql ) + this, + factory.getQueryPlanCache().getSQLParameterMetadata( sql ) ); query.setComment( "dynamic native SQL query" ); return query; } + @Override + @SuppressWarnings("UnnecessaryLocalVariable") + public ProcedureCall getNamedProcedureCall(String name) { + errorIfClosed(); + + final ProcedureCallMemento memento = factory.getNamedQueryRepository().getNamedProcedureCallMemento( name ); + if ( memento == null ) { + throw new IllegalArgumentException( + "Could not find named stored procedure call with that registration name : " + name + ); + } + final ProcedureCall procedureCall = memento.makeProcedureCall( this ); +// procedureCall.setComment( "Named stored procedure call [" + name + "]" ); + return procedureCall; + } + @Override @SuppressWarnings("UnnecessaryLocalVariable") public ProcedureCall createStoredProcedureCall(String procedureName) { diff --git a/hibernate-core/src/main/java/org/hibernate/internal/NamedQueryRepository.java b/hibernate-core/src/main/java/org/hibernate/internal/NamedQueryRepository.java index 6dc7bb2425..90866b06ad 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/NamedQueryRepository.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/NamedQueryRepository.java @@ -25,20 +25,20 @@ package org.hibernate.internal; import java.util.Collections; import java.util.HashMap; -import java.util.Iterator; +import java.util.List; import java.util.Map; import org.jboss.logging.Logger; import org.hibernate.HibernateException; import org.hibernate.MappingException; -import org.hibernate.QueryException; import org.hibernate.engine.ResultSetMappingDefinition; import org.hibernate.engine.query.spi.QueryPlanCache; import org.hibernate.engine.query.spi.sql.NativeSQLQuerySpecification; import org.hibernate.engine.spi.NamedQueryDefinition; import org.hibernate.engine.spi.NamedSQLQueryDefinition; import org.hibernate.internal.util.collections.CollectionHelper; +import org.hibernate.procedure.ProcedureCallMemento; /** * @author Steve Ebersole @@ -46,14 +46,17 @@ import org.hibernate.internal.util.collections.CollectionHelper; public class NamedQueryRepository { private static final Logger log = Logger.getLogger( NamedQueryRepository.class ); + private final Map namedSqlResultSetMappingMap; + private volatile Map namedQueryDefinitionMap; private volatile Map namedSqlQueryDefinitionMap; - private final Map namedSqlResultSetMappingMap; + private volatile Map procedureCallMementoMap; public NamedQueryRepository( Iterable namedQueryDefinitions, Iterable namedSqlQueryDefinitions, - Iterable namedSqlResultSetMappings) { + Iterable namedSqlResultSetMappings, + List namedProcedureCalls) { final HashMap namedQueryDefinitionMap = new HashMap(); for ( NamedQueryDefinition namedQueryDefinition : namedQueryDefinitions ) { namedQueryDefinitionMap.put( namedQueryDefinition.getName(), namedQueryDefinition ); @@ -83,6 +86,10 @@ public class NamedQueryRepository { return namedSqlQueryDefinitionMap.get( queryName ); } + public ProcedureCallMemento getNamedProcedureCallMemento(String name) { + return procedureCallMementoMap.get( name ); + } + public ResultSetMappingDefinition getResultSetMappingDefinition(String mappingName) { return namedSqlResultSetMappingMap.get( mappingName ); } @@ -127,6 +134,20 @@ public class NamedQueryRepository { this.namedSqlQueryDefinitionMap = Collections.unmodifiableMap( copy ); } + public synchronized void registerNamedProcedureCallMemento(String name, ProcedureCallMemento memento) { + final Map copy = CollectionHelper.makeCopy( procedureCallMementoMap ); + final ProcedureCallMemento previous = copy.put( name, memento ); + if ( previous != null ) { + log.debugf( + "registering named procedure call definition [%s] overriding previously registered definition [%s]", + name, + previous + ); + } + + this.procedureCallMementoMap = Collections.unmodifiableMap( copy ); + } + public Map checkNamedQueries(QueryPlanCache queryPlanCache) { Map errors = new HashMap(); diff --git a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java index 45b2529fa1..3f191d8a8b 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java @@ -35,6 +35,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; @@ -82,6 +83,7 @@ import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.cfg.Settings; import org.hibernate.cfg.SettingsFactory; +import org.hibernate.cfg.annotations.NamedProcedureCallDefinition; import org.hibernate.context.internal.JTASessionContext; import org.hibernate.context.internal.ManagedSessionContext; import org.hibernate.context.internal.ThreadLocalSessionContext; @@ -133,6 +135,7 @@ import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.Loadable; import org.hibernate.persister.entity.Queryable; import org.hibernate.persister.spi.PersisterFactory; +import org.hibernate.procedure.ProcedureCallMemento; import org.hibernate.proxy.EntityNotFoundDelegate; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.spi.ServiceRegistryImplementor; @@ -455,7 +458,8 @@ public final class SessionFactoryImpl this.namedQueryRepository = new NamedQueryRepository( cfg.getNamedQueries().values(), cfg.getNamedSQLQueries().values(), - cfg.getSqlResultSetMappings().values() + cfg.getSqlResultSetMappings().values(), + toProcedureCallMementos( cfg.getNamedProcedureCallMap(), cfg.getSqlResultSetMappings() ) ); imports = new HashMap( cfg.getImports() ); @@ -576,6 +580,18 @@ public final class SessionFactoryImpl this.observer.sessionFactoryCreated( this ); } + private List toProcedureCallMementos( + Map definitions, + Map resultSetMappingMap) { + final List rtn = new ArrayList(); + if ( definitions != null ) { + for ( NamedProcedureCallDefinition definition : definitions.values() ) { + rtn.add( definition.toMemento( this, resultSetMappingMap ) ); + } + } + return rtn; + } + private JdbcConnectionAccess buildLocalConnectionAccess() { return new JdbcConnectionAccess() { @Override @@ -854,7 +870,8 @@ public final class SessionFactoryImpl namedQueryRepository = new NamedQueryRepository( metadata.getNamedQueryDefinitions(), metadata.getNamedNativeQueryDefinitions(), - metadata.getResultSetMappingDefinitions() + metadata.getResultSetMappingDefinitions(), + null ); imports = new HashMap(); diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/collections/CollectionHelper.java b/hibernate-core/src/main/java/org/hibernate/internal/util/collections/CollectionHelper.java index 377622d2b6..ff56575229 100755 --- a/hibernate-core/src/main/java/org/hibernate/internal/util/collections/CollectionHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/collections/CollectionHelper.java @@ -27,6 +27,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -131,6 +132,17 @@ public final class CollectionHelper { return new ArrayList( anticipatedSize ); } + public static Set makeCopy(Set source) { + if ( source == null ) { + return null; + } + + final int size = source.size(); + final Set copy = new HashSet( size + 1 ); + copy.addAll( source ); + return copy; + } + public static boolean isEmpty(Collection collection) { return collection == null || collection.isEmpty(); } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLQueryReturnProcessor.java b/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLQueryReturnProcessor.java index fe2cc4713d..61921e41ef 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLQueryReturnProcessor.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLQueryReturnProcessor.java @@ -24,7 +24,10 @@ */ package org.hibernate.loader.custom.sql; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -56,9 +59,12 @@ import org.hibernate.loader.custom.NonScalarReturn; import org.hibernate.loader.custom.Return; import org.hibernate.loader.custom.RootReturn; import org.hibernate.loader.custom.ScalarReturn; +import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.SQLLoadableCollection; import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.persister.entity.Joinable; import org.hibernate.persister.entity.SQLLoadable; +import org.hibernate.type.AssociationType; import org.hibernate.type.EntityType; import org.hibernate.type.Type; @@ -84,10 +90,10 @@ public class SQLQueryReturnProcessor { private final Map alias2Return = new HashMap(); private final Map alias2OwnerAlias = new HashMap(); - private final Map alias2Persister = new HashMap(); + private final Map alias2Persister = new HashMap(); private final Map alias2Suffix = new HashMap(); - private final Map alias2CollectionPersister = new HashMap(); + private final Map alias2CollectionPersister = new HashMap(); private final Map alias2CollectionSuffix = new HashMap(); private final Map entityPropertyResultMaps = new HashMap(); @@ -112,7 +118,7 @@ public class SQLQueryReturnProcessor { this.factory = factory; } - /*package*/ class ResultAliasContext { + public class ResultAliasContext { public SQLLoadable getEntityPersister(String alias) { return ( SQLLoadable ) alias2Persister.get( alias ); } @@ -136,6 +142,25 @@ public class SQLQueryReturnProcessor { public Map getPropertyResultsMap(String alias) { return internalGetPropertyResultsMap( alias ); } + + public String[] collectQuerySpaces() { + final HashSet spaces = new HashSet(); + collectQuerySpaces( spaces ); + return spaces.toArray( new String[ spaces.size() ] ); + } + + public void collectQuerySpaces(Collection spaces) { + for ( EntityPersister persister : alias2Persister.values() ) { + Collections.addAll( spaces, (String[]) persister.getQuerySpaces() ); + } + for ( CollectionPersister persister : alias2CollectionPersister.values() ) { + final Type elementType = persister.getElementType(); + if ( elementType.isEntityType() && ! elementType.isAnyType() ) { + final Joinable joinable = ( (EntityType) elementType ).getAssociatedJoinable( factory ); + Collections.addAll( spaces, (String[]) ( (EntityPersister) joinable ).getQuerySpaces() ); + } + } + } } private Map internalGetPropertyResultsMap(String alias) { diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/ProcedureCall.java b/hibernate-core/src/main/java/org/hibernate/procedure/ProcedureCall.java index 3ad02c4013..62ad4f01ed 100644 --- a/hibernate-core/src/main/java/org/hibernate/procedure/ProcedureCall.java +++ b/hibernate-core/src/main/java/org/hibernate/procedure/ProcedureCall.java @@ -25,6 +25,7 @@ package org.hibernate.procedure; import javax.persistence.ParameterMode; import java.util.List; +import java.util.Map; import org.hibernate.BasicQueryContract; import org.hibernate.MappingException; @@ -58,6 +59,7 @@ public interface ProcedureCall extends BasicQueryContract, SynchronizeableQuery * @param position The position * @param type The Java type of the parameter * @param mode The parameter mode (in, out, inout) + * @param The parameterized Java type of the parameter. * * @return The parameter registration memento */ @@ -89,8 +91,12 @@ public interface ProcedureCall extends BasicQueryContract, SynchronizeableQuery * @param parameterName The parameter name * @param type The Java type of the parameter * @param mode The parameter mode (in, out, inout) + * @param The parameterized Java type of the parameter. * * @return The parameter registration memento + * + * @throws NamedParametersNotSupportedException When the underlying database is known to not support + * named procedure parameters. */ public ParameterRegistration registerParameter(String parameterName, Class type, ParameterMode mode) throws NamedParametersNotSupportedException; @@ -103,6 +109,9 @@ public interface ProcedureCall extends BasicQueryContract, SynchronizeableQuery * @param mode The parameter mode (in, out, inout) * * @return The parameter registration memento + * + * @throws NamedParametersNotSupportedException When the underlying database is known to not support + * named procedure parameters. */ public ProcedureCall registerParameter0(String parameterName, Class type, ParameterMode mode) throws NamedParametersNotSupportedException; @@ -133,4 +142,12 @@ public interface ProcedureCall extends BasicQueryContract, SynchronizeableQuery */ public ProcedureResult getResult(); + /** + * Extract the disconnected representation of this call. Used in HEM to allow redefining a named query + * + * @param hints The hints to incorporate into the memento + * + * @return The memento + */ + public ProcedureCallMemento extractMemento(Map hints); } diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/ProcedureCallMemento.java b/hibernate-core/src/main/java/org/hibernate/procedure/ProcedureCallMemento.java new file mode 100644 index 0000000000..45d582d8cf --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/procedure/ProcedureCallMemento.java @@ -0,0 +1,63 @@ +/* + * 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 + */ +package org.hibernate.procedure; + +import java.util.Map; + +import org.hibernate.Session; +import org.hibernate.engine.spi.SessionImplementor; + +/** + * Represents a "memento" of a ProcedureCall + * + * @author Steve Ebersole + */ +public interface ProcedureCallMemento { + /** + * Convert the memento back into an executable (connected) form. + * + * @param session The session to connect the procedure call to + * + * @return The executable call + */ + public ProcedureCall makeProcedureCall(Session session); + + /** + * Convert the memento back into an executable (connected) form. + * + * @param session The session to connect the procedure call to + * + * @return The executable call + */ + public ProcedureCall makeProcedureCall(SessionImplementor session); + + /** + * Access to any hints associated with the memento. + *

+ * IMPL NOTE : exposed separately because only HEM needs access to this. + * + * @return The hints. + */ + public Map getHintsMap(); +} diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/AbstractParameterRegistrationImpl.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/AbstractParameterRegistrationImpl.java index 5af4950331..21081e5681 100644 --- a/hibernate-core/src/main/java/org/hibernate/procedure/internal/AbstractParameterRegistrationImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/AbstractParameterRegistrationImpl.java @@ -43,6 +43,8 @@ import org.hibernate.type.ProcedureParameterExtractionAware; import org.hibernate.type.Type; /** + * Abstract implementation of ParameterRegistration/ParameterRegistrationImplementor + * * @author Steve Ebersole */ public abstract class AbstractParameterRegistrationImpl implements ParameterRegistrationImplementor { @@ -62,28 +64,53 @@ public abstract class AbstractParameterRegistrationImpl implements ParameterR private Type hibernateType; private int[] sqlTypes; + + // positional constructors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + protected AbstractParameterRegistrationImpl( ProcedureCallImpl procedureCall, Integer position, + ParameterMode mode, + Class type) { + this( procedureCall, position, null, mode, type ); + } + + protected AbstractParameterRegistrationImpl( + ProcedureCallImpl procedureCall, + Integer position, + ParameterMode mode, Class type, - ParameterMode mode) { - this( procedureCall, position, null, type, mode ); + Type hibernateType) { + this( procedureCall, position, null, mode, type, hibernateType ); + } + + + // named constructors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + protected AbstractParameterRegistrationImpl( + ProcedureCallImpl procedureCall, + String name, + ParameterMode mode, + Class type) { + this( procedureCall, null, name, mode, type ); } protected AbstractParameterRegistrationImpl( ProcedureCallImpl procedureCall, String name, + ParameterMode mode, Class type, - ParameterMode mode) { - this( procedureCall, null, name, type, mode ); + Type hibernateType) { + this( procedureCall, null, name, mode, type, hibernateType ); } private AbstractParameterRegistrationImpl( ProcedureCallImpl procedureCall, Integer position, String name, + ParameterMode mode, Class type, - ParameterMode mode) { + Type hibernateType) { this.procedureCall = procedureCall; this.position = position; @@ -92,7 +119,23 @@ public abstract class AbstractParameterRegistrationImpl implements ParameterR this.mode = mode; this.type = type; - setHibernateType( session().getFactory().getTypeResolver().heuristicType( type.getName() ) ); + setHibernateType( hibernateType ); + } + + private AbstractParameterRegistrationImpl( + ProcedureCallImpl procedureCall, + Integer position, + String name, + ParameterMode mode, + Class type) { + this( + procedureCall, + position, + name, + mode, + type, + procedureCall.getSession().getFactory().getTypeResolver().heuristicType( type.getName() ) + ); } protected SessionImplementor session() { @@ -119,6 +162,11 @@ public abstract class AbstractParameterRegistrationImpl implements ParameterR return mode; } + @Override + public Type getHibernateType() { + return hibernateType; + } + @Override public void setHibernateType(Type type) { if ( type == null ) { @@ -129,6 +177,7 @@ public abstract class AbstractParameterRegistrationImpl implements ParameterR } @Override + @SuppressWarnings("unchecked") public ParameterBind getBind() { return bind; } @@ -175,11 +224,12 @@ public abstract class AbstractParameterRegistrationImpl implements ParameterR if ( mode == ParameterMode.IN || mode == ParameterMode.INOUT || mode == ParameterMode.OUT ) { if ( mode == ParameterMode.INOUT || mode == ParameterMode.OUT ) { if ( sqlTypes.length > 1 ) { - if ( ProcedureParameterExtractionAware.class.isInstance( hibernateType ) - && ( (ProcedureParameterExtractionAware) hibernateType ).canDoExtraction() ) { - // the type can handle multi-param extraction... - } - else { + // there is more than one column involved; see if the Hibernate Type can handle + // multi-param extraction... + final boolean canHandleMultiParamExtraction = + ProcedureParameterExtractionAware.class.isInstance( hibernateType ) + && ( (ProcedureParameterExtractionAware) hibernateType ).canDoExtraction(); + if ( ! canHandleMultiParamExtraction ) { // it cannot... throw new UnsupportedOperationException( "Type [" + hibernateType + "] does support multi-parameter value extraction" diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/NamedParameterRegistration.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/NamedParameterRegistration.java index d3a772cb70..6f9321426a 100644 --- a/hibernate-core/src/main/java/org/hibernate/procedure/internal/NamedParameterRegistration.java +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/NamedParameterRegistration.java @@ -25,15 +25,28 @@ package org.hibernate.procedure.internal; import javax.persistence.ParameterMode; +import org.hibernate.type.Type; + /** + * Represents a registered named parameter + * * @author Steve Ebersole */ public class NamedParameterRegistration extends AbstractParameterRegistrationImpl { - public NamedParameterRegistration( + NamedParameterRegistration( ProcedureCallImpl procedureCall, String name, + ParameterMode mode, + Class type) { + super( procedureCall, name, mode, type ); + } + + NamedParameterRegistration( + ProcedureCallImpl procedureCall, + String name, + ParameterMode mode, Class type, - ParameterMode mode) { - super( procedureCall, name, type, mode ); + Type hibernateType) { + super( procedureCall, name, mode, type, hibernateType ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/ParameterRegistrationImplementor.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ParameterRegistrationImplementor.java index 0d1992d8a3..e349e6649e 100644 --- a/hibernate-core/src/main/java/org/hibernate/procedure/internal/ParameterRegistrationImplementor.java +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ParameterRegistrationImplementor.java @@ -27,15 +27,45 @@ import java.sql.CallableStatement; import java.sql.SQLException; import org.hibernate.procedure.ParameterRegistration; +import org.hibernate.type.Type; /** + * Additional internal contract for ParameterRegistration + * * @author Steve Ebersole */ public interface ParameterRegistrationImplementor extends ParameterRegistration { + /** + * Prepare for execution. + * + * @param statement The statement about to be executed + * @param i The parameter index for this registration (used for positional) + * + * @throws SQLException Indicates a problem accessing the statement object + */ public void prepare(CallableStatement statement, int i) throws SQLException; + /** + * Access to the Hibernate type for this parameter registration + * + * @return The Hibernate Type + */ + public Type getHibernateType(); + + /** + * Access to the SQL type(s) for this parameter + * + * @return The SQL types (JDBC type codes) + */ public int[] getSqlTypes(); + /** + * Extract value from the statement after execution (used for OUT/INOUT parameters). + * + * @param statement The callable statement + * + * @return The extracted value + */ public T extract(CallableStatement statement); } diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/ParameterStrategy.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ParameterStrategy.java index bf517dc3f5..f329d46208 100644 --- a/hibernate-core/src/main/java/org/hibernate/procedure/internal/ParameterStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ParameterStrategy.java @@ -27,7 +27,16 @@ package org.hibernate.procedure.internal; * The style/strategy of parameter registration used in a particular procedure call definition. */ public enum ParameterStrategy { + /** + * The parameters are named + */ NAMED, + /** + * The parameters are positional + */ POSITIONAL, + /** + * We do not (yet) know + */ UNKNOWN } diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/PositionalParameterRegistration.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/PositionalParameterRegistration.java index a991525c58..64e63aab35 100644 --- a/hibernate-core/src/main/java/org/hibernate/procedure/internal/PositionalParameterRegistration.java +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/PositionalParameterRegistration.java @@ -25,15 +25,28 @@ package org.hibernate.procedure.internal; import javax.persistence.ParameterMode; +import org.hibernate.type.Type; + /** + * Represents a registered positional parameter + * * @author Steve Ebersole */ public class PositionalParameterRegistration extends AbstractParameterRegistrationImpl { - public PositionalParameterRegistration( + PositionalParameterRegistration( ProcedureCallImpl procedureCall, Integer position, + ParameterMode mode, + Class type) { + super( procedureCall, position, mode, type ); + } + + PositionalParameterRegistration( + ProcedureCallImpl procedureCall, + Integer position, + ParameterMode mode, Class type, - ParameterMode mode) { - super( procedureCall, position, type, mode ); + Type hibernateType) { + super( procedureCall, position, mode, type, hibernateType ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallImpl.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallImpl.java index 0f82a10e6c..0c878894d2 100644 --- a/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallImpl.java @@ -31,25 +31,28 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; +import org.jboss.logging.Logger; + import org.hibernate.HibernateException; -import org.hibernate.LockMode; -import org.hibernate.MappingException; import org.hibernate.QueryException; import org.hibernate.cfg.NotYetImplementedException; import org.hibernate.engine.ResultSetMappingDefinition; import org.hibernate.engine.jdbc.spi.ExtractedDatabaseMetaData; import org.hibernate.engine.query.spi.sql.NativeSQLQueryReturn; -import org.hibernate.engine.query.spi.sql.NativeSQLQueryRootReturn; import org.hibernate.engine.spi.QueryParameters; +import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.internal.AbstractBasicQueryContractImpl; import org.hibernate.internal.util.StringHelper; +import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.persister.entity.EntityPersister; -import org.hibernate.procedure.ProcedureCall; import org.hibernate.procedure.NamedParametersNotSupportedException; import org.hibernate.procedure.ParameterRegistration; +import org.hibernate.procedure.ProcedureCall; +import org.hibernate.procedure.ProcedureCallMemento; import org.hibernate.procedure.ProcedureResult; import org.hibernate.result.spi.ResultContext; import org.hibernate.type.Type; @@ -60,6 +63,10 @@ import org.hibernate.type.Type; * @author Steve Ebersole */ public class ProcedureCallImpl extends AbstractBasicQueryContractImpl implements ProcedureCall, ResultContext { + private static final Logger log = Logger.getLogger( ProcedureCallImpl.class ); + + private static final NativeSQLQueryReturn[] NO_RETURNS = new NativeSQLQueryReturn[0]; + private final String procedureName; private final NativeSQLQueryReturn[] queryReturns; @@ -70,74 +77,167 @@ public class ProcedureCallImpl extends AbstractBasicQueryContractImpl implements private ProcedureResultImpl outputs; - - @SuppressWarnings("unchecked") + /** + * The no-returns form. + * + * @param session The session + * @param procedureName The name of the procedure to call + */ public ProcedureCallImpl(SessionImplementor session, String procedureName) { - this( session, procedureName, (List) null ); + super( session ); + this.procedureName = procedureName; + this.queryReturns = NO_RETURNS; } - public ProcedureCallImpl(SessionImplementor session, String procedureName, List queryReturns) { + /** + * The result Class(es) return form + * + * @param session The session + * @param procedureName The name of the procedure to call + * @param resultClasses The classes making up the result + */ + public ProcedureCallImpl(final SessionImplementor session, String procedureName, Class... resultClasses) { super( session ); this.procedureName = procedureName; - if ( queryReturns == null || queryReturns.isEmpty() ) { - this.queryReturns = new NativeSQLQueryReturn[0]; - } - else { - this.queryReturns = queryReturns.toArray( new NativeSQLQueryReturn[ queryReturns.size() ] ); - } + final List collectedQueryReturns = new ArrayList(); + final Set collectedQuerySpaces = new HashSet(); + + Util.resolveResultClasses( + new Util.ResultClassesResolutionContext() { + @Override + public SessionFactoryImplementor getSessionFactory() { + return session.getFactory(); + } + + @Override + public void addQueryReturns(NativeSQLQueryReturn... queryReturns) { + Collections.addAll( collectedQueryReturns, queryReturns ); + } + + @Override + public void addQuerySpaces(String... spaces) { + Collections.addAll( collectedQuerySpaces, spaces ); + } + }, + resultClasses + ); + + this.queryReturns = collectedQueryReturns.toArray( new NativeSQLQueryReturn[ collectedQueryReturns.size() ] ); + this.synchronizedQuerySpaces = collectedQuerySpaces; } - public ProcedureCallImpl(SessionImplementor session, String procedureName, Class... resultClasses) { - this( session, procedureName, collectQueryReturns( resultClasses ) ); + /** + * The result-set-mapping(s) return form + * + * @param session The session + * @param procedureName The name of the procedure to call + * @param resultSetMappings The names of the result set mappings making up the result + */ + public ProcedureCallImpl(final SessionImplementor session, String procedureName, String... resultSetMappings) { + super( session ); + this.procedureName = procedureName; + + final List collectedQueryReturns = new ArrayList(); + final Set collectedQuerySpaces = new HashSet(); + + Util.resolveResultSetMappings( + new Util.ResultSetMappingResolutionContext() { + @Override + public SessionFactoryImplementor getSessionFactory() { + return session.getFactory(); + } + + @Override + public ResultSetMappingDefinition findResultSetMapping(String name) { + return session.getFactory().getResultSetMapping( name ); + } + + @Override + public void addQueryReturns(NativeSQLQueryReturn... queryReturns) { + Collections.addAll( collectedQueryReturns, queryReturns ); + } + + @Override + public void addQuerySpaces(String... spaces) { + Collections.addAll( collectedQuerySpaces, spaces ); + } + }, + resultSetMappings + ); + + this.queryReturns = collectedQueryReturns.toArray( new NativeSQLQueryReturn[ collectedQueryReturns.size() ] ); + this.synchronizedQuerySpaces = collectedQuerySpaces; } - private static List collectQueryReturns(Class[] resultClasses) { - if ( resultClasses == null || resultClasses.length == 0 ) { - return null; + /** + * The named/stored copy constructor + * + * @param session The session + * @param memento The named/stored memento + */ + @SuppressWarnings("unchecked") + ProcedureCallImpl(SessionImplementor session, ProcedureCallMementoImpl memento) { + super( session ); + this.procedureName = memento.getProcedureName(); + + this.queryReturns = memento.getQueryReturns(); + this.synchronizedQuerySpaces = Util.copy( memento.getSynchronizedQuerySpaces() ); + this.parameterStrategy = memento.getParameterStrategy(); + if ( parameterStrategy == ParameterStrategy.UNKNOWN ) { + // nothing else to do in this case + return; } - List queryReturns = new ArrayList( resultClasses.length ); - int i = 1; - for ( Class resultClass : resultClasses ) { - queryReturns.add( new NativeSQLQueryRootReturn( "alias" + i, resultClass.getName(), LockMode.READ ) ); - i++; - } - return queryReturns; - } - - public ProcedureCallImpl(SessionImplementor session, String procedureName, String... resultSetMappings) { - this( session, procedureName, collectQueryReturns( session, resultSetMappings ) ); - } - - private static List collectQueryReturns(SessionImplementor session, String[] resultSetMappings) { - if ( resultSetMappings == null || resultSetMappings.length == 0 ) { - return null; + final List storedRegistrations = memento.getParameterDeclarations(); + if ( storedRegistrations == null ) { + // most likely a problem if ParameterStrategy is not UNKNOWN... + log.debugf( + "ParameterStrategy was [%s] on named copy [%s], but no parameters stored", + parameterStrategy, + procedureName + ); + return; } - List queryReturns = new ArrayList( resultSetMappings.length ); - for ( String resultSetMapping : resultSetMappings ) { - ResultSetMappingDefinition mapping = session.getFactory().getResultSetMapping( resultSetMapping ); - if ( mapping == null ) { - throw new MappingException( "Unknown SqlResultSetMapping [" + resultSetMapping + "]" ); + final List> parameterRegistrations = + CollectionHelper.arrayList( storedRegistrations.size() ); + + for ( ProcedureCallMementoImpl.ParameterMemento storedRegistration : storedRegistrations ) { + final ParameterRegistrationImplementor registration; + if ( StringHelper.isNotEmpty( storedRegistration.getName() ) ) { + if ( parameterStrategy != ParameterStrategy.NAMED ) { + throw new IllegalStateException( + "Found named stored procedure parameter associated with positional parameters" + ); + } + registration = new NamedParameterRegistration( + this, + storedRegistration.getName(), + storedRegistration.getMode(), + storedRegistration.getType(), + storedRegistration.getHibernateType() + ); } - queryReturns.addAll( Arrays.asList( mapping.getQueryReturns() ) ); + else { + if ( parameterStrategy != ParameterStrategy.POSITIONAL ) { + throw new IllegalStateException( + "Found named stored procedure parameter associated with positional parameters" + ); + } + registration = new PositionalParameterRegistration( + this, + storedRegistration.getPosition(), + storedRegistration.getMode(), + storedRegistration.getType(), + storedRegistration.getHibernateType() + ); + } + parameterRegistrations.add( registration ); } - return queryReturns; + this.registeredParameters = parameterRegistrations; } -// public ProcedureCallImpl( -// SessionImplementor session, -// String procedureName, -// List parameters) { -// // this form is intended for named stored procedure calls. -// // todo : introduce a NamedProcedureCallDefinition object to hold all needed info and pass that in here; will help with EM.addNamedQuery as well.. -// this( session, procedureName ); -// for ( StoredProcedureParameter parameter : parameters ) { -// registerParameter( (StoredProcedureParameterImplementor) parameter ); -// } -// } - @Override public SessionImplementor getSession() { return super.session(); @@ -165,7 +265,8 @@ public class ProcedureCallImpl extends AbstractBasicQueryContractImpl implements @Override @SuppressWarnings("unchecked") public ParameterRegistration registerParameter(int position, Class type, ParameterMode mode) { - final PositionalParameterRegistration parameterRegistration = new PositionalParameterRegistration( this, position, type, mode ); + final PositionalParameterRegistration parameterRegistration = + new PositionalParameterRegistration( this, position, mode, type ); registerParameter( parameterRegistration ); return parameterRegistration; } @@ -233,7 +334,8 @@ public class ProcedureCallImpl extends AbstractBasicQueryContractImpl implements @Override @SuppressWarnings("unchecked") public ParameterRegistration registerParameter(String name, Class type, ParameterMode mode) { - final NamedParameterRegistration parameterRegistration = new NamedParameterRegistration( this, name, type, mode ); + final NamedParameterRegistration parameterRegistration + = new NamedParameterRegistration( this, name, mode, type ); registerParameter( parameterRegistration ); return parameterRegistration; } @@ -329,6 +431,12 @@ public class ProcedureCallImpl extends AbstractBasicQueryContractImpl implements throw new NotYetImplementedException(); } + /** + * Use this form instead of {@link #getSynchronizedQuerySpaces()} when you want to make sure the + * underlying Set is instantiated (aka, on add) + * + * @return The spaces + */ protected Set synchronizedQuerySpaces() { if ( synchronizedQuerySpaces == null ) { synchronizedQuerySpaces = new HashSet(); @@ -374,6 +482,7 @@ public class ProcedureCallImpl extends AbstractBasicQueryContractImpl implements return buildQueryParametersObject(); } + @Override public QueryParameters buildQueryParametersObject() { QueryParameters qp = super.buildQueryParametersObject(); // both of these are for documentation purposes, they are actually handled directly... @@ -382,8 +491,13 @@ public class ProcedureCallImpl extends AbstractBasicQueryContractImpl implements return qp; } + /** + * Collects any parameter registrations which indicate a REF_CURSOR parameter type/mode. + * + * @return The collected REF_CURSOR type parameters. + */ public ParameterRegistrationImplementor[] collectRefCursorParameters() { - List refCursorParams = new ArrayList(); + final List refCursorParams = new ArrayList(); for ( ParameterRegistrationImplementor param : registeredParameters ) { if ( param.getMode() == ParameterMode.REF_CURSOR ) { refCursorParams.add( param ); @@ -391,4 +505,29 @@ public class ProcedureCallImpl extends AbstractBasicQueryContractImpl implements } return refCursorParams.toArray( new ParameterRegistrationImplementor[refCursorParams.size()] ); } + + @Override + public ProcedureCallMemento extractMemento(Map hints) { + return new ProcedureCallMementoImpl( + procedureName, + Util.copy( queryReturns ), + parameterStrategy, + toParameterMementos( registeredParameters ), + Util.copy( synchronizedQuerySpaces ), + Util.copy( hints ) + ); + } + + + private static List toParameterMementos(List> registeredParameters) { + if ( registeredParameters == null ) { + return null; + } + + final List copy = CollectionHelper.arrayList( registeredParameters.size() ); + for ( ParameterRegistrationImplementor registration : registeredParameters ) { + copy.add( ProcedureCallMementoImpl.ParameterMemento.fromRegistration( registration ) ); + } + return copy; + } } diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallMementoImpl.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallMementoImpl.java new file mode 100644 index 0000000000..7af100283e --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallMementoImpl.java @@ -0,0 +1,169 @@ +/* + * 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 + */ +package org.hibernate.procedure.internal; + +import javax.persistence.ParameterMode; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.engine.query.spi.sql.NativeSQLQueryReturn; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.procedure.ProcedureCall; +import org.hibernate.procedure.ProcedureCallMemento; +import org.hibernate.type.Type; + +/** + * Implementation of ProcedureCallMemento + * + * @author Steve Ebersole + */ +public class ProcedureCallMementoImpl implements ProcedureCallMemento { + private final String procedureName; + private final NativeSQLQueryReturn[] queryReturns; + + private final ParameterStrategy parameterStrategy; + private final List parameterDeclarations; + + private final Set synchronizedQuerySpaces; + + private final Map hintsMap; + + public ProcedureCallMementoImpl( + String procedureName, + NativeSQLQueryReturn[] queryReturns, + ParameterStrategy parameterStrategy, + List parameterDeclarations, + Set synchronizedQuerySpaces, + Map hintsMap) { + this.procedureName = procedureName; + this.queryReturns = queryReturns; + this.parameterStrategy = parameterStrategy; + this.parameterDeclarations = parameterDeclarations; + this.synchronizedQuerySpaces = synchronizedQuerySpaces; + this.hintsMap = hintsMap; + } + + @Override + public ProcedureCall makeProcedureCall(Session session) { + return new ProcedureCallImpl( (SessionImplementor) session, this ); + } + + @Override + public ProcedureCall makeProcedureCall(SessionImplementor session) { + return new ProcedureCallImpl( session, this ); + } + + public String getProcedureName() { + return procedureName; + } + + public NativeSQLQueryReturn[] getQueryReturns() { + return queryReturns; + } + + public ParameterStrategy getParameterStrategy() { + return parameterStrategy; + } + + public List getParameterDeclarations() { + return parameterDeclarations; + } + + public Set getSynchronizedQuerySpaces() { + return synchronizedQuerySpaces; + } + + @Override + public Map getHintsMap() { + return hintsMap; + } + + /** + * A "disconnected" copy of the metadata for a parameter, that can be used in ProcedureCallMementoImpl. + */ + public static class ParameterMemento { + private final Integer position; + private final String name; + private final ParameterMode mode; + private final Class type; + private final Type hibernateType; + + /** + * Create the memento + * + * @param position The parameter position + * @param name The parameter name + * @param mode The parameter mode + * @param type The Java type of the parameter + * @param hibernateType The Hibernate Type. + */ + public ParameterMemento(int position, String name, ParameterMode mode, Class type, Type hibernateType) { + this.position = position; + this.name = name; + this.mode = mode; + this.type = type; + this.hibernateType = hibernateType; + } + + public Integer getPosition() { + return position; + } + + public String getName() { + return name; + } + + public ParameterMode getMode() { + return mode; + } + + public Class getType() { + return type; + } + + public Type getHibernateType() { + return hibernateType; + } + + /** + * Build a ParameterMemento from the given parameter registration + * + * @param registration The parameter registration from a ProcedureCall + * + * @return The memento + */ + public static ParameterMemento fromRegistration(ParameterRegistrationImplementor registration) { + return new ParameterMemento( + registration.getPosition(), + registration.getName(), + registration.getMode(), + registration.getType(), + registration.getHibernateType() + ); + } + + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/Util.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/Util.java new file mode 100644 index 0000000000..36e6ffe66f --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/Util.java @@ -0,0 +1,116 @@ +/* + * 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 + */ +package org.hibernate.procedure.internal; + +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +import org.hibernate.LockMode; +import org.hibernate.MappingException; +import org.hibernate.engine.ResultSetMappingDefinition; +import org.hibernate.engine.query.spi.sql.NativeSQLQueryReturn; +import org.hibernate.engine.query.spi.sql.NativeSQLQueryRootReturn; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.internal.util.collections.CollectionHelper; +import org.hibernate.loader.custom.sql.SQLQueryReturnProcessor; +import org.hibernate.persister.entity.EntityPersister; + +/** + * @author Steve Ebersole + */ +public class Util { + private Util() { + } + + /** + * Makes a copy of the given query return array. + * + * @param queryReturns The returns to copy + * + * @return The copy + */ + static NativeSQLQueryReturn[] copy(NativeSQLQueryReturn[] queryReturns) { + if ( queryReturns == null ) { + return new NativeSQLQueryReturn[0]; + } + + final NativeSQLQueryReturn[] copy = new NativeSQLQueryReturn[ queryReturns.length ]; + System.arraycopy( queryReturns, 0, copy, 0, queryReturns.length ); + return copy; + } + + public static Set copy(Set synchronizedQuerySpaces) { + return CollectionHelper.makeCopy( synchronizedQuerySpaces ); + } + + public static Map copy(Map hints) { + return CollectionHelper.makeCopy( hints ); + } + + public static interface ResultSetMappingResolutionContext { + public SessionFactoryImplementor getSessionFactory(); + public ResultSetMappingDefinition findResultSetMapping(String name); + public void addQueryReturns(NativeSQLQueryReturn... queryReturns); + public void addQuerySpaces(String... spaces); + } + + public static void resolveResultSetMappings(ResultSetMappingResolutionContext context, String... resultSetMappingNames) { + for ( String resultSetMappingName : resultSetMappingNames ) { + final ResultSetMappingDefinition mapping = context.findResultSetMapping( resultSetMappingName ); + if ( mapping == null ) { + throw new MappingException( "Unknown SqlResultSetMapping [" + resultSetMappingName + "]" ); + } + + context.addQueryReturns( mapping.getQueryReturns() ); + + final SQLQueryReturnProcessor processor = + new SQLQueryReturnProcessor( mapping.getQueryReturns(), context.getSessionFactory() ); + final SQLQueryReturnProcessor.ResultAliasContext processResult = processor.process(); + context.addQuerySpaces( processResult.collectQuerySpaces() ); + } + } + + public static interface ResultClassesResolutionContext { + public SessionFactoryImplementor getSessionFactory(); + public void addQueryReturns(NativeSQLQueryReturn... queryReturns); + public void addQuerySpaces(String... spaces); + } + + public static void resolveResultClasses(ResultClassesResolutionContext context, Class... resultClasses) { + int i = 1; + for ( Class resultClass : resultClasses ) { + context.addQueryReturns( + new NativeSQLQueryRootReturn( "alias" + i, resultClass.getName(), LockMode.READ ) + ); + try { + final EntityPersister persister = context.getSessionFactory().getEntityPersister( resultClass.getName() ); + context.addQuerySpaces( (String[]) persister.getQuerySpaces() ); + } + catch (Exception ignore) { + + } + } + } +} diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/internal/EntityManagerFactoryImpl.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/internal/EntityManagerFactoryImpl.java index a94c3228aa..07da96f48b 100755 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/internal/EntityManagerFactoryImpl.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/internal/EntityManagerFactoryImpl.java @@ -75,6 +75,7 @@ import org.hibernate.jpa.internal.metamodel.MetamodelImpl; import org.hibernate.jpa.internal.util.PersistenceUtilHelper; import org.hibernate.mapping.PersistentClass; import org.hibernate.metadata.ClassMetadata; +import org.hibernate.procedure.ProcedureCall; import org.hibernate.service.ServiceRegistry; /** @@ -284,19 +285,25 @@ public class EntityManagerFactoryImpl implements HibernateEntityManagerFactory { throw new IllegalStateException( "EntityManagerFactory is closed" ); } - if ( ! HibernateQuery.class.isInstance( query ) ) { + if ( StoredProcedureQueryImpl.class.isInstance( query ) ) { + final ProcedureCall procedureCall = ( (StoredProcedureQueryImpl) query ).getHibernateProcedureCall(); + sessionFactory.getNamedQueryRepository().registerNamedProcedureCallMemento( name, procedureCall.extractMemento( query.getHints() ) ); + } + else if ( ! HibernateQuery.class.isInstance( query ) ) { throw new PersistenceException( "Cannot use query non-Hibernate EntityManager query as basis for named query" ); } - - // create and register the proper NamedQueryDefinition... - final org.hibernate.Query hibernateQuery = ( (HibernateQuery) query ).getHibernateQuery(); - if ( org.hibernate.SQLQuery.class.isInstance( hibernateQuery ) ) { - final NamedSQLQueryDefinition namedQueryDefinition = extractSqlQueryDefinition( ( org.hibernate.SQLQuery ) hibernateQuery, name ); - sessionFactory.registerNamedSQLQueryDefinition( name, namedQueryDefinition ); - } else { - final NamedQueryDefinition namedQueryDefinition = extractHqlQueryDefinition( hibernateQuery, name ); - sessionFactory.registerNamedQueryDefinition( name, namedQueryDefinition ); + // create and register the proper NamedQueryDefinition... + final org.hibernate.Query hibernateQuery = ( (HibernateQuery) query ).getHibernateQuery(); + if ( org.hibernate.SQLQuery.class.isInstance( hibernateQuery ) ) { + sessionFactory.registerNamedSQLQueryDefinition( + name, + extractSqlQueryDefinition( (org.hibernate.SQLQuery) hibernateQuery, name ) + ); + } + else { + sessionFactory.registerNamedQueryDefinition( name, extractHqlQueryDefinition( hibernateQuery, name ) ); + } } } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/internal/StoredProcedureQueryImpl.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/internal/StoredProcedureQueryImpl.java index aa9ddd912b..b232696774 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/internal/StoredProcedureQueryImpl.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/internal/StoredProcedureQueryImpl.java @@ -298,6 +298,10 @@ public class StoredProcedureQueryImpl extends BaseQueryImpl implements StoredPro return false; } + public ProcedureCall getHibernateProcedureCall() { + return procedureCall; + } + private static class ParameterRegistrationImpl implements ParameterRegistration { private final org.hibernate.procedure.ParameterRegistration nativeParamRegistration; diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/spi/AbstractEntityManagerImpl.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/spi/AbstractEntityManagerImpl.java index e7745f4081..369bbbe829 100755 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/spi/AbstractEntityManagerImpl.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/spi/AbstractEntityManagerImpl.java @@ -124,6 +124,7 @@ import org.hibernate.jpa.internal.TransactionImpl; import org.hibernate.jpa.internal.util.CacheModeHelper; import org.hibernate.jpa.internal.util.ConfigurationHelper; import org.hibernate.jpa.internal.util.LockModeTypeHelper; +import org.hibernate.procedure.ProcedureCallMemento; import org.hibernate.proxy.HibernateProxy; import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; import org.hibernate.transform.BasicTransformerAdapter; @@ -820,7 +821,7 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage public Query createNativeQuery(String sqlString, String resultSetMapping) { checkOpen(); try { - SQLQuery q = internalGetSession().createSQLQuery( sqlString ); + final SQLQuery q = internalGetSession().createSQLQuery( sqlString ); q.setResultSetMapping( resultSetMapping ); return new QueryImpl( q, this ); } @@ -832,15 +833,30 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage @Override public StoredProcedureQuery createNamedStoredProcedureQuery(String name) { checkOpen(); - throw new NotYetImplementedException(); + final ProcedureCallMemento memento = ( (SessionImplementor) internalGetSession() ).getFactory() + .getNamedQueryRepository().getNamedProcedureCallMemento( name ); + if ( memento == null ) { + throw new IllegalArgumentException( "No @NamedStoredProcedureQuery was found with that name : " + name ); + } + final ProcedureCall procedureCall = memento.makeProcedureCall( internalGetSession() ); + final StoredProcedureQueryImpl jpaImpl = new StoredProcedureQueryImpl( procedureCall, this ); + // apply hints + if ( memento.getHintsMap() != null ) { + for ( Map.Entry hintEntry : memento.getHintsMap().entrySet() ) { + jpaImpl.setHint( hintEntry.getKey(), hintEntry.getValue() ); + } + } + return jpaImpl; } @Override public StoredProcedureQuery createStoredProcedureQuery(String procedureName) { checkOpen(); try { - ProcedureCall procedureCall = internalGetSession().createStoredProcedureCall( procedureName ); - return new StoredProcedureQueryImpl( procedureCall, this ); + return new StoredProcedureQueryImpl( + internalGetSession().createStoredProcedureCall( procedureName ), + this + ); } catch ( HibernateException he ) { throw convert( he ); @@ -851,8 +867,10 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage public StoredProcedureQuery createStoredProcedureQuery(String procedureName, Class... resultClasses) { checkOpen(); try { - ProcedureCall procedureCall = internalGetSession().createStoredProcedureCall( procedureName, resultClasses ); - return new StoredProcedureQueryImpl( procedureCall, this ); + return new StoredProcedureQueryImpl( + internalGetSession().createStoredProcedureCall( procedureName, resultClasses ), + this + ); } catch ( HibernateException he ) { throw convert( he ); @@ -862,7 +880,15 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage @Override public StoredProcedureQuery createStoredProcedureQuery(String procedureName, String... resultSetMappings) { checkOpen(); - throw new NotYetImplementedException(); + try { + return new StoredProcedureQueryImpl( + internalGetSession().createStoredProcedureCall( procedureName, resultSetMappings ), + this + ); + } + catch ( HibernateException he ) { + throw convert( he ); + } } @Override From 0ff155d065b41ae212b303b8228b561425b9f17b Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Thu, 9 May 2013 14:52:54 -0500 Subject: [PATCH 16/25] HHH-8231 - Pass along IOException as cause when trying to open script outputs --- .../jpa/internal/schemagen/GenerationTargetToScript.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/internal/schemagen/GenerationTargetToScript.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/internal/schemagen/GenerationTargetToScript.java index da7f140c6a..677e38cb07 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/internal/schemagen/GenerationTargetToScript.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/internal/schemagen/GenerationTargetToScript.java @@ -189,7 +189,7 @@ class GenerationTargetToScript implements GenerationTarget { return new FileWriter( file ); } catch (IOException e) { - throw new PersistenceException( "Unable to open specified script target file for writing : " + fileUrl ); + throw new PersistenceException( "Unable to open specified script target file for writing : " + fileUrl, e ); } } } From ab47eae5b9657dbc6fef57f068822182d9621cd0 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Wed, 8 May 2013 16:18:42 -0400 Subject: [PATCH 17/25] HHH-8211 Fixed checkstyle issues in hibernate-ehcache module --- .../EhcacheTransactionalDataRegion.java | 8 +- .../management/impl/AbstractEmitterBean.java | 3 + .../management/impl/CacheRegionUtils.java | 2 +- .../management/impl/EhcacheHibernate.java | 75 ++++++++- .../EhcacheHibernateMBeanRegistration.java | 8 +- ...EhcacheHibernateMBeanRegistrationImpl.java | 19 ++- .../impl/EhcacheHibernateMbeanNames.java | 9 +- .../management/impl/EhcacheStatsImpl.java | 146 ++++++++++++------ .../ehcache/management/impl/EntityStats.java | 50 ++++-- .../management/impl/HibernateStatsImpl.java | 70 ++++++--- .../management/impl/NullHibernateStats.java | 31 ++++ .../impl/ProviderMBeanRegistrationHelper.java | 22 +-- .../ehcache/management/impl/QueryStats.java | 64 ++++---- 13 files changed, 365 insertions(+), 142 deletions(-) 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 d46513cbe6..fdd4c1f375 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 @@ -217,7 +217,7 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements * * @throws CacheException Indicates a problem accessing the cache */ - public final void writeLock(Object key) { + public final void writeLock(Object key) throws CacheException { try { lockProvider.getSyncForKey( key ).lock( LockType.WRITE ); } @@ -239,7 +239,7 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements * * @throws CacheException Indicates a problem accessing the cache */ - public final void writeUnlock(Object key) { + public final void writeUnlock(Object key) throws CacheException { try { lockProvider.getSyncForKey( key ).unlock( LockType.WRITE ); } @@ -261,7 +261,7 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements * * @throws CacheException Indicates a problem accessing the cache */ - public final void readLock(Object key) { + public final void readLock(Object key) throws CacheException { try { lockProvider.getSyncForKey( key ).lock( LockType.WRITE ); } @@ -283,7 +283,7 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements * * @throws CacheException Indicates a problem accessing the cache */ - public final void readUnlock(Object key) { + public final void readUnlock(Object key) throws CacheException { try { lockProvider.getSyncForKey( key ).unlock( LockType.WRITE ); } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java index 5d3f3abc31..d3e4245abe 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java @@ -138,6 +138,9 @@ public abstract class AbstractEmitterBean extends StandardMBean implements Notif notificationListeners.clear(); } + /** + * {@inheritDoc} + */ @Override public abstract MBeanNotificationInfo[] getNotificationInfo(); 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 267486a6a2..8ce621b7e5 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 @@ -95,7 +95,7 @@ public abstract class CacheRegionUtils { } boolean truncate = true; for ( int i = 0; i < comps.length; i++ ) { - String comp = comps[i]; + final String comp = comps[i]; final char c = comp.charAt( 0 ); if ( truncate && Character.isUpperCase( c ) ) { truncate = false; 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 a978ff6140..f03788cb75 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 @@ -63,7 +63,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe * * @param manager the backing {@link CacheManager} * - * @throws NotCompliantMBeanException + * @throws NotCompliantMBeanException if bean doesn't comply */ public EhcacheHibernate(CacheManager manager) throws NotCompliantMBeanException { super( EhcacheHibernateMBean.class ); @@ -72,12 +72,13 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * Enable hibernate statistics with the input session factory + * @param sessionFactory the session factory to enable stats for */ public void enableHibernateStatistics(SessionFactory sessionFactory) { try { hibernateStats = new HibernateStatsImpl( sessionFactory ); } - catch (Exception e) { + catch ( Exception e ) { throw new RuntimeException( e ); } } @@ -85,6 +86,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public boolean isHibernateStatisticsSupported() { return hibernateStats instanceof HibernateStatsImpl; } @@ -92,6 +94,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public void setStatisticsEnabled(boolean flag) { if ( flag ) { ehcacheStats.enableStats(); @@ -108,6 +111,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public boolean isStatisticsEnabled() { return statsEnabled.get(); } @@ -115,6 +119,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public void clearStats() { ehcacheStats.clearStats(); hibernateStats.clearStats(); @@ -123,6 +128,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public void disableStats() { setStatisticsEnabled( false ); } @@ -130,6 +136,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public void enableStats() { setStatisticsEnabled( true ); } @@ -137,6 +144,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public void flushRegionCache(String region) { ehcacheStats.flushRegionCache( region ); sendNotification( HibernateStats.CACHE_REGION_FLUSHED, region ); @@ -145,6 +153,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public void flushRegionCaches() { ehcacheStats.flushRegionCaches(); sendNotification( HibernateStats.CACHE_FLUSHED ); @@ -153,6 +162,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public String generateActiveConfigDeclaration() { return ehcacheStats.generateActiveConfigDeclaration(); } @@ -160,6 +170,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public String generateActiveConfigDeclaration(String region) { return ehcacheStats.generateActiveConfigDeclaration( region ); } @@ -167,6 +178,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getCacheHitCount() { return ehcacheStats.getCacheHitCount(); } @@ -174,6 +186,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public double getCacheHitRate() { return ehcacheStats.getCacheHitRate(); } @@ -181,6 +194,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getCacheHitSample() { return ehcacheStats.getCacheHitSample(); } @@ -188,6 +202,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getCacheMissCount() { return ehcacheStats.getCacheMissCount(); } @@ -195,6 +210,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public double getCacheMissRate() { return ehcacheStats.getCacheMissRate(); } @@ -202,6 +218,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getCacheMissSample() { return ehcacheStats.getCacheMissSample(); } @@ -209,6 +226,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getCachePutCount() { return ehcacheStats.getCachePutCount(); } @@ -216,6 +234,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public double getCachePutRate() { return ehcacheStats.getCachePutRate(); } @@ -223,6 +242,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getCachePutSample() { return ehcacheStats.getCachePutSample(); } @@ -230,6 +250,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public TabularData getCacheRegionStats() { return hibernateStats.getCacheRegionStats(); } @@ -237,6 +258,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getCloseStatementCount() { return hibernateStats.getCloseStatementCount(); } @@ -244,6 +266,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public TabularData getCollectionStats() { return hibernateStats.getCollectionStats(); } @@ -251,6 +274,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getConnectCount() { return hibernateStats.getConnectCount(); } @@ -258,6 +282,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public TabularData getEntityStats() { return hibernateStats.getEntityStats(); } @@ -265,6 +290,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getFlushCount() { return hibernateStats.getFlushCount(); } @@ -272,6 +298,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getOptimisticFailureCount() { return hibernateStats.getOptimisticFailureCount(); } @@ -279,6 +306,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public String getOriginalConfigDeclaration() { return ehcacheStats.getOriginalConfigDeclaration(); } @@ -286,6 +314,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public String getOriginalConfigDeclaration(String region) { return ehcacheStats.getOriginalConfigDeclaration( region ); } @@ -293,6 +322,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getPrepareStatementCount() { return hibernateStats.getPrepareStatementCount(); } @@ -300,6 +330,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getQueryExecutionCount() { return hibernateStats.getQueryExecutionCount(); } @@ -307,6 +338,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public double getQueryExecutionRate() { return hibernateStats.getQueryExecutionRate(); } @@ -314,6 +346,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getQueryExecutionSample() { return hibernateStats.getQueryExecutionSample(); } @@ -321,6 +354,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public TabularData getQueryStats() { return hibernateStats.getQueryStats(); } @@ -328,6 +362,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public Map> getRegionCacheAttributes() { return ehcacheStats.getRegionCacheAttributes(); } @@ -335,6 +370,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public Map getRegionCacheAttributes(String regionName) { return ehcacheStats.getRegionCacheAttributes( regionName ); } @@ -342,6 +378,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public int getRegionCacheMaxTTISeconds(String region) { return ehcacheStats.getRegionCacheMaxTTISeconds( region ); } @@ -349,6 +386,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public int getRegionCacheMaxTTLSeconds(String region) { return ehcacheStats.getRegionCacheMaxTTLSeconds( region ); } @@ -356,6 +394,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public int getRegionCacheOrphanEvictionPeriod(String region) { return ehcacheStats.getRegionCacheOrphanEvictionPeriod( region ); } @@ -363,6 +402,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public Map getRegionCacheSamples() { return ehcacheStats.getRegionCacheSamples(); } @@ -370,6 +410,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public int getRegionCacheTargetMaxInMemoryCount(String region) { return ehcacheStats.getRegionCacheTargetMaxInMemoryCount( region ); } @@ -377,6 +418,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public int getRegionCacheTargetMaxTotalCount(String region) { return ehcacheStats.getRegionCacheTargetMaxTotalCount( region ); } @@ -384,6 +426,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getSessionCloseCount() { return hibernateStats.getSessionCloseCount(); } @@ -391,6 +434,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getSessionOpenCount() { return hibernateStats.getSessionOpenCount(); } @@ -398,6 +442,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getSuccessfulTransactionCount() { return hibernateStats.getSuccessfulTransactionCount(); } @@ -405,6 +450,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public String[] getTerracottaHibernateCacheRegionNames() { return ehcacheStats.getTerracottaHibernateCacheRegionNames(); } @@ -412,6 +458,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public long getTransactionCount() { return hibernateStats.getTransactionCount(); } @@ -419,6 +466,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public boolean isRegionCacheEnabled(String region) { return ehcacheStats.isRegionCacheEnabled( region ); } @@ -426,6 +474,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public void setRegionCachesEnabled(boolean enabled) { ehcacheStats.setRegionCachesEnabled( enabled ); sendNotification( HibernateStats.CACHE_ENABLED, enabled ); @@ -434,6 +483,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public void setRegionCacheEnabled(String region, boolean enabled) { ehcacheStats.setRegionCacheEnabled( region, enabled ); sendNotification( HibernateStats.CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region ); @@ -442,6 +492,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public boolean isRegionCacheLoggingEnabled(String region) { return ehcacheStats.isRegionCacheLoggingEnabled( region ); } @@ -449,6 +500,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public boolean isRegionCacheOrphanEvictionEnabled(String region) { return ehcacheStats.isRegionCacheOrphanEvictionEnabled( region ); } @@ -456,6 +508,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public boolean isRegionCachesEnabled() { return ehcacheStats.isRegionCachesEnabled(); } @@ -463,6 +516,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public boolean isTerracottaHibernateCache(String region) { return ehcacheStats.isTerracottaHibernateCache( region ); } @@ -470,6 +524,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public void setRegionCacheLoggingEnabled(String region, boolean loggingEnabled) { ehcacheStats.setRegionCacheLoggingEnabled( region, loggingEnabled ); sendNotification( HibernateStats.CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region ); @@ -478,6 +533,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public void setRegionCacheMaxTTISeconds(String region, int maxTTISeconds) { ehcacheStats.setRegionCacheMaxTTISeconds( region, maxTTISeconds ); sendNotification( HibernateStats.CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region ); @@ -486,6 +542,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public void setRegionCacheMaxTTLSeconds(String region, int maxTTLSeconds) { ehcacheStats.setRegionCacheMaxTTLSeconds( region, maxTTLSeconds ); sendNotification( HibernateStats.CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region ); @@ -494,6 +551,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public void setRegionCacheTargetMaxInMemoryCount(String region, int targetMaxInMemoryCount) { ehcacheStats.setRegionCacheTargetMaxInMemoryCount( region, targetMaxInMemoryCount ); sendNotification( HibernateStats.CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region ); @@ -502,6 +560,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe /** * {@inheritDoc} */ + @Override public void setRegionCacheTargetMaxTotalCount(String region, int targetMaxTotalCount) { ehcacheStats.setRegionCacheTargetMaxTotalCount( region, targetMaxTotalCount ); sendNotification( HibernateStats.CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region ); @@ -512,6 +571,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe * * @see EhcacheStats#getNumberOfElementsInMemory(java.lang.String) */ + @Override public int getNumberOfElementsInMemory(String region) { return ehcacheStats.getNumberOfElementsInMemory( region ); } @@ -521,6 +581,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe * * @see EhcacheStats#getNumberOfElementsInMemory(java.lang.String) */ + @Override public int getNumberOfElementsOffHeap(String region) { return ehcacheStats.getNumberOfElementsOffHeap( region ); } @@ -530,6 +591,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe * * @see EhcacheStats#getNumberOfElementsOnDisk(java.lang.String) */ + @Override public int getNumberOfElementsOnDisk(String region) { return ehcacheStats.getNumberOfElementsOnDisk( region ); } @@ -539,6 +601,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe * * @see EhcacheStats#getMaxGetTimeMillis() */ + @Override public long getMaxGetTimeMillis() { return ehcacheStats.getMaxGetTimeMillis(); } @@ -548,6 +611,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe * * @see EhcacheStats#getMaxGetTimeMillis(java.lang.String) */ + @Override public long getMaxGetTimeMillis(String cacheName) { return ehcacheStats.getMaxGetTimeMillis( cacheName ); } @@ -557,6 +621,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe * * @see EhcacheStats#getMinGetTimeMillis() */ + @Override public long getMinGetTimeMillis() { return ehcacheStats.getMinGetTimeMillis(); } @@ -566,6 +631,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe * * @see EhcacheStats#getMinGetTimeMillis(java.lang.String) */ + @Override public long getMinGetTimeMillis(String cacheName) { return ehcacheStats.getMinGetTimeMillis( cacheName ); } @@ -575,6 +641,7 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe * * @see EhcacheStats#getAverageGetTimeMillis(java.lang.String) */ + @Override public float getAverageGetTimeMillis(String region) { return ehcacheStats.getAverageGetTimeMillis( region ); } @@ -588,10 +655,12 @@ public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibe } /** + * {@inheritDoc} + * * @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/EhcacheHibernateMBeanRegistration.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMBeanRegistration.java index 2fdeba973d..6f3a646d62 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMBeanRegistration.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMBeanRegistration.java @@ -44,17 +44,17 @@ public interface EhcacheHibernateMBeanRegistration { * MBeans will be registered based on the input session factory name. If the input name is null or blank, the name of the cache-manager * is used * - * @param manager - * @param properties + * @param manager the {@link CacheManager} to register the MBean for + * @param properties properties to used to create the associated {@link SessionFactory} * - * @throws Exception + * @throws Exception reflecting the source of the problem registering the MBean */ public void registerMBeanForCacheManager(CacheManager manager, Properties properties) throws Exception; /** * Enable hibernate statistics in the mbean. * - * @param sessionFactory + * @param sessionFactory the {@link SessionFactory} to enable stats for */ public void enableHibernateStatisticsSupport(SessionFactory sessionFactory); 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 738bca7e05..38c0e1409a 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 @@ -65,9 +65,10 @@ public class EhcacheHibernateMBeanRegistrationImpl /** * {@inheritDoc} */ + @Override public synchronized void registerMBeanForCacheManager(final CacheManager manager, final Properties properties) throws Exception { - String sessionFactoryName = properties.getProperty( Environment.SESSION_FACTORY_NAME ); + final String sessionFactoryName = properties.getProperty( Environment.SESSION_FACTORY_NAME ); String name = null; if ( sessionFactoryName == null ) { name = manager.getName(); @@ -91,7 +92,7 @@ public class EhcacheHibernateMBeanRegistrationImpl } try { // register the CacheManager MBean - MBeanServer mBeanServer = getMBeanServer(); + final MBeanServer mBeanServer = getMBeanServer(); cacheManagerObjectName = EhcacheHibernateMbeanNames.getCacheManagerObjectName( cacheManagerClusterUUID, registeredCacheManagerName @@ -123,6 +124,7 @@ public class EhcacheHibernateMBeanRegistrationImpl /** * {@inheritDoc} */ + @Override public void enableHibernateStatisticsSupport(SessionFactory sessionFactory) { ehcacheHibernate.enableHibernateStatistics( sessionFactory ); } @@ -130,6 +132,7 @@ public class EhcacheHibernateMBeanRegistrationImpl /** * {@inheritDoc} */ + @Override public synchronized void dispose() throws CacheException { if ( status == Status.STATUS_SHUTDOWN ) { return; @@ -152,27 +155,39 @@ public class EhcacheHibernateMBeanRegistrationImpl /** * {@inheritDoc} */ + @Override public synchronized Status getStatus() { return status; } /** + * + * {@inheritDoc} + * * No-op in this case */ + @Override public void init() throws CacheException { // no-op } /** + * + * {@inheritDoc} + * * No-op in this case */ + @Override public void notifyCacheAdded(String cacheName) { // no-op } /** + * {@inheritDoc} + * * No-op in this case */ + @Override public void notifyCacheRemoved(String cacheName) { // no-op } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMbeanNames.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMbeanNames.java index 46fd1c2176..02362916aa 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMbeanNames.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMbeanNames.java @@ -49,7 +49,7 @@ public abstract class EhcacheHibernateMbeanNames { /** * Filter out invalid ObjectName characters from s. * - * @param s + * @param s the name to be filtered out * * @return A valid JMX ObjectName attribute value. */ @@ -60,15 +60,16 @@ public abstract class EhcacheHibernateMbeanNames { /** * Returns an ObjectName for the passed name * - * @param name + * @param cacheManagerClusterUUID the UUID of the cacheManager within the cluster + * @param name the name to use, which should be made "mbean safe" * * @return An {@link javax.management.ObjectName} using the input name of cache manager * - * @throws javax.management.MalformedObjectNameException + * @throws javax.management.MalformedObjectNameException The name derived from the params does not correspond to a valid ObjectName */ public static ObjectName getCacheManagerObjectName(String cacheManagerClusterUUID, String name) throws MalformedObjectNameException { - ObjectName objectName = new ObjectName( + final ObjectName objectName = new ObjectName( GROUP_ID + ":type=" + EHCACHE_HIBERNATE_TYPE + ",name=" + mbeanSafe( name ) + getBeanNameSuffix( cacheManagerClusterUUID ) ); 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 b3c90f2727..36d9f4c123 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 @@ -63,7 +63,8 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * Constructor accepting the backing {@link CacheManager} * - * @throws javax.management.NotCompliantMBeanException + * @param manager The {@link CacheManager} to expose stats for + * @throws javax.management.NotCompliantMBeanException should registering the MBean fail */ public EhcacheStatsImpl(CacheManager manager) throws NotCompliantMBeanException { super( EhcacheStats.class ); @@ -74,6 +75,7 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public boolean isStatisticsEnabled() { return false; } @@ -81,6 +83,7 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public void clearStats() { sampledCacheManager.clearStatistics(); statsSince = System.currentTimeMillis(); @@ -89,6 +92,7 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public void disableStats() { setStatisticsEnabled( false ); } @@ -96,6 +100,7 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public void enableStats() { setStatisticsEnabled( true ); } @@ -103,8 +108,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public void flushRegionCache(String region) { - Cache cache = this.cacheManager.getCache( region ); + final Cache cache = this.cacheManager.getCache( region ); if ( cache != null ) { cache.flush(); } @@ -113,9 +119,10 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public void flushRegionCaches() { for ( String name : cacheManager.getCacheNames() ) { - Cache cache = this.cacheManager.getCache( name ); + final Cache cache = this.cacheManager.getCache( name ); if ( cache != null ) { cache.flush(); } @@ -126,6 +133,7 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public String generateActiveConfigDeclaration() { return this.cacheManager.getActiveConfigurationText(); } @@ -133,6 +141,7 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public String generateActiveConfigDeclaration(String region) { return this.cacheManager.getActiveConfigurationText( region ); } @@ -140,10 +149,11 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public long getCacheHitCount() { long count = 0; for ( String name : cacheManager.getCacheNames() ) { - Cache cache = cacheManager.getCache( name ); + final Cache cache = cacheManager.getCache( name ); if ( cache != null ) { count += cache.getLiveCacheStatistics().getCacheHitCount(); } @@ -154,19 +164,21 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public double getCacheHitRate() { - long now = System.currentTimeMillis(); - double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND; + final long now = System.currentTimeMillis(); + final double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND; return getCacheHitCount() / deltaSecs; } /** * {@inheritDoc} */ + @Override public long getCacheHitSample() { long count = 0; for ( String name : cacheManager.getCacheNames() ) { - Cache cache = cacheManager.getCache( name ); + final Cache cache = cacheManager.getCache( name ); if ( cache != null ) { count += cache.getSampledCacheStatistics().getCacheHitMostRecentSample(); } @@ -177,10 +189,11 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public long getCacheMissCount() { long count = 0; for ( String name : cacheManager.getCacheNames() ) { - Cache cache = cacheManager.getCache( name ); + final Cache cache = cacheManager.getCache( name ); if ( cache != null ) { count += cache.getLiveCacheStatistics().getCacheMissCount(); } @@ -191,19 +204,21 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public double getCacheMissRate() { - long now = System.currentTimeMillis(); - double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND; + final long now = System.currentTimeMillis(); + final double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND; return getCacheMissCount() / deltaSecs; } /** * {@inheritDoc} */ + @Override public long getCacheMissSample() { long count = 0; for ( String name : cacheManager.getCacheNames() ) { - Cache cache = cacheManager.getCache( name ); + final Cache cache = cacheManager.getCache( name ); if ( cache != null ) { count += cache.getSampledCacheStatistics().getCacheMissMostRecentSample(); } @@ -214,10 +229,11 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public long getCachePutCount() { long count = 0; for ( String name : cacheManager.getCacheNames() ) { - Cache cache = cacheManager.getCache( name ); + final Cache cache = cacheManager.getCache( name ); if ( cache != null ) { count += cache.getLiveCacheStatistics().getPutCount(); } @@ -228,19 +244,21 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public double getCachePutRate() { - long now = System.currentTimeMillis(); - double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND; + final long now = System.currentTimeMillis(); + final double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND; return getCachePutCount() / deltaSecs; } /** * {@inheritDoc} */ + @Override public long getCachePutSample() { long count = 0; for ( String name : cacheManager.getCacheNames() ) { - Cache cache = cacheManager.getCache( name ); + final Cache cache = cacheManager.getCache( name ); if ( cache != null ) { count += cache.getSampledCacheStatistics().getCacheElementPutMostRecentSample(); } @@ -251,6 +269,7 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public String getOriginalConfigDeclaration() { return this.cacheManager.getOriginalConfigurationText(); } @@ -258,6 +277,7 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public String getOriginalConfigDeclaration(String region) { return this.cacheManager.getOriginalConfigurationText( region ); } @@ -265,8 +285,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public Map> getRegionCacheAttributes() { - Map> result = new HashMap>(); + final Map> result = new HashMap>(); for ( String regionName : this.cacheManager.getCacheNames() ) { result.put( regionName, getRegionCacheAttributes( regionName ) ); } @@ -276,8 +297,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public Map getRegionCacheAttributes(String regionName) { - Map result = new HashMap(); + final Map result = new HashMap(); result.put( "Enabled", isRegionCacheEnabled( regionName ) ); result.put( "LoggingEnabled", isRegionCacheLoggingEnabled( regionName ) ); result.put( "MaxTTISeconds", getRegionCacheMaxTTISeconds( regionName ) ); @@ -292,8 +314,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public int getRegionCacheMaxTTISeconds(String region) { - Cache cache = cacheManager.getCache( region ); + final Cache cache = cacheManager.getCache( region ); if ( cache != null ) { return (int) cache.getCacheConfiguration().getTimeToIdleSeconds(); } @@ -305,8 +328,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public int getRegionCacheMaxTTLSeconds(String region) { - Cache cache = cacheManager.getCache( region ); + final Cache cache = cacheManager.getCache( region ); if ( cache != null ) { return (int) cache.getCacheConfiguration().getTimeToLiveSeconds(); } @@ -318,8 +342,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public int getRegionCacheOrphanEvictionPeriod(String region) { - Cache cache = this.cacheManager.getCache( region ); + final Cache cache = this.cacheManager.getCache( region ); if ( cache != null && cache.isTerracottaClustered() ) { return cache.getCacheConfiguration().getTerracottaConfiguration().getOrphanEvictionPeriod(); } @@ -331,10 +356,11 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public Map getRegionCacheSamples() { - Map rv = new HashMap(); + final Map rv = new HashMap(); for ( String name : cacheManager.getCacheNames() ) { - Cache cache = cacheManager.getCache( name ); + final Cache cache = cacheManager.getCache( name ); if ( cache != null ) { rv.put( name, new int[] { @@ -352,8 +378,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public int getRegionCacheTargetMaxInMemoryCount(String region) { - Cache cache = cacheManager.getCache( region ); + final Cache cache = cacheManager.getCache( region ); if ( cache != null ) { return cache.getCacheConfiguration().getMaxElementsInMemory(); } @@ -365,8 +392,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public int getRegionCacheTargetMaxTotalCount(String region) { - Cache cache = cacheManager.getCache( region ); + final Cache cache = cacheManager.getCache( region ); if ( cache != null ) { return cache.getCacheConfiguration().getMaxElementsOnDisk(); } @@ -378,10 +406,11 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public String[] getTerracottaHibernateCacheRegionNames() { - ArrayList rv = new ArrayList(); + final ArrayList rv = new ArrayList(); for ( String name : cacheManager.getCacheNames() ) { - Cache cache = cacheManager.getCache( name ); + final Cache cache = cacheManager.getCache( name ); if ( cache != null ) { if ( cache.getCacheConfiguration().isTerracottaClustered() ) { rv.add( name ); @@ -394,8 +423,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public boolean isRegionCacheEnabled(String region) { - Cache cache = this.cacheManager.getCache( region ); + final Cache cache = this.cacheManager.getCache( region ); if ( cache != null ) { return !cache.isDisabled(); } @@ -407,8 +437,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public void setRegionCacheEnabled(String region, boolean enabled) { - Cache cache = this.cacheManager.getCache( region ); + final Cache cache = this.cacheManager.getCache( region ); if ( cache != null ) { cache.setDisabled( !enabled ); } @@ -418,9 +449,10 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public boolean isRegionCachesEnabled() { for ( String name : this.cacheManager.getCacheNames() ) { - Cache cache = this.cacheManager.getCache( name ); + final Cache cache = this.cacheManager.getCache( name ); if ( cache != null ) { if ( cache.isDisabled() ) { return false; @@ -431,11 +463,13 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } /** + * {@inheritDoc} * @see EhcacheStats#setRegionCachesEnabled(boolean) */ + @Override public void setRegionCachesEnabled(final boolean flag) { for ( String name : this.cacheManager.getCacheNames() ) { - Cache cache = this.cacheManager.getCache( name ); + final Cache cache = this.cacheManager.getCache( name ); if ( cache != null ) { cache.setDisabled( !flag ); } @@ -446,8 +480,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public boolean isRegionCacheLoggingEnabled(String region) { - Cache cache = this.cacheManager.getCache( region ); + final Cache cache = this.cacheManager.getCache( region ); if ( cache != null ) { return cache.getCacheConfiguration().getLogging(); } @@ -459,8 +494,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public boolean isRegionCacheOrphanEvictionEnabled(String region) { - Cache cache = this.cacheManager.getCache( region ); + final Cache cache = this.cacheManager.getCache( region ); if ( cache != null && cache.isTerracottaClustered() ) { return cache.getCacheConfiguration().getTerracottaConfiguration().getOrphanEviction(); } @@ -472,8 +508,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public boolean isTerracottaHibernateCache(String region) { - Cache cache = cacheManager.getCache( region ); + final Cache cache = cacheManager.getCache( region ); if ( cache != null ) { return cache.getCacheConfiguration().isTerracottaClustered(); } @@ -485,8 +522,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public void setRegionCacheLoggingEnabled(String region, boolean loggingEnabled) { - Cache cache = this.cacheManager.getCache( region ); + final Cache cache = this.cacheManager.getCache( region ); if ( cache != null ) { cache.getCacheConfiguration().setLogging( loggingEnabled ); sendNotification( CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region ); @@ -496,8 +534,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public void setRegionCacheMaxTTISeconds(String region, int maxTTISeconds) { - Cache cache = this.cacheManager.getCache( region ); + final Cache cache = this.cacheManager.getCache( region ); if ( cache != null ) { cache.getCacheConfiguration().setTimeToIdleSeconds( maxTTISeconds ); sendNotification( CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region ); @@ -507,8 +546,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public void setRegionCacheMaxTTLSeconds(String region, int maxTTLSeconds) { - Cache cache = this.cacheManager.getCache( region ); + final Cache cache = this.cacheManager.getCache( region ); if ( cache != null ) { cache.getCacheConfiguration().setTimeToLiveSeconds( maxTTLSeconds ); sendNotification( CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region ); @@ -518,8 +558,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public void setRegionCacheTargetMaxInMemoryCount(String region, int targetMaxInMemoryCount) { - Cache cache = this.cacheManager.getCache( region ); + final Cache cache = this.cacheManager.getCache( region ); if ( cache != null ) { cache.getCacheConfiguration().setMaxElementsInMemory( targetMaxInMemoryCount ); sendNotification( CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region ); @@ -529,8 +570,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public void setRegionCacheTargetMaxTotalCount(String region, int targetMaxTotalCount) { - Cache cache = this.cacheManager.getCache( region ); + final Cache cache = this.cacheManager.getCache( region ); if ( cache != null ) { cache.getCacheConfiguration().setMaxElementsOnDisk( targetMaxTotalCount ); sendNotification( CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region ); @@ -542,8 +584,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat * * @see EhcacheStats#getNumberOfElementsInMemory(java.lang.String) */ + @Override public int getNumberOfElementsInMemory(String region) { - Cache cache = this.cacheManager.getCache( region ); + final Cache cache = this.cacheManager.getCache( region ); if ( cache != null ) { return (int) cache.getMemoryStoreSize(); } @@ -557,8 +600,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat * * @see EhcacheStats#getNumberOfElementsOffHeap(java.lang.String) */ + @Override public int getNumberOfElementsOffHeap(String region) { - Cache cache = this.cacheManager.getCache( region ); + final Cache cache = this.cacheManager.getCache( region ); if ( cache != null ) { return (int) cache.getOffHeapStoreSize(); } @@ -572,8 +616,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat * * @see EhcacheStats#getNumberOfElementsOnDisk(java.lang.String) */ + @Override public int getNumberOfElementsOnDisk(String region) { - Cache cache = this.cacheManager.getCache( region ); + final Cache cache = this.cacheManager.getCache( region ); if ( cache != null ) { return cache.getDiskStoreSize(); } @@ -585,9 +630,10 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public void setStatisticsEnabled(boolean flag) { for ( String cacheName : cacheManager.getCacheNames() ) { - Cache cache = cacheManager.getCache( cacheName ); + final Cache cache = cacheManager.getCache( cacheName ); if ( cache != null ) { cache.setStatisticsEnabled( flag ); } @@ -601,10 +647,11 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public long getMaxGetTimeMillis() { long rv = 0; for ( String cacheName : cacheManager.getCacheNames() ) { - Cache cache = cacheManager.getCache( cacheName ); + final Cache cache = cacheManager.getCache( cacheName ); if ( cache != null ) { rv = Math.max( rv, cache.getLiveCacheStatistics().getMaxGetTimeMillis() ); } @@ -615,10 +662,11 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat /** * {@inheritDoc} */ + @Override public long getMinGetTimeMillis() { long rv = 0; for ( String cacheName : cacheManager.getCacheNames() ) { - Cache cache = cacheManager.getCache( cacheName ); + final Cache cache = cacheManager.getCache( cacheName ); if ( cache != null ) { rv = Math.max( rv, cache.getLiveCacheStatistics().getMinGetTimeMillis() ); } @@ -631,8 +679,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat * * @see EhcacheStats#getMaxGetTimeMillis(java.lang.String) */ + @Override public long getMaxGetTimeMillis(String cacheName) { - Cache cache = cacheManager.getCache( cacheName ); + final Cache cache = cacheManager.getCache( cacheName ); if ( cache != null ) { return cache.getLiveCacheStatistics().getMaxGetTimeMillis(); } @@ -646,8 +695,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat * * @see EhcacheStats#getMinGetTimeMillis(java.lang.String) */ + @Override public long getMinGetTimeMillis(String cacheName) { - Cache cache = cacheManager.getCache( cacheName ); + final Cache cache = cacheManager.getCache( cacheName ); if ( cache != null ) { return cache.getLiveCacheStatistics().getMinGetTimeMillis(); } @@ -661,8 +711,9 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat * * @see EhcacheStats#getAverageGetTimeMillis(java.lang.String) */ + @Override public float getAverageGetTimeMillis(String region) { - Cache cache = this.cacheManager.getCache( region ); + final Cache cache = this.cacheManager.getCache( region ); if ( cache != null ) { return cache.getLiveCacheStatistics().getAverageGetTimeMillis(); } @@ -680,6 +731,7 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } /** + * {@inheritDoc} * @see AbstractEmitterBean#getNotificationInfo() */ @Override 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 a121801db3..19faf860c1 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 @@ -120,7 +120,8 @@ public class EntityStats implements Serializable { protected long optimisticFailureCount; /** - * @param name + * Constructor only naming the stat + * @param name the name of the entity */ public EntityStats(String name) { this.name = name; @@ -128,8 +129,9 @@ public class EntityStats implements Serializable { } /** - * @param name - * @param src + * Constructor naming the stat and sourcing stats + * @param name the name of the entity + * @param src its source for the stats to expose */ public EntityStats(String name, EntityStatistics src) { this( name ); @@ -149,7 +151,8 @@ public class EntityStats implements Serializable { } /** - * @param cData + * Constructor from compositeDate + * @param cData CompositeData of the stats */ public EntityStats(final CompositeData cData) { int i = 0; @@ -173,7 +176,8 @@ public class EntityStats implements Serializable { } /** - * @param stats + * Adds the counters of this instance up with the ones passed in + * @param stats the stats to add to this one */ public void add(EntityStats stats) { loadCount += stats.getLoadCount(); @@ -185,7 +189,7 @@ public class EntityStats implements Serializable { } /** - * toString + * {@inheritDoc} */ @Override public String toString() { @@ -195,63 +199,72 @@ public class EntityStats implements Serializable { } /** - * getName + * The name of the entity those stats are about + * @return the entity name */ public String getName() { return name; } /** - * getShortName + * The short name of the entity those stats are about + * @return the shortName of the entity */ public String getShortName() { return shortName; } /** - * getLoadCount + * Amount of load ops on the entity + * @return the load count */ public long getLoadCount() { return loadCount; } /** - * getUpdateCount + * Amount of update ops on the entity + * @return the update count */ public long getUpdateCount() { return updateCount; } /** - * getInsertCount + * Amount of insert ops on the entity + * @return the insert count */ public long getInsertCount() { return insertCount; } /** - * getDeleteCount + * Amount of delete ops on the entity + * @return the delete count */ public long getDeleteCount() { return deleteCount; } /** - * getFetchCount + * Amount of fetch ops on the entity + * @return the fetch count */ public long getFetchCount() { return fetchCount; } /** - * getOptimisticFailureCount + * Amount of optimistic failures on the entity + * @return the optimistic failure count */ public long getOptimisticFailureCount() { return optimisticFailureCount; } /** - * toCompositeData + * Creates a CompositeData instance of this instance + * @return the compositeData representation of this instance */ public CompositeData toCompositeData() { try { @@ -268,14 +281,17 @@ public class EntityStats implements Serializable { } /** - * newTabularDataInstance + * Creates a new TabularData + * @return a new TabularData instance */ public static TabularData newTabularDataInstance() { return new TabularDataSupport( TABULAR_TYPE ); } /** - * fromTabularData + * Reads an array of entityStats from TabularData + * @param tabularData the tabularData with the {@link CompositeData} of stats to extract + * @return all entityStats as an array */ public static EntityStats[] fromTabularData(final TabularData tabularData) { final List countList = new ArrayList( tabularData.size() ); 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 85eed55b05..35bc4e0ea2 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 @@ -59,9 +59,9 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate /** * Constructor accepting the backing {@link SessionFactory} * - * @param sessionFactory + * @param sessionFactory the {@link SessionFactory} to source stats from * - * @throws javax.management.NotCompliantMBeanException + * @throws javax.management.NotCompliantMBeanException thrown from JMX super ctor */ public HibernateStatsImpl(SessionFactory sessionFactory) throws NotCompliantMBeanException { super( HibernateStats.class ); @@ -80,6 +80,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#clearStats() */ + @Override public void clearStats() { getStatistics().clear(); sendNotification( CACHE_STATISTICS_RESET ); @@ -90,6 +91,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#disableStats() */ + @Override public void disableStats() { setStatisticsEnabled( false ); } @@ -99,6 +101,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#enableStats() */ + @Override public void enableStats() { setStatisticsEnabled( true ); } @@ -108,6 +111,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#getCloseStatementCount() */ + @Override public long getCloseStatementCount() { return getStatistics().getCloseStatementCount(); } @@ -117,13 +121,18 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#getConnectCount() */ + @Override public long getConnectCount() { return getStatistics().getConnectCount(); } /** - * Not supported right now + * Unsupported operation + * @return nothing ever, this only throws! + * @throws UnsupportedOperationException + * @deprecated DO NOT USE, WILL ONLY THROW AT YOU! */ + @Deprecated public long getDBSQLExecutionSample() { throw new UnsupportedOperationException( "Use getQueryExecutionCount() instead" ); } @@ -133,6 +142,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#getFlushCount() */ + @Override public long getFlushCount() { return getStatistics().getFlushCount(); } @@ -142,6 +152,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#getOptimisticFailureCount() */ + @Override public long getOptimisticFailureCount() { return getStatistics().getOptimisticFailureCount(); } @@ -151,6 +162,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#getPrepareStatementCount() */ + @Override public long getPrepareStatementCount() { return getStatistics().getPrepareStatementCount(); } @@ -160,6 +172,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#getQueryExecutionCount() */ + @Override public long getQueryExecutionCount() { return getStatistics().getQueryExecutionCount(); } @@ -169,10 +182,11 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#getQueryExecutionRate() */ + @Override public double getQueryExecutionRate() { - long startTime = getStatistics().getStartTime(); - long now = System.currentTimeMillis(); - double deltaSecs = (now - startTime) / MILLIS_PER_SECOND; + final long startTime = getStatistics().getStartTime(); + final long now = System.currentTimeMillis(); + final double deltaSecs = (now - startTime) / MILLIS_PER_SECOND; return getQueryExecutionCount() / deltaSecs; } @@ -181,6 +195,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#getQueryExecutionSample() */ + @Override public long getQueryExecutionSample() { throw new UnsupportedOperationException( "TODO: need to impl. rates for query execution" ); } @@ -190,6 +205,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#getSessionCloseCount() */ + @Override public long getSessionCloseCount() { return getStatistics().getSessionCloseCount(); } @@ -199,6 +215,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#getSessionOpenCount() */ + @Override public long getSessionOpenCount() { return getStatistics().getSessionOpenCount(); } @@ -208,6 +225,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#getSuccessfulTransactionCount() */ + @Override public long getSuccessfulTransactionCount() { return getStatistics().getSuccessfulTransactionCount(); } @@ -217,6 +235,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#getTransactionCount() */ + @Override public long getTransactionCount() { return getStatistics().getTransactionCount(); } @@ -226,6 +245,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#isStatisticsEnabled() */ + @Override public boolean isStatisticsEnabled() { return getStatistics().isStatisticsEnabled(); } @@ -235,6 +255,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#setStatisticsEnabled(boolean) */ + @Override public void setStatisticsEnabled(boolean flag) { getStatistics().setStatisticsEnabled( flag ); sendNotification( CACHE_STATISTICS_ENABLED, flag ); @@ -245,14 +266,15 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#getEntityStats() */ + @Override public TabularData getEntityStats() { - List result = new ArrayList(); - Statistics statistics = getStatistics(); + final List result = new ArrayList(); + final Statistics statistics = getStatistics(); for ( String entity : statistics.getEntityNames() ) { - EntityStats entityStats = new EntityStats( entity, statistics.getEntityStatistics( entity ) ); + final EntityStats entityStats = new EntityStats( entity, statistics.getEntityStatistics( entity ) ); result.add( entityStats.toCompositeData() ); } - TabularData td = EntityStats.newTabularDataInstance(); + final TabularData td = EntityStats.newTabularDataInstance(); td.putAll( result.toArray( new CompositeData[result.size()] ) ); return td; } @@ -262,17 +284,18 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#getCollectionStats() */ + @Override public TabularData getCollectionStats() { - List result = new ArrayList(); - Statistics statistics = getStatistics(); + final List result = new ArrayList(); + final Statistics statistics = getStatistics(); for ( String roleName : statistics.getCollectionRoleNames() ) { - CollectionStats collectionStats = new CollectionStats( + final CollectionStats collectionStats = new CollectionStats( roleName, statistics.getCollectionStatistics( roleName ) ); result.add( collectionStats.toCompositeData() ); } - TabularData td = CollectionStats.newTabularDataInstance(); + final TabularData td = CollectionStats.newTabularDataInstance(); td.putAll( result.toArray( new CompositeData[result.size()] ) ); return td; } @@ -282,14 +305,15 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * * @see HibernateStats#getQueryStats() */ + @Override public TabularData getQueryStats() { - List result = new ArrayList(); - Statistics statistics = getStatistics(); + final List result = new ArrayList(); + final Statistics statistics = getStatistics(); for ( String query : statistics.getQueries() ) { - QueryStats queryStats = new QueryStats( query, statistics.getQueryStatistics( query ) ); + final QueryStats queryStats = new QueryStats( query, statistics.getQueryStatistics( query ) ); result.add( queryStats.toCompositeData() ); } - TabularData td = QueryStats.newTabularDataInstance(); + final TabularData td = QueryStats.newTabularDataInstance(); td.putAll( result.toArray( new CompositeData[result.size()] ) ); return td; } @@ -297,17 +321,18 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate /** * {@inheritDoc} */ + @Override public TabularData getCacheRegionStats() { - List list = new ArrayList(); - Statistics statistics = getStatistics(); + final List list = new ArrayList(); + final Statistics statistics = getStatistics(); for ( String region : statistics.getSecondLevelCacheRegionNames() ) { - CacheRegionStats l2CacheStats = new CacheRegionStats( + final CacheRegionStats l2CacheStats = new CacheRegionStats( region, statistics.getSecondLevelCacheStatistics( region ) ); list.add( l2CacheStats.toCompositeData() ); } - TabularData td = CacheRegionStats.newTabularDataInstance(); + final TabularData td = CacheRegionStats.newTabularDataInstance(); td.putAll( list.toArray( new CompositeData[list.size()] ) ); return td; } @@ -321,6 +346,7 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate } /** + * {@inheritDoc} * @see AbstractEmitterBean#getNotificationInfo() */ @Override diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/NullHibernateStats.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/NullHibernateStats.java index b7712a71c1..56c66c0e90 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/NullHibernateStats.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/NullHibernateStats.java @@ -59,6 +59,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#clearStats() */ + @Override public void clearStats() { // no-op @@ -69,6 +70,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#disableStats() */ + @Override public void disableStats() { // no-op @@ -79,6 +81,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#enableStats() */ + @Override public void enableStats() { // no-op @@ -89,6 +92,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#getCloseStatementCount() */ + @Override public long getCloseStatementCount() { // no-op return 0; @@ -99,6 +103,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#getCollectionStats() */ + @Override public TabularData getCollectionStats() { // no-op return null; @@ -109,6 +114,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#getConnectCount() */ + @Override public long getConnectCount() { // no-op return 0; @@ -116,6 +122,7 @@ public final class NullHibernateStats implements HibernateStats { /** * Not supported right now + * @return 0 always */ public long getDBSQLExecutionSample() { // no-op @@ -127,6 +134,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#getEntityStats() */ + @Override public TabularData getEntityStats() { // no-op return null; @@ -137,6 +145,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#getFlushCount() */ + @Override public long getFlushCount() { // no-op return 0; @@ -147,6 +156,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#getOptimisticFailureCount() */ + @Override public long getOptimisticFailureCount() { // no-op return 0; @@ -157,6 +167,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#getPrepareStatementCount() */ + @Override public long getPrepareStatementCount() { // no-op return 0; @@ -167,6 +178,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#getQueryExecutionCount() */ + @Override public long getQueryExecutionCount() { // no-op return 0; @@ -177,6 +189,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#getQueryExecutionRate() */ + @Override public double getQueryExecutionRate() { // no-op return 0; @@ -187,6 +200,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#getQueryExecutionSample() */ + @Override public long getQueryExecutionSample() { // no-op return 0; @@ -197,6 +211,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#getQueryStats() */ + @Override public TabularData getQueryStats() { // no-op return null; @@ -207,6 +222,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#getSessionCloseCount() */ + @Override public long getSessionCloseCount() { // no-op return 0; @@ -217,6 +233,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#getSessionOpenCount() */ + @Override public long getSessionOpenCount() { // no-op return 0; @@ -227,6 +244,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#getSuccessfulTransactionCount() */ + @Override public long getSuccessfulTransactionCount() { // no-op return 0; @@ -237,6 +255,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#getTransactionCount() */ + @Override public long getTransactionCount() { // no-op return 0; @@ -247,6 +266,7 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#isStatisticsEnabled() */ + @Override public boolean isStatisticsEnabled() { // no-op return false; @@ -257,43 +277,54 @@ public final class NullHibernateStats implements HibernateStats { * * @see HibernateStats#setStatisticsEnabled(boolean) */ + @Override public void setStatisticsEnabled(boolean flag) { // no-op } /** + * {@inheritDoc} * @see HibernateStats#getCacheRegionStats() */ + @Override public TabularData getCacheRegionStats() { return null; } /** + * {@inheritDoc} * @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object) */ + @Override public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException { /**/ } /** + * {@inheritDoc} * @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object) */ + @Override public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException { /**/ } /** + * {@inheritDoc} * @see javax.management.NotificationBroadcaster#getNotificationInfo() */ + @Override public MBeanNotificationInfo[] getNotificationInfo() { return null; } /** + * {@inheritDoc} * @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener) */ + @Override public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { /**/ } 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 648cc17cf6..2a081f12e0 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 @@ -116,7 +116,7 @@ public class ProviderMBeanRegistrationHelper { throw new CacheException( e ); } } - SessionFactory sessionFactory = locateSessionFactory(); + final SessionFactory sessionFactory = locateSessionFactory(); if ( sessionFactory == null ) { LOG.debug( "SessionFactory is probably still being initialized..." @@ -140,29 +140,29 @@ public class ProviderMBeanRegistrationHelper { } private SessionFactory locateSessionFactory() { - String jndiName = properties.getProperty( Environment.SESSION_FACTORY_NAME ); + final 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" ); + final Class factoryType = SessionFactoryRegistry.class; + final 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 ); + final Map map = (Map) instancesField.get( SessionFactoryRegistry.INSTANCE ); if ( map == null ) { return null; } - Iterator values = map.values().iterator(); + final Iterator values = map.values().iterator(); while ( values.hasNext() ) { - SessionFactory sessionFactory = (SessionFactory) values.next(); - Class sessionFactoryType = sessionFactory.getClass(); - Field propertiesField = getField( sessionFactoryType, "properties" ); + final SessionFactory sessionFactory = (SessionFactory) values.next(); + final Class sessionFactoryType = sessionFactory.getClass(); + final Field propertiesField = getField( sessionFactoryType, "properties" ); if ( propertiesField != null ) { propertiesField.setAccessible( true ); - Properties props = (Properties) propertiesField.get( sessionFactory ); + final Properties props = (Properties) propertiesField.get( sessionFactory ); if ( props != null && props.equals( properties ) ) { return sessionFactory; } @@ -187,4 +187,4 @@ public class ProviderMBeanRegistrationHelper { } 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 27c33bea14..4eba0d82e7 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 @@ -41,6 +41,8 @@ import org.hibernate.stat.QueryStatistics; /** + * Represent point in time state of the query stats of a given query + * * @author gkeim * @author Alex Snaps */ @@ -137,15 +139,17 @@ public class QueryStats implements Serializable { protected long executionMinTime; /** - * @param name + * Constructor + * @param name the query string */ public QueryStats(String name) { this.query = name; } /** - * @param name - * @param src + * Constructor + * @param name the query string + * @param src the source of the stats to this query */ public QueryStats(String name, QueryStatistics src) { this( name ); @@ -168,7 +172,8 @@ public class QueryStats implements Serializable { } /** - * @param cData + * Constructor + * @param cData CompositeDate to construct an instance from */ public QueryStats(final CompositeData cData) { int i = 0; @@ -183,17 +188,9 @@ public class QueryStats implements Serializable { executionMinTime = (Long) cData.get( ITEM_NAMES[i++] ); } - private static int safeParseInt(String s) { - try { - return Integer.parseInt( s ); - } - catch (Exception e) { - return -1; - } - } - /** - * @param stats + * Adds to the counter of this instance + * @param stats the counters to add to these ones */ public void add(QueryStats stats) { cacheHitCount += stats.getCacheHitCount(); @@ -207,7 +204,7 @@ public class QueryStats implements Serializable { } /** - * toString + * {@inheritDoc} */ @Override public String toString() { @@ -218,70 +215,80 @@ public class QueryStats implements Serializable { } /** - * getQuery + * Accessor to the queryString + * @return the query string */ public String getQuery() { return query; } /** - * getCacheHitCount + * The amount of hits for this query + * @return the hit count */ public long getCacheHitCount() { return cacheHitCount; } /** - * getCacheMissCount + * The amount of misses for this query + * @return the miss count */ public long getCacheMissCount() { return cacheMissCount; } /** - * getCachePutCount + * The amount of puts for this query + * @return the put count */ public long getCachePutCount() { return cachePutCount; } /** - * getExecutionCount + * The amount of execution of this query + * @return the execution count */ public long getExecutionCount() { return executionCount; } /** - * getExecutionRowCount + * The amount of rows returned for this query + * @return the row count */ public long getExecutionRowCount() { return executionRowCount; } /** - * getExecutionAvgTime + * The avg time to execute this query + * @return the avg time in ms */ public long getExecutionAvgTime() { return executionAvgTime; } /** - * getExecutionMaxTime + * The max time to execute this query + * @return the max time in ms */ public long getExecutionMaxTime() { return executionMaxTime; } /** - * getExecutionMinTime + * The minimum time to execute this query + * @return the min time in ms */ public long getExecutionMinTime() { return executionMinTime; } /** - * toCompositeData + * Creates a CompositeData instance of this instance + * @return the compositeData representation of this instance */ public CompositeData toCompositeData() { try { @@ -303,14 +310,17 @@ public class QueryStats implements Serializable { } /** - * newTabularDataInstance + * Creates a new TabularData + * @return a new TabularData instance */ public static TabularData newTabularDataInstance() { return new TabularDataSupport( TABULAR_TYPE ); } /** - * fromTabularData + * Reads an array of queryStats from TabularData + * @param tabularData the tabularData with the {@link CompositeData} of stats to extract + * @return all queryStats as an array */ public static QueryStats[] fromTabularData(final TabularData tabularData) { final List countList = new ArrayList( tabularData.size() ); From f841c2ab3b27d8bddcd6c13fc411c0fe9455884a Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Wed, 8 May 2013 16:23:40 -0400 Subject: [PATCH 18/25] HHH-8211 FindBugs: Redundant null check removed --- .../management/impl/ProviderMBeanRegistrationHelper.java | 3 --- 1 file changed, 3 deletions(-) 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 2a081f12e0..7b720e49ce 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 @@ -147,9 +147,6 @@ public class ProviderMBeanRegistrationHelper { try { final Class factoryType = SessionFactoryRegistry.class; final Field instancesField = getField( factoryType, "sessionFactoryMap" ); - if ( instancesField == null ) { - throw new RuntimeException( "Expected 'sessionFactoryMap' field on " + SessionFactoryRegistry.class.getName() ); - } instancesField.setAccessible( true ); final Map map = (Map) instancesField.get( SessionFactoryRegistry.INSTANCE ); if ( map == null ) { From 6fe63e035c0bbc3b0af18052a51800f17b2e3208 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Thu, 9 May 2013 15:19:02 -0500 Subject: [PATCH 19/25] HHH-8211 - Checkstyle and FindBugs fix-ups --- .../EhcacheHibernateMBeanRegistrationImpl.java | 17 +++++------------ .../impl/EhcacheHibernateMbeanNames.java | 7 +++---- .../impl/ProviderMBeanRegistrationHelper.java | 6 ++---- .../ehcache/management/impl/QueryStats.java | 4 ++-- 4 files changed, 12 insertions(+), 22 deletions(-) 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 38c0e1409a..8b39cd7b27 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 @@ -56,20 +56,15 @@ public class EhcacheHibernateMBeanRegistrationImpl 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} - */ @Override public synchronized void registerMBeanForCacheManager(final CacheManager manager, final Properties properties) throws Exception { final String sessionFactoryName = properties.getProperty( Environment.SESSION_FACTORY_NAME ); - String name = null; + final String name; if ( sessionFactoryName == null ) { name = manager.getName(); } @@ -82,11 +77,12 @@ public class EhcacheHibernateMBeanRegistrationImpl private void registerBean(String name, CacheManager manager) throws Exception { ehcacheHibernate = new EhcacheHibernate( manager ); int tries = 0; - boolean success = false; + boolean success; Exception exception = null; - cacheManagerClusterUUID = manager.getClusterUUID(); + final String cacheManagerClusterUUID = manager.getClusterUUID(); + String registeredCacheManagerName; do { - this.registeredCacheManagerName = name; + registeredCacheManagerName = name; if ( tries != 0 ) { registeredCacheManagerName += "_" + tries; } @@ -121,9 +117,6 @@ public class EhcacheHibernateMBeanRegistrationImpl return ManagementFactory.getPlatformMBeanServer(); } - /** - * {@inheritDoc} - */ @Override public void enableHibernateStatisticsSupport(SessionFactory sessionFactory) { ehcacheHibernate.enableHibernateStatistics( sessionFactory ); diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMbeanNames.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMbeanNames.java index 02362916aa..4d4c5c5872 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMbeanNames.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMbeanNames.java @@ -69,11 +69,10 @@ public abstract class EhcacheHibernateMbeanNames { */ public static ObjectName getCacheManagerObjectName(String cacheManagerClusterUUID, String name) throws MalformedObjectNameException { - final ObjectName objectName = new ObjectName( - GROUP_ID + ":type=" + EHCACHE_HIBERNATE_TYPE + ",name=" + mbeanSafe( name ) - + getBeanNameSuffix( cacheManagerClusterUUID ) + return new ObjectName( + GROUP_ID + ":type=" + EHCACHE_HIBERNATE_TYPE + + ",name=" + mbeanSafe( name ) + getBeanNameSuffix( cacheManagerClusterUUID ) ); - return objectName; } private static String getBeanNameSuffix(String cacheManagerClusterUUID) { 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 7b720e49ce..7bfa2d7856 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 @@ -130,7 +130,6 @@ public class ProviderMBeanRegistrationHelper { ); this.cancel(); } - return; } else { ehcacheHibernateMBeanRegistration.enableHibernateStatisticsSupport( sessionFactory ); @@ -152,9 +151,8 @@ public class ProviderMBeanRegistrationHelper { if ( map == null ) { return null; } - final Iterator values = map.values().iterator(); - while ( values.hasNext() ) { - final SessionFactory sessionFactory = (SessionFactory) values.next(); + for ( Object o : map.values() ) { + final SessionFactory sessionFactory = (SessionFactory) o; final Class sessionFactoryType = sessionFactory.getClass(); final Field propertiesField = getField( sessionFactoryType, "properties" ); if ( propertiesField != null ) { 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 4eba0d82e7..5be104df11 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 @@ -324,8 +324,8 @@ public class QueryStats implements Serializable { */ public static QueryStats[] fromTabularData(final TabularData tabularData) { final List countList = new ArrayList( tabularData.size() ); - for ( final Iterator pos = tabularData.values().iterator(); pos.hasNext(); ) { - countList.add( new QueryStats( (CompositeData) pos.next() ) ); + for ( Object o : tabularData.values() ) { + countList.add( new QueryStats( (CompositeData) o ) ); } return countList.toArray( new QueryStats[countList.size()] ); } From 8e3770235b852024b6ff0ac7ff764b291d76fa61 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Thu, 9 May 2013 19:51:10 -0500 Subject: [PATCH 20/25] HHH-8211 - Checkstyle and FindBugs fix-ups --- .../c3p0/internal/C3P0ConnectionProvider.java | 3 +- .../procedure/internal/ParameterBindImpl.java | 4 +- .../procedure/internal/ProcedureCallImpl.java | 2 +- .../internal/ProcedureCallMementoImpl.java | 10 + .../internal/ProcedureResultImpl.java | 8 +- .../hibernate/procedure/internal/Util.java | 82 ++++++- .../procedure/internal/package-info.java | 4 + .../management/impl/AbstractEmitterBean.java | 1 + ...EhcacheHibernateMBeanRegistrationImpl.java | 20 +- .../management/impl/EhcacheStatsImpl.java | 200 +----------------- .../ehcache/management/impl/EntityStats.java | 17 +- .../management/impl/HibernateStatsImpl.java | 111 +--------- .../management/impl/NullHibernateStats.java | 1 + .../impl/ProviderMBeanRegistrationHelper.java | 1 - .../ehcache/management/impl/QueryStats.java | 7 +- .../access/TransactionalAccessDelegate.java | 8 +- 16 files changed, 133 insertions(+), 346 deletions(-) create mode 100644 hibernate-core/src/main/java/org/hibernate/procedure/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 207461b1c5..27ef421bd7 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 @@ -168,7 +168,7 @@ public class C3P0ConnectionProvider } final String key = (String) o; if ( key.startsWith( "hibernate.c3p0." ) ) { - String newKey = key.substring( 15 ); + final String newKey = key.substring( 15 ); if ( props.containsKey( newKey ) ) { warnPropertyConflict( key, newKey ); } @@ -267,6 +267,7 @@ public class C3P0ConnectionProvider * * @deprecated Use {@link #stop} instead */ + @SuppressWarnings("UnusedDeclaration") @Deprecated public void close() { stop(); diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/ParameterBindImpl.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ParameterBindImpl.java index 505bca94f4..80d2b3b621 100644 --- a/hibernate-core/src/main/java/org/hibernate/procedure/internal/ParameterBindImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ParameterBindImpl.java @@ -36,11 +36,11 @@ public class ParameterBindImpl implements ParameterBind { private final T value; private final TemporalType explicitTemporalType; - public ParameterBindImpl(T value) { + ParameterBindImpl(T value) { this( value, null ); } - public ParameterBindImpl(T value, TemporalType explicitTemporalType) { + ParameterBindImpl(T value, TemporalType explicitTemporalType) { this.value = value; this.explicitTemporalType = explicitTemporalType; } diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallImpl.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallImpl.java index 0c878894d2..f6235b8aea 100644 --- a/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallImpl.java @@ -484,7 +484,7 @@ public class ProcedureCallImpl extends AbstractBasicQueryContractImpl implements @Override public QueryParameters buildQueryParametersObject() { - QueryParameters qp = super.buildQueryParametersObject(); + final QueryParameters qp = super.buildQueryParametersObject(); // both of these are for documentation purposes, they are actually handled directly... qp.setAutoDiscoverScalarTypes( true ); qp.setCallable( true ); diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallMementoImpl.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallMementoImpl.java index 7af100283e..456198a494 100644 --- a/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallMementoImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureCallMementoImpl.java @@ -51,6 +51,16 @@ public class ProcedureCallMementoImpl implements ProcedureCallMemento { private final Map hintsMap; + /** + * Constructs a ProcedureCallImpl + * + * @param procedureName The name of the procedure to be called + * @param queryReturns The result mappings + * @param parameterStrategy Are parameters named or positional? + * @param parameterDeclarations The parameters registrations + * @param synchronizedQuerySpaces Any query spaces to synchronize on execution + * @param hintsMap Map of JPA query hints + */ public ProcedureCallMementoImpl( String procedureName, NativeSQLQueryReturn[] queryReturns, diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureResultImpl.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureResultImpl.java index 6b52b3f895..d618e3d6c6 100644 --- a/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureResultImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/ProcedureResultImpl.java @@ -35,6 +35,8 @@ import org.hibernate.result.Return; import org.hibernate.result.internal.ResultImpl; /** + * Implementation of ProcedureResult. Defines centralized access to all of the results of a procedure call. + * * @author Steve Ebersole */ public class ProcedureResultImpl extends ResultImpl implements ProcedureResult { @@ -42,7 +44,7 @@ public class ProcedureResultImpl extends ResultImpl implements ProcedureResult { private final CallableStatement callableStatement; private final ParameterRegistrationImplementor[] refCursorParameters; - private int refCursorParamIndex = 0; + private int refCursorParamIndex; ProcedureResultImpl(ProcedureCallImpl procedureCall, CallableStatement callableStatement) { super( procedureCall, callableStatement ); @@ -80,9 +82,9 @@ public class ProcedureResultImpl extends ResultImpl implements ProcedureResult { @Override protected Return buildExtendedReturn(CurrentReturnDescriptor returnDescriptor) { this.refCursorParamIndex++; + final int refCursorParamIndex = ( (ProcedureCurrentReturnDescriptor) returnDescriptor ).refCursorParamIndex; + final ParameterRegistrationImplementor refCursorParam = refCursorParameters[refCursorParamIndex]; ResultSet resultSet; - int refCursorParamIndex = ( (ProcedureCurrentReturnDescriptor) returnDescriptor ).refCursorParamIndex; - ParameterRegistrationImplementor refCursorParam = refCursorParameters[refCursorParamIndex]; if ( refCursorParam.getName() != null ) { resultSet = procedureCall.getSession().getFactory().getServiceRegistry() .getService( RefCursorSupport.class ) diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/Util.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/Util.java index 36e6ffe66f..bae270906f 100644 --- a/hibernate-core/src/main/java/org/hibernate/procedure/internal/Util.java +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/Util.java @@ -23,7 +23,6 @@ */ package org.hibernate.procedure.internal; -import java.util.Collections; import java.util.Map; import java.util.Set; @@ -38,6 +37,8 @@ import org.hibernate.loader.custom.sql.SQLQueryReturnProcessor; import org.hibernate.persister.entity.EntityPersister; /** + * Utilities used to implement procedure call support. + * * @author Steve Ebersole */ public class Util { @@ -51,7 +52,7 @@ public class Util { * * @return The copy */ - static NativeSQLQueryReturn[] copy(NativeSQLQueryReturn[] queryReturns) { + public static NativeSQLQueryReturn[] copy(NativeSQLQueryReturn[] queryReturns) { if ( queryReturns == null ) { return new NativeSQLQueryReturn[0]; } @@ -61,21 +62,69 @@ public class Util { return copy; } + /** + * Make a (shallow) copy of query spaces to be synchronized + * + * @param synchronizedQuerySpaces The query spaces + * + * @return The copy + */ public static Set copy(Set synchronizedQuerySpaces) { return CollectionHelper.makeCopy( synchronizedQuerySpaces ); } + /** + * Make a (shallow) copy of the JPA query hints map + * + * @param hints The JPA query hints to copy + * + * @return The copy + */ public static Map copy(Map hints) { return CollectionHelper.makeCopy( hints ); } + /** + * Context for resolving result-set-mapping definitions + */ public static interface ResultSetMappingResolutionContext { + /** + * Access to the SessionFactory + * + * @return SessionFactory + */ public SessionFactoryImplementor getSessionFactory(); + + /** + * Locate a ResultSetMappingDefinition by name + * + * @param name The name of the ResultSetMappingDefinition to locate + * + * @return The ResultSetMappingDefinition + */ public ResultSetMappingDefinition findResultSetMapping(String name); + + /** + * Callback to add query returns indicated by the result set mapping(s) + * + * @param queryReturns The query returns + */ public void addQueryReturns(NativeSQLQueryReturn... queryReturns); - public void addQuerySpaces(String... spaces); + + /** + * Callback to add query spaces indicated by the result set mapping(s) + * + * @param querySpaces The query spaces + */ + public void addQuerySpaces(String... querySpaces); } + /** + * Resolve the given result set mapping names + * + * @param context The context for the resolution. See {@link ResultSetMappingResolutionContext} + * @param resultSetMappingNames The names of the result-set-mappings to resolve + */ public static void resolveResultSetMappings(ResultSetMappingResolutionContext context, String... resultSetMappingNames) { for ( String resultSetMappingName : resultSetMappingNames ) { final ResultSetMappingDefinition mapping = context.findResultSetMapping( resultSetMappingName ); @@ -92,12 +141,37 @@ public class Util { } } + /** + * Context for resolving result-class definitions + */ public static interface ResultClassesResolutionContext { + /** + * Access to the SessionFactory + * + * @return SessionFactory + */ public SessionFactoryImplementor getSessionFactory(); + /** + * Callback to add query returns indicated by the result set mapping(s) + * + * @param queryReturns The query returns + */ public void addQueryReturns(NativeSQLQueryReturn... queryReturns); - public void addQuerySpaces(String... spaces); + + /** + * Callback to add query spaces indicated by the result set mapping(s) + * + * @param querySpaces The query spaces + */ + public void addQuerySpaces(String... querySpaces); } + /** + * Resolve the given result classes + * + * @param context The context for the resolution. See {@link ResultSetMappingResolutionContext} + * @param resultClasses The Classes to which the results should be mapped + */ public static void resolveResultClasses(ResultClassesResolutionContext context, Class... resultClasses) { int i = 1; for ( Class resultClass : resultClasses ) { diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/package-info.java new file mode 100644 index 0000000000..66aff73343 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/package-info.java @@ -0,0 +1,4 @@ +/** + * Defines the internal support for implementing stored procedure calling. + */ +package org.hibernate.procedure.internal; diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java index d3e4245abe..12d3c448a5 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java @@ -103,6 +103,7 @@ public abstract class AbstractEmitterBean extends StandardMBean implements Notif /** * Dispose of this SampledCacheManager and clean up held resources */ + @SuppressWarnings("UnusedDeclaration") public final void dispose() { doDispose(); removeAllNotificationListeners(); 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 8b39cd7b27..980cdb7ad7 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 @@ -122,9 +122,6 @@ public class EhcacheHibernateMBeanRegistrationImpl ehcacheHibernate.enableHibernateStatistics( sessionFactory ); } - /** - * {@inheritDoc} - */ @Override public synchronized void dispose() throws CacheException { if ( status == Status.STATUS_SHUTDOWN ) { @@ -145,19 +142,15 @@ public class EhcacheHibernateMBeanRegistrationImpl status = Status.STATUS_SHUTDOWN; } - /** - * {@inheritDoc} - */ @Override public synchronized Status getStatus() { return status; } /** - * * {@inheritDoc} - * - * No-op in this case + *

+ * NOTE : No-op in this case */ @Override public void init() throws CacheException { @@ -165,10 +158,9 @@ public class EhcacheHibernateMBeanRegistrationImpl } /** - * * {@inheritDoc} - * - * No-op in this case + *

+ * NOTE : No-op in this case */ @Override public void notifyCacheAdded(String cacheName) { @@ -177,8 +169,8 @@ public class EhcacheHibernateMBeanRegistrationImpl /** * {@inheritDoc} - * - * No-op in this case + *

+ * NOTE : No-op in this case */ @Override public void notifyCacheRemoved(String cacheName) { 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 36d9f4c123..c81d78c274 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 @@ -72,42 +72,27 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat this.cacheManager = manager; } - /** - * {@inheritDoc} - */ @Override public boolean isStatisticsEnabled() { return false; } - /** - * {@inheritDoc} - */ @Override public void clearStats() { sampledCacheManager.clearStatistics(); statsSince = System.currentTimeMillis(); } - /** - * {@inheritDoc} - */ @Override public void disableStats() { setStatisticsEnabled( false ); } - /** - * {@inheritDoc} - */ @Override public void enableStats() { setStatisticsEnabled( true ); } - /** - * {@inheritDoc} - */ @Override public void flushRegionCache(String region) { final Cache cache = this.cacheManager.getCache( region ); @@ -116,9 +101,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - */ @Override public void flushRegionCaches() { for ( String name : cacheManager.getCacheNames() ) { @@ -127,28 +109,18 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat cache.flush(); } } - } - /** - * {@inheritDoc} - */ @Override public String generateActiveConfigDeclaration() { return this.cacheManager.getActiveConfigurationText(); } - /** - * {@inheritDoc} - */ @Override public String generateActiveConfigDeclaration(String region) { return this.cacheManager.getActiveConfigurationText( region ); } - /** - * {@inheritDoc} - */ @Override public long getCacheHitCount() { long count = 0; @@ -161,9 +133,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat return count; } - /** - * {@inheritDoc} - */ @Override public double getCacheHitRate() { final long now = System.currentTimeMillis(); @@ -171,9 +140,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat return getCacheHitCount() / deltaSecs; } - /** - * {@inheritDoc} - */ @Override public long getCacheHitSample() { long count = 0; @@ -186,9 +152,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat return count; } - /** - * {@inheritDoc} - */ @Override public long getCacheMissCount() { long count = 0; @@ -201,9 +164,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat return count; } - /** - * {@inheritDoc} - */ @Override public double getCacheMissRate() { final long now = System.currentTimeMillis(); @@ -211,9 +171,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat return getCacheMissCount() / deltaSecs; } - /** - * {@inheritDoc} - */ @Override public long getCacheMissSample() { long count = 0; @@ -226,9 +183,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat return count; } - /** - * {@inheritDoc} - */ @Override public long getCachePutCount() { long count = 0; @@ -241,9 +195,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat return count; } - /** - * {@inheritDoc} - */ @Override public double getCachePutRate() { final long now = System.currentTimeMillis(); @@ -251,9 +202,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat return getCachePutCount() / deltaSecs; } - /** - * {@inheritDoc} - */ @Override public long getCachePutSample() { long count = 0; @@ -266,25 +214,16 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat return count; } - /** - * {@inheritDoc} - */ @Override public String getOriginalConfigDeclaration() { return this.cacheManager.getOriginalConfigurationText(); } - /** - * {@inheritDoc} - */ @Override public String getOriginalConfigDeclaration(String region) { return this.cacheManager.getOriginalConfigurationText( region ); } - /** - * {@inheritDoc} - */ @Override public Map> getRegionCacheAttributes() { final Map> result = new HashMap>(); @@ -294,9 +233,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat return result; } - /** - * {@inheritDoc} - */ @Override public Map getRegionCacheAttributes(String regionName) { final Map result = new HashMap(); @@ -311,9 +247,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat return result; } - /** - * {@inheritDoc} - */ @Override public int getRegionCacheMaxTTISeconds(String region) { final Cache cache = cacheManager.getCache( region ); @@ -325,9 +258,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - */ @Override public int getRegionCacheMaxTTLSeconds(String region) { final Cache cache = cacheManager.getCache( region ); @@ -339,9 +269,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - */ @Override public int getRegionCacheOrphanEvictionPeriod(String region) { final Cache cache = this.cacheManager.getCache( region ); @@ -353,9 +280,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - */ @Override public Map getRegionCacheSamples() { final Map rv = new HashMap(); @@ -375,9 +299,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat return rv; } - /** - * {@inheritDoc} - */ @Override public int getRegionCacheTargetMaxInMemoryCount(String region) { final Cache cache = cacheManager.getCache( region ); @@ -389,9 +310,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - */ @Override public int getRegionCacheTargetMaxTotalCount(String region) { final Cache cache = cacheManager.getCache( region ); @@ -403,9 +321,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - */ @Override public String[] getTerracottaHibernateCacheRegionNames() { final ArrayList rv = new ArrayList(); @@ -417,26 +332,15 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } } - return rv.toArray( new String[] {} ); + return rv.toArray( new String[ rv.size() ] ); } - /** - * {@inheritDoc} - */ @Override public boolean isRegionCacheEnabled(String region) { final Cache cache = this.cacheManager.getCache( region ); - if ( cache != null ) { - return !cache.isDisabled(); - } - else { - return false; - } + return cache != null && !cache.isDisabled(); } - /** - * {@inheritDoc} - */ @Override public void setRegionCacheEnabled(String region, boolean enabled) { final Cache cache = this.cacheManager.getCache( region ); @@ -446,9 +350,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat sendNotification( CACHE_REGION_CHANGED, getRegionCacheAttributes( region ), region ); } - /** - * {@inheritDoc} - */ @Override public boolean isRegionCachesEnabled() { for ( String name : this.cacheManager.getCacheNames() ) { @@ -462,10 +363,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat return true; } - /** - * {@inheritDoc} - * @see EhcacheStats#setRegionCachesEnabled(boolean) - */ @Override public void setRegionCachesEnabled(final boolean flag) { for ( String name : this.cacheManager.getCacheNames() ) { @@ -477,51 +374,26 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat sendNotification( CACHE_ENABLED, flag ); } - /** - * {@inheritDoc} - */ @Override public boolean isRegionCacheLoggingEnabled(String region) { final Cache cache = this.cacheManager.getCache( region ); - if ( cache != null ) { - return cache.getCacheConfiguration().getLogging(); - } - else { - return false; - } + return cache != null && cache.getCacheConfiguration().getLogging(); } - /** - * {@inheritDoc} - */ @Override public boolean isRegionCacheOrphanEvictionEnabled(String region) { final Cache cache = this.cacheManager.getCache( region ); - if ( cache != null && cache.isTerracottaClustered() ) { - return cache.getCacheConfiguration().getTerracottaConfiguration().getOrphanEviction(); - } - else { - return false; - } + return cache != null && cache.isTerracottaClustered() && cache.getCacheConfiguration() + .getTerracottaConfiguration() + .getOrphanEviction(); } - /** - * {@inheritDoc} - */ @Override public boolean isTerracottaHibernateCache(String region) { final Cache cache = cacheManager.getCache( region ); - if ( cache != null ) { - return cache.getCacheConfiguration().isTerracottaClustered(); - } - else { - return false; - } + return cache != null && cache.getCacheConfiguration().isTerracottaClustered(); } - /** - * {@inheritDoc} - */ @Override public void setRegionCacheLoggingEnabled(String region, boolean loggingEnabled) { final Cache cache = this.cacheManager.getCache( region ); @@ -531,9 +403,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - */ @Override public void setRegionCacheMaxTTISeconds(String region, int maxTTISeconds) { final Cache cache = this.cacheManager.getCache( region ); @@ -543,9 +412,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - */ @Override public void setRegionCacheMaxTTLSeconds(String region, int maxTTLSeconds) { final Cache cache = this.cacheManager.getCache( region ); @@ -555,9 +421,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - */ @Override public void setRegionCacheTargetMaxInMemoryCount(String region, int targetMaxInMemoryCount) { final Cache cache = this.cacheManager.getCache( region ); @@ -567,9 +430,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - */ @Override public void setRegionCacheTargetMaxTotalCount(String region, int targetMaxTotalCount) { final Cache cache = this.cacheManager.getCache( region ); @@ -579,11 +439,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - * - * @see EhcacheStats#getNumberOfElementsInMemory(java.lang.String) - */ @Override public int getNumberOfElementsInMemory(String region) { final Cache cache = this.cacheManager.getCache( region ); @@ -595,11 +450,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - * - * @see EhcacheStats#getNumberOfElementsOffHeap(java.lang.String) - */ @Override public int getNumberOfElementsOffHeap(String region) { final Cache cache = this.cacheManager.getCache( region ); @@ -611,11 +461,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - * - * @see EhcacheStats#getNumberOfElementsOnDisk(java.lang.String) - */ @Override public int getNumberOfElementsOnDisk(String region) { final Cache cache = this.cacheManager.getCache( region ); @@ -627,9 +472,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - */ @Override public void setStatisticsEnabled(boolean flag) { for ( String cacheName : cacheManager.getCacheNames() ) { @@ -644,9 +486,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat sendNotification( CACHE_STATISTICS_ENABLED, flag ); } - /** - * {@inheritDoc} - */ @Override public long getMaxGetTimeMillis() { long rv = 0; @@ -659,9 +498,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat return rv; } - /** - * {@inheritDoc} - */ @Override public long getMinGetTimeMillis() { long rv = 0; @@ -674,11 +510,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat return rv; } - /** - * {@inheritDoc} - * - * @see EhcacheStats#getMaxGetTimeMillis(java.lang.String) - */ @Override public long getMaxGetTimeMillis(String cacheName) { final Cache cache = cacheManager.getCache( cacheName ); @@ -690,11 +521,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - * - * @see EhcacheStats#getMinGetTimeMillis(java.lang.String) - */ @Override public long getMinGetTimeMillis(String cacheName) { final Cache cache = cacheManager.getCache( cacheName ); @@ -706,11 +532,6 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - * - * @see EhcacheStats#getAverageGetTimeMillis(java.lang.String) - */ @Override public float getAverageGetTimeMillis(String region) { final Cache cache = this.cacheManager.getCache( region ); @@ -722,18 +543,11 @@ public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStat } } - /** - * {@inheritDoc} - */ @Override protected void doDispose() { // no-op } - /** - * {@inheritDoc} - * @see AbstractEmitterBean#getNotificationInfo() - */ @Override public MBeanNotificationInfo[] getNotificationInfo() { 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 19faf860c1..4322b01007 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 @@ -34,7 +34,6 @@ 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; @@ -154,6 +153,7 @@ public class EntityStats implements Serializable { * Constructor from compositeDate * @param cData CompositeData of the stats */ + @SuppressWarnings("UnusedAssignment") public EntityStats(final CompositeData cData) { int i = 0; name = (String) cData.get( ITEM_NAMES[i++] ); @@ -166,15 +166,6 @@ public class EntityStats implements Serializable { optimisticFailureCount = (Long) cData.get( ITEM_NAMES[i++] ); } - private static int safeParseInt(String s) { - try { - return Integer.parseInt( s ); - } - catch (Exception e) { - return -1; - } - } - /** * Adds the counters of this instance up with the ones passed in * @param stats the stats to add to this one @@ -210,6 +201,7 @@ public class EntityStats implements Serializable { * The short name of the entity those stats are about * @return the shortName of the entity */ + @SuppressWarnings("UnusedDeclaration") public String getShortName() { return shortName; } @@ -293,10 +285,11 @@ public class EntityStats implements Serializable { * @param tabularData the tabularData with the {@link CompositeData} of stats to extract * @return all entityStats as an array */ + @SuppressWarnings({"unchecked", "UnusedDeclaration"}) public static EntityStats[] fromTabularData(final TabularData tabularData) { final List countList = new ArrayList( tabularData.size() ); - for ( final Iterator pos = tabularData.values().iterator(); pos.hasNext(); ) { - countList.add( new EntityStats( (CompositeData) pos.next() ) ); + for ( Object o : tabularData.values() ) { + countList.add( new EntityStats( (CompositeData) o ) ); } return countList.toArray( new EntityStats[countList.size()] ); } 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 35bc4e0ea2..434be5a9e0 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 @@ -75,52 +75,27 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate return sessionFactory.getStatistics(); } - /** - * {@inheritDoc} - * - * @see HibernateStats#clearStats() - */ @Override public void clearStats() { getStatistics().clear(); sendNotification( CACHE_STATISTICS_RESET ); } - /** - * {@inheritDoc} - * - * @see HibernateStats#disableStats() - */ @Override public void disableStats() { setStatisticsEnabled( false ); } - /** - * {@inheritDoc} - * - * @see HibernateStats#enableStats() - */ @Override public void enableStats() { setStatisticsEnabled( true ); } - /** - * {@inheritDoc} - * - * @see HibernateStats#getCloseStatementCount() - */ @Override public long getCloseStatementCount() { return getStatistics().getCloseStatementCount(); } - /** - * {@inheritDoc} - * - * @see HibernateStats#getConnectCount() - */ @Override public long getConnectCount() { return getStatistics().getConnectCount(); @@ -133,55 +108,31 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate * @deprecated DO NOT USE, WILL ONLY THROW AT YOU! */ @Deprecated + @SuppressWarnings("UnusedDeclaration") public long getDBSQLExecutionSample() { throw new UnsupportedOperationException( "Use getQueryExecutionCount() instead" ); } - /** - * {@inheritDoc} - * - * @see HibernateStats#getFlushCount() - */ @Override public long getFlushCount() { return getStatistics().getFlushCount(); } - /** - * {@inheritDoc} - * - * @see HibernateStats#getOptimisticFailureCount() - */ @Override public long getOptimisticFailureCount() { return getStatistics().getOptimisticFailureCount(); } - /** - * {@inheritDoc} - * - * @see HibernateStats#getPrepareStatementCount() - */ @Override public long getPrepareStatementCount() { return getStatistics().getPrepareStatementCount(); } - /** - * {@inheritDoc} - * - * @see HibernateStats#getQueryExecutionCount() - */ @Override public long getQueryExecutionCount() { return getStatistics().getQueryExecutionCount(); } - /** - * {@inheritDoc} - * - * @see HibernateStats#getQueryExecutionRate() - */ @Override public double getQueryExecutionRate() { final long startTime = getStatistics().getStartTime(); @@ -190,82 +141,42 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate return getQueryExecutionCount() / deltaSecs; } - /** - * {@inheritDoc} - * - * @see HibernateStats#getQueryExecutionSample() - */ @Override public long getQueryExecutionSample() { throw new UnsupportedOperationException( "TODO: need to impl. rates for query execution" ); } - /** - * {@inheritDoc} - * - * @see HibernateStats#getSessionCloseCount() - */ @Override public long getSessionCloseCount() { return getStatistics().getSessionCloseCount(); } - /** - * {@inheritDoc} - * - * @see HibernateStats#getSessionOpenCount() - */ @Override public long getSessionOpenCount() { return getStatistics().getSessionOpenCount(); } - /** - * {@inheritDoc} - * - * @see HibernateStats#getSuccessfulTransactionCount() - */ @Override public long getSuccessfulTransactionCount() { return getStatistics().getSuccessfulTransactionCount(); } - /** - * {@inheritDoc} - * - * @see HibernateStats#getTransactionCount() - */ @Override public long getTransactionCount() { return getStatistics().getTransactionCount(); } - /** - * {@inheritDoc} - * - * @see HibernateStats#isStatisticsEnabled() - */ @Override public boolean isStatisticsEnabled() { return getStatistics().isStatisticsEnabled(); } - /** - * {@inheritDoc} - * - * @see HibernateStats#setStatisticsEnabled(boolean) - */ @Override public void setStatisticsEnabled(boolean flag) { getStatistics().setStatisticsEnabled( flag ); sendNotification( CACHE_STATISTICS_ENABLED, flag ); } - /** - * {@inheritDoc} - * - * @see HibernateStats#getEntityStats() - */ @Override public TabularData getEntityStats() { final List result = new ArrayList(); @@ -279,11 +190,6 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate return td; } - /** - * {@inheritDoc} - * - * @see HibernateStats#getCollectionStats() - */ @Override public TabularData getCollectionStats() { final List result = new ArrayList(); @@ -300,11 +206,6 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate return td; } - /** - * {@inheritDoc} - * - * @see HibernateStats#getQueryStats() - */ @Override public TabularData getQueryStats() { final List result = new ArrayList(); @@ -318,9 +219,6 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate return td; } - /** - * {@inheritDoc} - */ @Override public TabularData getCacheRegionStats() { final List list = new ArrayList(); @@ -337,18 +235,11 @@ public class HibernateStatsImpl extends AbstractEmitterBean implements Hibernate return td; } - /** - * {@inheritDoc} - */ @Override protected void doDispose() { // no-op } - /** - * {@inheritDoc} - * @see AbstractEmitterBean#getNotificationInfo() - */ @Override public MBeanNotificationInfo[] getNotificationInfo() { return new MBeanNotificationInfo[] {NOTIFICATION_INFO}; diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/NullHibernateStats.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/NullHibernateStats.java index 56c66c0e90..eafe92b3b4 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/NullHibernateStats.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/NullHibernateStats.java @@ -124,6 +124,7 @@ public final class NullHibernateStats implements HibernateStats { * Not supported right now * @return 0 always */ + @SuppressWarnings("UnusedDeclaration") public long getDBSQLExecutionSample() { // no-op return 0; 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 7bfa2d7856..fb5c1d90a7 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 @@ -24,7 +24,6 @@ package org.hibernate.cache.ehcache.management.impl; import java.lang.reflect.Field; -import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.TimerTask; 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 5be104df11..ab2f203d23 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 @@ -34,7 +34,6 @@ 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; @@ -175,6 +174,7 @@ public class QueryStats implements Serializable { * Constructor * @param cData CompositeDate to construct an instance from */ + @SuppressWarnings("UnusedAssignment") public QueryStats(final CompositeData cData) { int i = 0; query = (String) cData.get( ITEM_NAMES[i++] ); @@ -203,9 +203,6 @@ public class QueryStats implements Serializable { executionMinTime += stats.getExecutionMinTime(); } - /** - * {@inheritDoc} - */ @Override public String toString() { return "query=" + query + ", cacheHitCount=" + cacheHitCount + ", cacheMissCount=" + cacheMissCount @@ -218,6 +215,7 @@ public class QueryStats implements Serializable { * Accessor to the queryString * @return the query string */ + @SuppressWarnings("UnusedDeclaration") public String getQuery() { return query; } @@ -322,6 +320,7 @@ public class QueryStats implements Serializable { * @param tabularData the tabularData with the {@link CompositeData} of stats to extract * @return all queryStats as an array */ + @SuppressWarnings({"unchecked", "UnusedDeclaration"}) public static QueryStats[] fromTabularData(final TabularData tabularData) { final List countList = new ArrayList( tabularData.size() ); for ( Object o : tabularData.values() ) { diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java index 8069383837..dfb7c24a1c 100755 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java @@ -58,6 +58,7 @@ public class TransactionalAccessDelegate { * @param region to control access to * @param validator put from load validator */ + @SuppressWarnings("unchecked") public TransactionalAccessDelegate(BaseRegion region, PutFromLoadValidator validator) { this.region = region; this.cache = region.getCache(); @@ -73,6 +74,7 @@ public class TransactionalAccessDelegate { * @return the cached object or null * @throws CacheException if the cache retrieval failed */ + @SuppressWarnings("UnusedParameters") public Object get(Object key, long txTimestamp) throws CacheException { if ( !region.checkValid() ) { return null; @@ -109,6 +111,7 @@ public class TransactionalAccessDelegate { * @return true if the object was successfully cached * @throws CacheException if storing the object failed */ + @SuppressWarnings("UnusedParameters") public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { if ( !region.checkValid() ) { @@ -154,6 +157,7 @@ public class TransactionalAccessDelegate { * @return Were the contents of the cache actual changed by this operation? * @throws CacheException if the insert fails */ + @SuppressWarnings("UnusedParameters") public boolean insert(Object key, Object value, Object version) throws CacheException { if ( !region.checkValid() ) { return false; @@ -174,6 +178,7 @@ public class TransactionalAccessDelegate { * @return Whether the contents of the cache actual changed by this operation * @throws CacheException if the update fails */ + @SuppressWarnings("UnusedParameters") public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { // We update whether or not the region is valid. Other nodes @@ -241,7 +246,8 @@ public class TransactionalAccessDelegate { } final Transaction tx = region.suspend(); try { - region.invalidateRegion(); // Invalidate the local region and then go remote + // Invalidate the local region and then go remote + region.invalidateRegion(); Caches.broadcastEvictAll( cache ); } finally { From e9a54405c243e6b7895f17afbfe676284bab79c8 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Thu, 9 May 2013 20:33:19 -0500 Subject: [PATCH 21/25] HHH-8232 - Upgrade to Gradle 1.6 --- build.gradle | 2 +- buildSrc/build.gradle | 1 - .../database/AbstractDatabaseProfileImpl.java | 2 +- .../testing/matrix/MatrixTestingPlugin.groovy | 8 ++++---- gradle/wrapper/gradle-wrapper.jar | Bin 46742 -> 49875 bytes gradle/wrapper/gradle-wrapper.properties | 4 ++-- 6 files changed, 8 insertions(+), 9 deletions(-) diff --git a/build.gradle b/build.gradle index 79e36532ae..b127489e75 100644 --- a/build.gradle +++ b/build.gradle @@ -29,7 +29,7 @@ ext.hibernateTargetVersion = '4.3.0-SNAPSHOT' ext.javaLanguageLevel = "1.6" task wrapper(type: Wrapper) { - gradleVersion = '1.5' + gradleVersion = '1.6' } diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle index d4a8169547..58efbd34d3 100644 --- a/buildSrc/build.gradle +++ b/buildSrc/build.gradle @@ -39,7 +39,6 @@ dependencies { // common compile gradleApi() compile localGroovy() - groovy localGroovy() compile 'org.apache.ant:ant:1.8.2' // injection plugin compile 'org.javassist:javassist:3.15.0-GA' diff --git a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/AbstractDatabaseProfileImpl.java b/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/AbstractDatabaseProfileImpl.java index 0e0edb6fe1..fddaf9d7f7 100644 --- a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/AbstractDatabaseProfileImpl.java +++ b/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/AbstractDatabaseProfileImpl.java @@ -119,7 +119,7 @@ public abstract class AbstractDatabaseProfileImpl implements DatabaseProfile { protected Configuration getOrCreateConfiguration(String name) { Configuration configuration = project.getConfigurations().findByName( name ); if ( configuration == null ) { - configuration = project.getConfigurations().add( name ); + configuration = project.getConfigurations().create( name ); } return configuration; } diff --git a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/matrix/MatrixTestingPlugin.groovy b/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/matrix/MatrixTestingPlugin.groovy index 92b7a8c86a..31686a0dc2 100644 --- a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/matrix/MatrixTestingPlugin.groovy +++ b/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/matrix/MatrixTestingPlugin.groovy @@ -101,7 +101,7 @@ public class MatrixTestingPlugin implements Plugin { * Prepare compile configuration for matrix source set. */ private Configuration prepareCompileConfiguration() { - return project.configurations.add( MATRIX_COMPILE_CONFIG_NAME ) + return project.configurations.create( MATRIX_COMPILE_CONFIG_NAME ) .setDescription( "Dependencies used to compile the matrix tests" ) .extendsFrom( project.configurations.getByName( COMPILE_CONFIGURATION_NAME ) ) .extendsFrom( project.configurations.getByName( TEST_COMPILE_CONFIGURATION_NAME ) ); @@ -111,7 +111,7 @@ public class MatrixTestingPlugin implements Plugin { * Prepare runtime configuration for matrix source set. */ private Configuration prepareRuntimeConfiguration() { - return project.configurations.add( MATRIX_RUNTIME_CONFIG_NAME ) + return project.configurations.create( MATRIX_RUNTIME_CONFIG_NAME ) .setDescription( "Dependencies (baseline) used to run the matrix tests" ) .extendsFrom( matrixCompileConfig ) .extendsFrom( project.configurations.getByName( RUNTIME_CONFIGURATION_NAME ) ) @@ -119,7 +119,7 @@ public class MatrixTestingPlugin implements Plugin { } private Task prepareGroupingTask() { - Task matrixTask = project.tasks.add( MATRIX_TASK_NAME ); + Task matrixTask = project.tasks.create( MATRIX_TASK_NAME ); matrixTask.group = "Verification" matrixTask.description = "Runs the unit tests on Database Matrix" return matrixTask; @@ -140,7 +140,7 @@ public class MatrixTestingPlugin implements Plugin { private Task prepareNodeTask(MatrixNode node) { String taskName = MATRIX_TASK_NAME + '_' + node.name log.debug( "Adding Matrix Testing task $taskName" ); - final Test nodeTask = project.tasks.add( taskName, Test ); + final Test nodeTask = project.tasks.create( taskName, Test ); nodeTask.description = "Runs the matrix against ${node.name}" nodeTask.classpath = node.databaseProfile.testingRuntimeConfiguration + testSourceSet.runtimeClasspath nodeTask.testClassesDir = testSourceSet.output.classesDir diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index faa569a9a0eedc9ff37450fed24a7efd77a86729..a7634b071cb255e91a4572934e55b8cd8877b3e4 100644 GIT binary patch delta 12392 zcmZ{K1yEc~v-YyMyL*5H2<{f#-Q6{Ka19Ft2_9J7-GaM2!3i4NJ-ADdOUV1Z_vZiV z->R*i>FIuYx~J=$IWrx92%HRrL{^l6ghBuS;NSpVS_RR_ui>7FaFp?5aWt<6=Em0g z77*~iBAw47dE}74$pG~WxnTNDz;7Vd;Gd~5Ld&Qx4j3J%1OnM(2%&vMjP2fdf2vyX zL)zB*U9n@Y!MGs-{I{Nf#MjfW^Fs!Jgj`Oo6kcJm_IXdU;+O)yq=Q_Ds_-$!>kpNz zy!Ok(3v;cc0_{Gqir-8yEwN-Zsqr*r*78GKY;r4-x~g35lV-bYF&(&I>W~+WB>B&Q z3WqE`Y3mRo*&v)csBYyY#Gd_SC6Rv4mNk{0vS7I*(hqxk4_t|g#Eiz8E2N^*M27TA-v^kdLV{w(;TYeziqsIVIC9H`j_VGci{GZV+SY=R+>$bDKGSFe9sO@vBr+iDm5 zu!71K0p`|Ojw6)$2V31Enz>m`#FSDhPH8;r@nu$oGE~d2-S>nIvOiukM!aI^>`|-g z&-a1&E186M4m6#L0RX_l^Zymt4+RID57mwSJChb9#b}{n002cq0D$%P2uRG`#Ky(R z($!4d(#A~4#Kg?WNzTa5$imE#!NkVM$tg}<<^z@*);q?eVMbyg1P~G;$d?5^AmkMg z{5dFE&=8|PSP%f8CiTX0Vvoej6Jz};7Cz@79W+;$>hSRRZF>A}; z(Ijr&V+s6)5hrElc*#v*2ej<9oOb)T!dM3B4j>Iu3Q>h49H&c&2Sf&}b&mtIyH6;n zP;DJ&NJNA0Nx(7kjYOy$P)$HC{GK8v>AVW8f^K)9MVIq5@i(nPhzqFb_@Gvy_Y)Iz_gk`LsCZMl?)NOjBP8m`G#4}b`9}xX z)S>L`YAy&jG3t!SGAd0)wVOenY|SEv%xw7IrN4?7SnZ#s;@+h~r0K8I3>`&XFIbgl z^-9>VgU1hU9?vZ)Knc^qwc<--1QV9@DYoizwFcGjQ{_!Szo5i~V7uNt{WP~h?k02v z9djOwh2*^+aIsPUXBRcrD*g#4c^O`39K*r7$yKI4ksedcJt02?g~{BF3ty|`VxNHONZv1g8e2IElEiv2I&g!-tqDghhW}lItAl1pJL6z?E@$@idT&>IaaNUwId8XsOJZUdFH2IZnO}0#19NPaWyg}kjAzSU zR^Xlb(61d;Co)z9bI`= zvXH~Tw#{tnAVp}M&WG7-vLJfk;IIvrsnA(T@~_ORE$1AK96gk71o02)X)AWQu-M_! zLfGlbCv55Pt6I?C*F5~D!!A`aJ4lpHfci+QRM3nY*wDYm@j9TP%h%bJ*W?fCQfUkh z*~p04Bd)YuLC(qbO2-~z#Bb;OPT-SU*Mxjn zee1DWBHVxtg{ykACC9*W!QwXDj$a7;UufB{FWRK88lf<#!v|mzF04nD)MBWfXpPmJ zNHu(E>3^azYV;K25IFkauN+Vn&))Cf;@mO}&g^QYOBzo4d#7(nPB^@;(5SCwxB*vJ zS&@$LfacNW(hAxR6szsp~nOYYlG0YRU2#OBd4@g;6ObN_b zQ6Le^qP0Uj>Bz7E1daNn+(FZ3=tm*%N3arW z!3$+s!er>7Xj?op?*01S#6SL3js$3J0x( zW{inLN!@of8+cq39zU)w(GztUaD{`uUG}67%k*YoUxN#B~Sk} zWiYbaOie+UKij=zcMyHB#^A?Om5%|!oFg&U{3H-!&xo%XwsJ~MB7$D&@0~ocBJq$r zG}|ZT{`g~a;A7|tFkx{eGxv@l8z_~qDx;S_E76OAGezOStq1I*In2IivzL$AwOAA# zEUFGzfrL67|3#KeY5tl~gya$R?^lgUxnGkZ5CA}f0iROhgTFu%f?^izCI!)gEWljy z#GIp9^z=J|S&=$FVHyBRYOx$dxq?ceZd41s~T@jG-ge zbzK)O7vBd9YL^qE_aEH8Yne$dvuMZnIhgI_{W@vEdS5mzPz6j#2b;d;aS;L5=96;e zV`{dx+4`WAbatQ&Z_FOwF2l~?!{GD^(v4K+JQQ)#{bYY62GxFHq}`ijkFD*h4K=Ve zTD0>dj#E@^DSXm-Yejq#?UGh;tzXU^`WIZL9E|st5!Dy^DquDv^ZMK@NG6VLY zVkdIz`@@D%r15Y5i)S?%BAuj4@%; zSeprju%Be0pFoE2$~E}nG(3qO^ryW&35nk!v-;oTo;Zhl_&+9}LVi|~k07&+Wu^F{ znQB&fA2EPC&ag%%Xaqw6&0w@|7Os8*K{QHW2G&%j=0naL(8IaaW0ynUt>_%2CG43P|;6^Bzqz;`{3JRYS?W3Cpn7tRbBQuI+N}k%+-FKc^uRs2pCT;bO`^<6P=Z}>q z5DnVanef(07N8e9w_v$DCz~E8MEKYzaz8TTkCoZ}rM5kGyIIH++=iQbJZS*ECv<0R z`6!;%j;sv*kY@AX73iZV{v`NRI3@tSn}L0oK*m1N4r596kTU$_<@+dd_oTYp?q3tX z45!TgP|x;6F@kD#2oei@LL7@S-A?YxWdgxAP*^dWKM@*r2>dJEu>atEY>Zo7SSdHcxhl4)5xy=PPovsy0EVaT8B= zd14hf1635I0qbt-I|I!{1XX^S*Wza%sIE)83bV(FP%k&ZM!SfWi*6U6pBJvvCKQhY#$77rX;Vk9%SP_S=3Z(OUTN|x`xlkM<*_h)RfG~=GxF3 zk&YW%zU!!Gh0fk?6dj(*mbHeJv#tV}OiW}mw{E27QGuJLna2{e5;mkp_?Ob8_f9Jl z?U-$;T@5Kgs3@fq1>a2eVja|1EP5`EP95IG5lmpr=PK?}i)TGG!3vJH_etVi>E|zh ztH-(iR>e+ibas`jlxBIG89f#}dCI)RlWU}OU=e9uNs(;U?`A$>ox!0j`!x*Yh%@xf z7>$|BZZEm?8lNU*uP)n|#Ko(@q$^QYC)qYJWJ#`U2&q~G3)d@Zr<|3&)mC|o8sRFQ zIX?clTRpsJkt$>CFtQsKwj%G^{w_5e6M z+E*$WMrLLMMa4W-M65Aq$e2J7q^ELZ9#-3@A}i(k^AKV-x!Jnv$}hvp{fx|(wryH> z7gG&plzP~$O5OfeZx=B&qg;@T8AnU#0=k?XAyC%Dysohv7s9Ij62G!g2jfaD)Wm|_ zy2h8kYN@}|b@#5kSWZmu0HQL*;o-$b5`f`HMO;SOAQ8g=UC0fBq8xGH9=f&{K}w{M5G#Ahz`#Ty$s|=*>8toI zajH1i37pMdT*8jd8%t`7J%IM~sd3R9Cbn^#^Lh)!)(p0oYa6S#XIEW*_2UPdh#X?L zEFZ1tM1R&8OF}wldIlzaGDk9deNA4vRwcc&xL3}|@MrUUgAXCjAl>iVI9vC^sXrLD z(*1s(Ik0lS`_jL$l0Hde@8jlBq}xJ;keWt~HZPP68ipXhB028Vl|3MwB3hVnb9H4w z#wo{0()~EOmt$J2k~}hDGf+8CS8~-t^)7s;&^78P{CPoiw- z8(NFMDxu1+9GU2|RWYu6wKS%aW*;~;dHw3!j5BF(OnP=qu;j)R4cJ*eKlm7Z~QDfD#q+4F9k^Q@P zq#Ap;y;hyf6wx5&md|%2lqrrJMVbw?KN(pGO%b1RNE5R1N&4- zc9a5hXg_L&${wztYYna`Ed{9~nz5!1Pmi1gSh@tNrLRiGDSU!Zev%6OUg%A_5`m=K z;=KOKfU>XAnzoON!SQu2GonpAeJSnFEh*EJAXO1zK946*S6vrIQ5Ds~k2aS$Q>!EP z$;v{=nki(}-UnC8d}|s&FVfJKCR(&OrEG9S$Vp8SN=CP}NX3_LB)@7%Mpu8H01OKg zi>{y$iU(=xu;ssc$A2&4>n*e%nuGi!cTKOAEX_|5D9)d6yZUSIDM5Hr8v?JUTh!T ztv5GPaRObWVkHIwdaDRkOcV}5$<15a$J2;yu0+W@V!B$J$zxnhWDoiEw~m5q`p(nh z)a)GeK0E>Tly4@BQao;2a&|yXd$%Zc`3UBRkyh`c{GbzG!YhPgMZFnFT+thyY;* z!U1THU-9Ae*J1{%FgJ+7!@y;eFlY79{oSf6ZVnah*F>5hrL>L+K^P~JR6NTRuIFjh zNR?s!_C<0v>Dj6hqWTEY@|ZnrA>|l6a&e9YeGSTGoAOb=xbL=RO_VVXA8tayQGB~I z?BAm&_!Rsk%`Blmnnn6+6qYn@A>1bGlz#zv&XHSX>4iXw*88t{7Uz3b*k;z&L@OsE zH|O@}vqiIFpwHrmpi$vvpIURqEK`dln%n_JE)o+IWOEAlUL$P6{Nyw`BPWzxbq z8&MI<<=#Z}(Ag<;j4#&D`T3nOrU2d+F;3;Jsa1~J)LMV_OkPHu1)R3la0RA)PWV8ZB!YQJP>RlWKkwod#x#>& zc9VxTeo@I~o3IPI!v1a;R&tJ7x$z~A`{`uT)^u3HJI3*3jKTMt4s6<6k{{6ysZ(9x zIQWGRont*|*56MbIDWTcKj5Z4h{v*AiH$;2Wq|E(%R+0$@Gm?i-Jl+>9_j4A=0z&6G1Y$bwT%x!q>QlZzCj^V#hQ(J7ojRd`f1h&uPx9g9OOf^ zv;Q7bFE_*2vtDp7%7n7)aFljFO^FR)m8~zO{?2V%YWO}EGCZRT)Z(ZYd|Ka;hjnfb z+_+5W_wqsB{ST zY()8&O3j+b&%^@xSu3Zlc&+)+kD!IIk%=p8@g?zigeR*d>~q@6T&s zVeO8Udpx};^!#RuIC52&*M!Nj@Y3>lqegXq=}RW%9j)PO?>Qd!Rtytgq1Ly`r<}PT z>kJcG$GK&-BlTME;wNX36oAt2SR5Q~4IH%Mgp@`?Q-V6wW7uIPX=1Y&S zKmKs=!v2`%13@u$eIMH!_QKsd2Z78#~N{1ZBC&GX1 zl)h7?l{2w+O5Jge$I`#yy9|zmd8>zjzf619&B!fPE9yf#aB@qRi)DCZpFn0)8^b-=_$V$|97V-cS^;IOF{Y1$V_k$zYxYi<-pr%L2t+p zD@a)N>t2Y%362x-sOJa|2oJP93=%fpD7^2us-yW85{RSS%tvZ589ZmvZxNXaF?YRD zxul?UQwyTus(vgnl%YtU5yWkp8GiU29gNbfDc~4lB?eZ%I>XN(dmK05%ZdQ4--;9=4?r+R zMdXnrg>q)dYzOS<_G?>{vIJp8kY!c@<>4TZE*Pgh9y?`1wKN| zu97$Ti}E8%YZ&e{+Q1YScrmdeE~E>3B_Y z&bdHXJsyewOj5FepCVPFU?@*Ep}3aE2ot2EI8xJ(a$Hc@QahpoIo)So_5d)%lR(QD zoL1*NZx6r1ruK?cpDfR!{Rp4!!;J`qHWE7Pd&$WCio>ukOn%!yqFufn0(}VmxSV%@ z?d^If;NkU0s!!`apo3_uQnvcck~=5p>0>lqu*MknT`7`CU|Vu!h;Tc79tji~kSP&)ip9_OD^*uLC zHLRyr^NHL&vMd`MtzuOvNLycjX+*dhvOq;?4MElX0Se;8(SU*6yoTe34Lb(|^cjCN zgw%~wqPE+>s7LHa#GkE6xiSRnovGmZMYrSQhoiIQ6oJRKJ3?Rf22DR6XQ#<-IY!Qp z5CN4d!H^KK8<`+fROr<{pLC-2@opc!u7?~t?%{}Uasr%{03P&fk+V%nXbij)5sSkd z2%=A&L!aW9j4Fj=3i{p}QK-SgTG|EO3!p(ia`nK2-jb+oaO#0^%hW zFB_At{#g0kg6fFy!8C|>YR%e)4pUW_(E+8s$oTkmwWiAR(HyK>?}Iu$30+j&I1pPF8~6^)94Xo?H6D)aO~ z@zPQ;bo8LkLRaKy4Y=@B)S#aTCO98pz?kTlJ=`D6JWD(HG@^kPqVq(S){$n_cbVp- z;JUB;L$NIBR<%KL-4pA;buwnB5>r(asZWlA!~QCU*|CV*#yas76^2d06ay^@?9i_X z3sjbe>FP2*4^Zx~ZFM_|avUdQC57}aKjyG}<5dGW@4>4$O>kt{r4=!mWhDOI4AINI znGlXPe$`udST*4)+cf&M@rI* za!_B@*w(3p6Px@(Rc0wGKE#;eVwWY&#{YrX3w!g0W4IvngEgMbR4^+oe^(zZe`f)|cmBGQ zch1feSy4wwe5|38t#21uLimi&2^j-n0K0OLp*(B$=>9S`8 zW=-EJ->+HRuXiVgo;PH!YlzSFmoYG?RjYD?0&g)im065>tS3yf1)*@3yh+yytMj(| z)r(pEki`^SGZyMKx6$84=YJ9`9AO=ee$%t#p)SlrOfcyf)+2H5YO9D7UznoPriQnW zTdhKx+{iciN(0$+*NsktvVu?bAUO#}bc*&;)tX;NtI1h&=rVT5iQ{x}KBFqUhJu$3 zWZ?_U={05%!`-lIBFL%t-okb;VNu_5C?n;j@6)58kwC#V-1A9W zUxdePQB7fL6TKfdwAPOIwq^N){XFzH5Nr9~LcYv<`*+t!V@t%vZy)(oM`D#5U~5#H z`Gn9ylMc_=2$ReoO2<;yH+VSg9#`y{B~;P~4y86P>t(|f+PtD`hKz8sg7^)(E)>fH zFp$m;Q59Fd?C&A>UtO?`!6pYkMrcaR?^{lVvbYx+VCj3nziRo3G1zsPunMp77L=dsQpTg3iK&3H@fq%WreF)OC1Cq##iX(ceFdiir=^Hs;&KM zELZidMun;&7NL8M?5bNVr$@o+44O}E!slizM?zJvJ_n1HIZ&Cxc*~HP^7c=4dbfgf zVHI@;ttokUP?ku{xhjnZ&4@G$&-@BIO;$7hUozZep#JrKF{oKbR` zFy_0TBU}Q_ zInK<(x#3D-#T=m6QKc)@_iz?MiPhb=tRV@TQ2m@tpo=d=8_!- z1VTxEMVVV^|LgR&dWRnx`0`qj`q)pw1q%RpA_D;AFQ>G=g>Ya(Arz2AJX_8w*+P{A z8cMGNV91NymdsH&Gy)#jr});D_PtEsL@oUn^VlSG8O{kRxs-gF`CKh&@R2iPE}6;! z<;Oce)Ca}~MB5eKc&fSGtoRJx>vX5@EXQ6)Nx#aU79Y?$eC|d10HRPLnz7w6qefaH z`h6a{ib`Wy*@fNyr8%Gg+|AYgcV#H3X4trDx)b9;Lp<3H*&AUuF{&V~ZVhK|Y>lmx z?8x%9eexR+Yb$!wV^EO&Pj~p0iBp!gQX^G{Hj3-kS5)QiZ_0u+*u53Hui5VfyHVL& z^4BGJe8OkcTC&#P&@QV2pv4EP0$8<}^fVd}?j|&J6|fX|U8O)=`uYv2dToxm2lR+T zLl$!1U9m(JzNdSdyV9odb9#8&ZRY~1@(dSpZ5z`qJ6*Aq(7qQ%ZFXt5nh6w4yx__*BiJ`!8j+LG>&+r!#2wJXT>yvyNM5zU9ieyg<` z;STe9VUZC(Q3DN>TH_Qx&XHE%Biq=ubL5njGjcIWXj+hIbKvE^0JWb4V9K z&uv~t_KksCR*cI;;!sAtlfy~&XsyJSemh|>auy*f!(2vK{D-3&By{uFJ?$>SloUBN zm5~LLzBA~xf}-TcR0`d1k#@_{NKRdsXX?{#&ef&Bk3Stj>an>KYNzr3R}mF7Lzt0f zIEe~#G&T-=azpRuut%e*l=8w)7-Dg8q2WBr2;&71AT24rMv zG#}9HmTfr|AH)rkWZ{}eFMsO!e0wyD6~}HIQX(7A3-tI|KXag>p5qa|X*vWwiRnbB zMY}7F#P$^%lm<0zC7M9E9T*3Wn{R3>Eav%H>?t*OtnZydz0s9ur>oDzg`%+f_Fn-R?Wt_ntIX*!fF)PmXt8LWGgoHT^U%rrhPPA zjk*E*v2w}4ZF+^@Ko#Cp`?VV`b{IH_^vXdVZ`i}6chjr)6oxLq&}u3<^mVK_%yiJI zBb7*LdXtDVs%tS9f2Ezb-5)a6%bq_f+^WuYs*|$0Yq>aZ>APxb4QV}UcoG<6+Cnd! z=`RWdotJQ8lj7Z=k&d50u%WfQo>$dt-4`M{(iqc<(&3FwsnXg>`alO?K6v$f1)t1T zo$s=o;I3#eU%hfnxm0^zmuJ0Sb`lvXR;{}#_0w`!GUe))Kl~f5(b|x+T(H-VnM1<9 zisitrUc|PZUCFGD2Uo$y!VjPZmHHn(;GJ5i^j7#(jK9!y)bVhp7j~6rmSl*3?8~tVY6vQM zTc%#|j-(`$7ysw3y}@LR_GTstYHuw9$sivId`mFo(%n_R%(hUg&T&_y@#dx5_$|Nd zH&0skS=^9Mcapl+b0kHEGnY@x;HD_G3SN>XSbCD;Ot(!E7;#$nO`f|Lag|!yX@`xR z6z>GIvUP%$4T5&Z87oPx-8J`)@*EJFbwQlz)t4TA8T@&P=!lau8Y}}jY-<0zD5ymcM+r<5d3BkyzIg8|%(@IoI z??W;vZqPSsK`fW)&t{HH2rbC066XoXbafbvt`>391 z9rRt?{C2H0e!IPBd@}^EB`|(ZlXU-lZZ?O=!q|)J^{2|#GxX3yaMXtq1O6$^Y`tFq z$Rr$X=!v9NMIOx1;EALUe5s>_4(w^;L6b>WCvdPogzr#b?59?b&LQ*h-6PS4b3TO} z8OAgxZS&`IbZt_KR_}+X8E^%teLs8iJ+bCC74(e;!9}!C=Z~&Ubn&!`8=CS&vju6;7~~cTpBsG z6S)#qCMFFgwi*_;N){&N53a~4;1x+m__F7Ev9g?em~UWQDN0aer(HK0n&|PpGWUAw=EXEtOn#{oEX9wfT8i^POOxv1TpQxDYC2xNztOVT}<- z;Oc(xPUv;kr54f$`mjY+tKWx2j3Q|5l{gZ5LA`Z#tjc{0sr`a3ZG z&;v23%3O!{=2xb6DvkQUmBlxB#9ETei6_B@d*J`Z;@LYeyfhu;Gp**5W`+FS0Ncs! zy)d-pZ-6fiHKqMO4H4BCh!@VR+9K>rqh62dMX7qlko!-A(3BVYWk}2N_K&cdHTxgo z2*>e193$t-KY-Y7vuH2EC&A}`INPCHe;T6^uzzr7V<7(^FUOq%(SNT8WrOlP9|QoP z1qlGqfR$8dH>(V zuVblFd|CXm{5O!#^{U|6e71k4>WJTEn=N(GEB^iu)H3vDUjf1wWr^8cq+RkhIa zh1*d`2y}%4M?+D92}+R2{;LG>c`pC?<@y;yKMP{x{r@Tw!O=BXF9`oza{>U+|403q z=K9qk{ziDNLLmU_79qXNz`BSKXoT{@PAj5$VGTU9;xNI{UtfXYiZNaw|Edu93-X-c zSr-SaSd8}vu9y%=LHh@;`1Omfxz56=&~xcQEe-%c{g*Bi<3H1Z1wR!Nyyz2sB?Q)U zzp&-MQoQK@b)52-KBeeCwqe-*bGo7^0|CT>{8L)|JDLQaeebKD6GHttA-Mih_LP41 zQ2fQhUpwo+g#2Y+rt*8EjaBj|6#qUTo&_oX624UdM@dqFtxJ&p&$Gd|1REHp3MP{x z_&xAD0l^(5guq}m@KOo!OZVZqTc-vVti}f$N)v$PO8-ddmJ$LFG{I|$L||VfSa7Bs zEZzTg?svK(_%|14Jr@^UKOZ*n{WXBSP$)AqieqD9xKlV?Vj-j{=(9;`4{V|oc6`A)O}d*-E#>G__;3k^KkE=1M{!q7PWUQu3vn z^xRzm{X31hO6C_faup#E?Ek_RbVC9s)%@|&=$UN?{#W`W8yfuPGxC2em(n-m@PucN zQ=y-Wi~n-MH2xoDOfX6{#)~5ljbap)&mNOMA0qPpB`lltoGVf<^9ipe1gfV$JMjwq zp8#+Ugq9~g8!3LyiNBXfH|rlG$Y8pfS1wB(iuC>p-?-e`NnX_ljY&c@-F#?vR3L+9Z0PyrFAkoV|35)qDOh}uNnjR;K>J#kj zZ0;Zc{*RIXqZHF2{uX1bZ~^81EkGIFfVnMVxjqfbbp^Ax{z9x6+`%E!qjH}i6P>*Sy6*Lb;rKeb z2lb;5x*3&;voGS|H4+!gii(IoIa1akRCiClw2^=1(QJ7~ zgX0kyi9*eD^sx4h%&k{X{YmAXdN7?RL)-SdgQV zYD!4lqJjI5sye2DA!yJXk;I`{9<9zb+zCN=dt{qkP9XI$;zm@|H5ysefud9~us@t2 zJ+EZEJC8Mu2F$=6>bT{mF*ZDGxa7pyt~KyF=K2-myFf)Fs@=6dn+8E&2SQgg=9*+V z!7Gfv_7W%*X%GANwwW8$n~g#Q04UHvUoiNADW~rE3Zx^wmAFCM$pED$9!6)UxL^VP zdHZT|e>7PgG};vFOrZ=lw@-~eBP&$4P?tlD90&Okl6%Bk1<%`~?^5QSlOCkkUju`J zu6>Cg9`-KH01Gp!^x=`NV#=F5f*_ywdHCre)FY{h%dRP593%A%+dB1P1QRu{gW@-U zzL-Q2O{T)rKxgXa3eUiQerdILOeL0gZMyi>4_15C9|)Js2aR$!I~&!EaJuAq`=Jav zk-n~=(tRe-O&Ip3%YAsQgR^o%BgoD?5_2}B!aC1@Dl0E}s{BBEVJp|}8}ZlBH>n#$ zMsX$;Dda6Ku8WDfo+sVbQQdr14~;4EZ~BVE&3eZi;b^%=3!f%oyx68DyhIN;W*p`g$U4Z2nYx zcD{H*%cjHqn}FC?{4px@vV$PiUIjkHwU82LpW-CyVmIG*6?&&Rwj7Epym{MVU7*y+ z?(KoRg4mCW>^=9#E4^ZDdD^|FO-dKyM^n!ZuxSuf_II&qGQFmRdAwA4vXSSJ7Ld{+ zYy!p-1HVnHfG=jGWNH^D;tG@Os0MQ**x&HX33R=b85FDG=BTu~+ea zzFL0f*cO3#PkWmn)1{_ANY6{&UBE zdxuy_C!17MCx-!~zaF7I2&*+FLyyOP@1lK3>oa?b?Mp(8c7?!p;OL?`S&_G)yiR0` zD>@^j^`aK(!#J%klcE$BJ{TzVR%h}XY2q*3ZQ>riVAbBVmkVIpR<>?Tw;zy>d~T+ZS#C`iht6+E9n^_s+_1qCaeE`MK4r!oYp4# zD;Z(~>3b(uDSk3*eKa=>tb#FGe?lE9#AGa~lV?&T)`=v_i8OPxI=qS$F_zaO!5rbV zICtqZkH~+eY~x#O9%Q`VIr~iA8I2qj0C2?y0GL5ZNW`E@Wvs?o0(Mk*_bz1cU=h}} zL*5|G{6U*3u7@MEH+j_zb>HaXzGd<*j(?4c!ndQpS}trdgk0vl`dbk*`Ms z92+_mi`8pVZ0pDMx)}TB(HB{}bmg1bk2giYUT)n36S{|ZEuzAt>pP@pYP^@u;reAB zB(=IeVCBFr-aaAJ7liBc>?S(`I{_HA;XNz3>p;&76E1BEqPN-(=~=}N2WYHw-|8le}WK(8rj5npUA zmJ(%4REJq=wQo+!2=;?EN#q=j$!8~UJFIRe5-pA-S*jFl4(E!QqOXM<^!%D#0+O|G z?BmVj(Z2AV#X@ZJdP2Zj+>X#_s>A2Q|1pnV@G5HY?u^P>cjs3%j^mPh+n1O0xz&j*N71BPh&-V4V z2AK_C(z$=_`c@G~e4MMx9`X=GuZgU0MtpG!CSpT<{tP&jSW)=2o6SKtueESd`BSV@ z#4|fyCGFlsM{@U=k>eYWrD$L&C9Cs3Psw$5jqjx}7^f(Er7DuTlGejF>tj<)R>x-N z#tjdNqd9K}#gLY3v50*s{#Hb3dumO`@xV)lNbfgtPphuohzV(?@V8XTNx70K`SVK>o9SO&Xpafxkob_l!4(=Bm1)=K1w`z8Bh#{CgZVze?7y`9ura?U2fxmi+_ z@tpgGQLKQ(U|^r3OhbS2Yq4~?XB-vel8n}sroA=10;lylGf^1eZ7k<+BDexjMg*tG zZE~h0RXWd7nO#}?Z$R~M^(}ff9@UUxVT&+`4=Fl>Pjrq`tLA%wpl5k{Hx_X;8?6p^ zUO|M8rQL6;&#msT@fDM?*2opV zhJ}DEBizN%O*B(B(0PNrXo^*jwj6v1{KDb(Y>evYWZ*NKjE#j7P%L*yKXkw$Vd zY7&GHpTow`N(k)6CFGVq8t+jX3^LMQhVCUcYsSA#%OH$3%;2 z(FZ$q6RV_uD*SQeOqAP{cYmaJmT(zxvt1bo<#cbZDJ!zKsV?j>nQnY~XK?OVvabm; zQkIm0_{;zq0#8J({>h5&f4>-=5^-epQ5qs?f!OoD%F~6lxYdRiB2%hM<9m;ZWeb!a zGfFfU_R0$+563FCQkR!d(}KOqiCZ1^4S6PWAN6!5o7P23NWMoN)4F+4#@PYbXOO#I zMk^G0Go(p?w~DR=hT?v}?OgLW^xn?WI@4`89SsGxw>|ffO^H`k_ z`EGd)v2>~n5V25h)_qBgEkso^?;$CGpOo;Pu$Yv`fE1jlHh&TIve$4G?*^rAR}=l1 zEmr>J)}XiRC5Nl~1cokTgclktVhJ?@dr{b zfBG^Y(mm<{T>xFlHa%Mr-Z=p$-}YKUi3e(CgF5i?a$82@fE_FKi{{75$;I+2F%6>r z1~PU@jgehNs-&P#lnxAyO^UZ*zNWSg^v{@_8O4V+FS)s81P0R_95Tx~h-0exbWz`v zRYb-nFPN{RbB1~&4A8weI@Oh3zo>cX&dsd?6!HWwvhS65EC8u_$7`q2OWZw_{GMfW z%zg9=e>J9C3Vmzq2cD~m7W+V_i1})A`i%x>5_wg6vA`fnO?Rq-S4<+<*LvR32A6e3 zhnWD2ET>BCo6O?fDFM`pK>e~}*`|!*SNU%d-%BJhyW}b4 z0u}DbNZ9e$beiyw{n(KMbl()PzscX3i->AvfKYindx)?{jDyJc?F#yZ3C<8SW#kqt zAA~l6zsw5WdVW(kD-zxJZwd`k6g?PeiqY2+sxAD!qV9j=b+~cgl$HRI$SvZQl=bc; z^@}AA@n-1;e?dq!3+sxUsr+bg<`=e#0t^gJ#~hgU7Zpd>1z!{{{lcbI*=dBT`%$Lq zo)b3tQL>tRA?}V@Mf86qv*6!f8@u2Zwi>C2O#T?Qda5j{A^8!<+*q9k!5u50JEN56 z(qi(4=MrzU&wXK#JCMi>dF@2_@Flkk5ouap;quwn>9uR+(zQhcLnFfmeBQMhN7W7gR%KYL452`HJ?j-Hi8L`RzM2M$}(XmYElHWF{U+q$3 zoyJAKmi|nLwwUr#Ukgt#hvAV)3D}={_<6MHennCthrxzxHWkn8>Nu3);jlWCp?I{Z zrr+S(!Vb=@oqcE8xOaA`fN$U0hK)7$A&LDd+jMJz&C4iLWY1aaw@bsSO^`ZX24yVq*_K{`L}s=43yNa{KB;<)6gJi)sqMs7z4 z$OHdN?0W@-6%Ie*@Sj4{y|EQHVuzb5Wl^=Xz@85S|4=C=_6>(Xbw(TP_R}^lBFmq2 zN+N$qU|;|uGl>BlaDta>>4$(O>yI4bk+_l=-!x|BCdE&$gFaVJ={H*RMmwd{El%ry z>^E2(;F_`Pn~Hp3vfn0pU?2srcXs)$%XRGWQf24&_oN=m@bT+jD6wCeK~1u~QL>-- zP#1~JL2cHb5zqNjLK+0Jv3d`v#hEU2)D6Fsek=yKtHfks9^X)|o-PCH8?L~1_MVL~ z)eB&XC(j8d)O+XFwAVh31SGT4R*$jOqhQme0FdQg$~<`;jXxa>b%_`>A}JP> zGDa-3U2&rwndfjDj1>Q|FW0eI(Z%$mhV$*1#a*|o`+@8u9=Zlu&ow1hLenI~NX$46 z+G>)|pdE)gLk8wsFN*|T`A=zezlN}fTGiP^#3L4(Ibz@1?Dhylo%#^v()Fm{^m+_B2rh)i@~C z)a%~aPOT}VtMO#aX?D+8R`<#0T8K+O8#@_v87lftw`BKwI8Y3DHe2I^?mkd$@gYxw zV&BCfD}O9W{c)tMq4~2uMzw}<+jZd3m~2qaBw5|c)f#fsRK8na<|{x7U7sswaQX+l zbXz^AkBj?1O^7J=FQKUG+VVoPB>On|mQ32`2`eILI`v4A;iI?s-4td-?i!HAe2z!S z|2jV-c=`*eoGT0+-WU>o^QRH1jEn$3JX?Gf4b_I7t#hyd06O^DnhW76 zs8baiIFia=c)l(tC>Sl{O4)Z&ky*kKk!Ws(&lFAf%8A}ydIZwUnP{7mfu|w_VNwG@ zn4BSk4k{fHEe8l}qlBVLSrRxjw`R8_-+H_`j2dQSx>t6Nes=BUwm;rZScq&k zcg_@G(9m13(GZ_@t|uIzHnMmgM|+o7p38jI<={%=5ntAt4zRqvA(#b~&t-gIu`9`a^^uX#DWi^ak&n}5VKPm& z5K~WT_GYr)3N&k{{XqxBc-72q&lB^ht0|?inyrzRP&V1_^QEnriy_8&%HDQWcqrpS z)MxaOog!KfR=b_9LG)Y8pNA_d2YGrx-1NFe=uGmYfn|kmI>8tBUE|fCZ|o-Tst&fd zd!#XaVuWoi{2^Y%n;7vKpJQ&2BlDlK1kLrB?>O^KtW!@eEd;#H-;Vlxa6af1t2AZU zQt;7Sfyr3K=RD&;mT4}VN-}i>{wteG-J)f~>sbVFj>BxpS+zPSY%P6%~cq-P`bt(3vNxhyX zk{0t73QyHbQiQ~L8i|YF$G--40}W@;rv2jfwas6>HZUkxtIR^LtRAmOO*yW4WwGSt z_(36il0L5ZC>eyuJ70Cyj82;5g-JOS7IOc>+*}oVE8Se3M7;Kec8VU|)~jTM{4X zjbgBP$~p55Q=u09#0b6$68E42LDhc3Z?hIc}G^Llp})oMEcnY^%}vZ%|()2K{acbTd_z}}-qFj0*r z`^4mJK-x0F@(wlh@zyc53l%soEiB=kDp$IBit-SmQRYL#k=`Y;A`9-m4|*BTZeM$A z(wjk1V1S%;@EX??`9cNVYw^I|Gp1X}t9Q4_ea?j?=SSLGogWJ(8&pJ>wro>B=1gW& z1xJ4g#(rbp$iXFXui3l(eoV*}8oTOI)-e9oq%(8=3n6><#4e@xXYFEOA=^_wK_jU+ ziv^rj|#X4Cko}*F)5v3qte0+)`dsGdmb|=~}K;Bg{=AE;g|u zn+UM1E_HtUk@yvtsy740s&wQZg66nWq@?OXW0{gyS|??CwW{e+@qTOt-;i1M@TkD* z1Za;kTNLA$DgCOeUY~{`KqwY|yYDhvx`+42_|Dm}&q9@^`I~e-Rwy@pr1Ah9a~z4m zD~5o6{`JO{)9SCMGO{gNH4F_PH|%6@+{hOa<2g!X64cWYbx1bmXT;|-_M&lA`P6dSK=xZP&;*2iBgr5v1v*`PM?kE5g?CpimR~kkVmxfh(lh! zHPmn7;q1~#Kq)jNTZZ@#Vx3xQl=cYRMYn65&WYl3hOKo)U*k+u`PRiAODG-9Miv@w zExaSk>$qO)Ol~cV&9y&!-eg}F8yRt00Bnn0b=;@oJ8aM!iwBa^tgRcoZ<};sy8+JU z>GRpky!yG zWWCNz4oZqNsGXAaa?6fB+I&GAb(E^Z4PhzOWMpO$fUH#nMum7VG?Qx|^qI3$#iHmO zX!55hS854>7b3I|7N)sT7o-mbQEF>TI~ToulH+Gp`+;mtJlW2e_Nb=o&OS*t{=*tG z&^P8_L{zr(_rSeOpCOWa(ZylioQ;a4TeN`ONbhc-8_J~w|ouRsH@pyoR-ERd}(7n(mznahnlX#kX~%Lr8Oemh8uyXp&Oj|#P% z4JkG%W>=}KnGc!5PI`h-H$TGVkh$FR=4G@%1Q1&V6pETSmv$ak$HX2Y|`2Ovg8M^wjb7NxSLxq8AQ@2LG z8t@Vk&Rv1FjJgK#&FH7rM2^Kv&IfA9!)(7yTEO~vw)qP^c2uGkZ~)WVQD86;aJ3Nj zNL6r&uqd3RYB_Y~6HNKR*%{olI_Y-FGmJq|>eY#h|%L;T$U{d#=>2X+i@ z5a5k<;~#$-U(Ax9z!58p6;!<6)AE=YfIEu-04$>b074*F3r3J+FG{1I!|@-5H%`KE zn~fzdqR4Q~ZI54nOssnepu!Q-pqW3&5wQM`*2nitxbQB2(B&V*HFf7t!yp6oj~%OA z#6OlD^3VTtnG^;8f6K)$k>KhK71Mu^>q^Z(9Hp9MM6BO&hX%xi%ER`6ENH)8^ncgB ziB~}H_u7jzupq(;=OF6_{{IxvK_44L;KlLp4P0=E(vj1rlbbL9n1sDOM>gTZ$^V<%|MH7M+!aAYx=f(5HcZ;z3lGm@STFh$ z0D$yg7EBg}ASr?7+L(WD9MF9m1;U*Yh`gN&ek;;Wf$&Tj6xd4!de{DkkpY7&)IeGe z44|*=1aQ_V3{q2vLtGs!aLAy80zpv=2C;$iI_Tm4)3Qb<j9s20uy77G!2%pkn z5GBaJodQ0lm!FGx4q(#~fB^uA{W~C-EDBM~gh$HM|7Yzr`Y8}%azRf03UIybMkOF3 z%x5bsn|S}yGyMqHW39sby(DmQf?&3g7|h8yEbT=9BG(td$^JFupqKrB$p3ki!H6_} dk>yK3$Mtle?t!P+oUlhsD-HlKR`Q$i{{R;owm<*? diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 3c7e5519fd..4e3c898281 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Thu Apr 04 13:01:06 CDT 2013 +#Thu May 09 20:32:29 CDT 2013 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=http\://services.gradle.org/distributions/gradle-1.5-bin.zip +distributionUrl=http\://services.gradle.org/distributions/gradle-1.6-bin.zip From 9a590c8e6900a4e421909b4fb761a7b311014686 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Thu, 9 May 2013 20:36:14 -0500 Subject: [PATCH 22/25] HHH-8222 - Implement @NamedStoredProcedureQuery binding --- .../src/main/java/org/hibernate/procedure/internal/Util.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/procedure/internal/Util.java b/hibernate-core/src/main/java/org/hibernate/procedure/internal/Util.java index bae270906f..822eddf167 100644 --- a/hibernate-core/src/main/java/org/hibernate/procedure/internal/Util.java +++ b/hibernate-core/src/main/java/org/hibernate/procedure/internal/Util.java @@ -173,17 +173,16 @@ public class Util { * @param resultClasses The Classes to which the results should be mapped */ public static void resolveResultClasses(ResultClassesResolutionContext context, Class... resultClasses) { - int i = 1; + int i = 0; for ( Class resultClass : resultClasses ) { context.addQueryReturns( - new NativeSQLQueryRootReturn( "alias" + i, resultClass.getName(), LockMode.READ ) + new NativeSQLQueryRootReturn( "alias" + (++i), resultClass.getName(), LockMode.READ ) ); try { final EntityPersister persister = context.getSessionFactory().getEntityPersister( resultClass.getName() ); context.addQuerySpaces( (String[]) persister.getQuerySpaces() ); } catch (Exception ignore) { - } } } From 5373be01dfefbcb57bd56640bfd2cde48b6095ce Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Fri, 10 May 2013 11:10:29 -0500 Subject: [PATCH 23/25] HHH-8232 - Upgrade to Gradle 1.6 --- build.gradle | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/build.gradle b/build.gradle index b127489e75..abea8e632c 100644 --- a/build.gradle +++ b/build.gradle @@ -406,14 +406,12 @@ subprojects { subProject -> } pom.withXml { -// sadly for some reason it is not working within the closure above to define the descritpion... - asNode().appendNode( 'description', subProject.pomDescription() ) - // append additional metadata asNode().children().last() + { + resolveStrategy = Closure.DELEGATE_FIRST + name subProject.pomName() -// ugh, see above -// description subProject.pomDescription() + description subProject.pomDescription() url 'http://hibernate.org' organization { name 'Hibernate.org' From cf91fd7a4930052bfea4306866568da68ec261e8 Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Fri, 10 May 2013 12:53:28 -0400 Subject: [PATCH 24/25] HHH-6813 @Id @OneToOne cause NullPointerException during query --- .../org/hibernate/cfg/OneToOneSecondPass.java | 19 +++++++++++- .../OneToOneWithDerivedIdentityTest.java | 31 ++++++++++++++++--- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/OneToOneSecondPass.java b/hibernate-core/src/main/java/org/hibernate/cfg/OneToOneSecondPass.java index a428cd3465..a922034d74 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/OneToOneSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/OneToOneSecondPass.java @@ -32,6 +32,7 @@ import org.hibernate.annotations.common.reflection.XClass; import org.hibernate.cfg.annotations.PropertyBinder; import org.hibernate.internal.util.StringHelper; import org.hibernate.mapping.Column; +import org.hibernate.mapping.Component; import org.hibernate.mapping.DependantValue; import org.hibernate.mapping.Join; import org.hibernate.mapping.ManyToOne; @@ -212,7 +213,23 @@ public class OneToOneSecondPass implements SecondPass { propertyHolder.addProperty( prop, inferredData.getDeclaringClass() ); } - value.setReferencedPropertyName( mappedBy ); + // HHH-6813 + // If otherSide's id is derived, do not set EntityType#uniqueKeyPropertyName. + // EntityType#isReferenceToPrimaryKey() assumes that, if it's set, + // a PK is not referenced. Example: + // + // Foo: @Id long id, @OneToOne(mappedBy="foo") Bar bar + // Bar: @Id @OneToOne Foo foo + boolean referencesDerivedId = false; + try { + referencesDerivedId = otherSide.getIdentifier() instanceof Component + && ( (Component) otherSide.getIdentifier() ).getProperty( mappedBy ) != null; + } + catch ( MappingException e ) { + // ignore + } + String referencedPropertyName = referencesDerivedId ? null : mappedBy; + value.setReferencedPropertyName( referencedPropertyName ); String propertyRef = value.getReferencedPropertyName(); if ( propertyRef != null ) { diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/derivedidentities/bidirectional/OneToOneWithDerivedIdentityTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/derivedidentities/bidirectional/OneToOneWithDerivedIdentityTest.java index 6183728f06..d530da8612 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/derivedidentities/bidirectional/OneToOneWithDerivedIdentityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/derivedidentities/bidirectional/OneToOneWithDerivedIdentityTest.java @@ -23,14 +23,14 @@ */ package org.hibernate.test.annotations.derivedidentities.bidirectional; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.hibernate.Session; import org.hibernate.testing.FailureExpected; +import org.hibernate.testing.TestForIssue; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.Test; public class OneToOneWithDerivedIdentityTest extends BaseCoreFunctionalTestCase { @Test @@ -57,6 +57,29 @@ public class OneToOneWithDerivedIdentityTest extends BaseCoreFunctionalTestCase s.getTransaction().rollback(); s.close(); } + + @Test + @TestForIssue(jiraKey = "HHH-6813") + public void testSelectWithDerivedId() { + Session s = openSession(); + s.beginTransaction(); + Bar bar = new Bar(); + bar.setDetails( "Some details" ); + Foo foo = new Foo(); + foo.setBar( bar ); + bar.setFoo( foo ); + s.persist( foo ); + s.flush(); + assertNotNull( foo.getId() ); + assertEquals( foo.getId(), bar.getFoo().getId() ); + + s.clear(); + Foo newFoo = (Foo) s.createQuery( "SELECT f FROM Foo f" ).uniqueResult(); + assertNotNull( newFoo ); + assertEquals( "Some details", newFoo.getBar().getDetails() ); + s.getTransaction().rollback(); + s.close(); + } @Override protected Class[] getAnnotatedClasses() { From 1337d36a798d9d33542bdfaa24f6ba2cff785e46 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Fri, 10 May 2013 15:28:03 -0500 Subject: [PATCH 25/25] HHH-8235 - Drop database profiles upstream --- build.gradle | 1 + buildSrc/Readme.md | 184 ------------------ .../database/AbstractDatabaseProfileImpl.java | 126 ------------ .../database/DatabaseAllocationCleanUp.java | 53 ----- .../testing/database/DatabaseProfile.java | 45 ----- .../database/DatabaseProfilePlugin.java | 169 ---------------- .../DuplicateDatabaseProfileException.java | 39 ---- .../database/JdbcDirectoryProfile.groovy | 48 ----- .../database/MatrixDotGradleProfile.java | 82 -------- .../gradle/testing/matrix/MatrixNode.java | 79 -------- .../testing/matrix/MatrixTestingPlugin.groovy | 159 --------------- .../build/qalab/DatabaseAllocation.java | 39 ---- .../build/qalab/DatabaseAllocator.groovy | 101 ---------- .../qalab/DisabledDatabaseAllocation.groovy | 47 ----- .../qalab/EnabledDatabaseAllocation.groovy | 150 -------------- databases/.gitignore | 3 - databases/derby/matrix.gradle | 25 --- .../derby/resources/hibernate.properties | 40 ---- databases/mysql50/matrix.gradle | 25 --- .../mysql50/resources/hibernate.properties | 42 ---- databases/mysql51/matrix.gradle | 25 --- .../mysql51/resources/hibernate.properties | 46 ----- databases/postgresql82/matrix.gradle | 24 --- .../resources/hibernate.properties | 42 ---- databases/postgresql83/matrix.gradle | 24 --- .../resources/hibernate.properties | 43 ---- databases/postgresql84/matrix.gradle | 24 --- .../resources/hibernate.properties | 42 ---- hibernate-core/hibernate-core.gradle | 4 +- .../hibernate-entitymanager.gradle | 2 +- hibernate-envers/hibernate-envers.gradle | 2 +- 31 files changed, 6 insertions(+), 1729 deletions(-) delete mode 100644 buildSrc/Readme.md delete mode 100644 buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/AbstractDatabaseProfileImpl.java delete mode 100644 buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DatabaseAllocationCleanUp.java delete mode 100644 buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DatabaseProfile.java delete mode 100644 buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DatabaseProfilePlugin.java delete mode 100644 buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DuplicateDatabaseProfileException.java delete mode 100644 buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/JdbcDirectoryProfile.groovy delete mode 100644 buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/MatrixDotGradleProfile.java delete mode 100644 buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/matrix/MatrixNode.java delete mode 100644 buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/matrix/MatrixTestingPlugin.groovy delete mode 100644 buildSrc/src/main/groovy/org/hibernate/build/qalab/DatabaseAllocation.java delete mode 100644 buildSrc/src/main/groovy/org/hibernate/build/qalab/DatabaseAllocator.groovy delete mode 100644 buildSrc/src/main/groovy/org/hibernate/build/qalab/DisabledDatabaseAllocation.groovy delete mode 100644 buildSrc/src/main/groovy/org/hibernate/build/qalab/EnabledDatabaseAllocation.groovy delete mode 100644 databases/.gitignore delete mode 100644 databases/derby/matrix.gradle delete mode 100644 databases/derby/resources/hibernate.properties delete mode 100644 databases/mysql50/matrix.gradle delete mode 100644 databases/mysql50/resources/hibernate.properties delete mode 100644 databases/mysql51/matrix.gradle delete mode 100644 databases/mysql51/resources/hibernate.properties delete mode 100644 databases/postgresql82/matrix.gradle delete mode 100644 databases/postgresql82/resources/hibernate.properties delete mode 100644 databases/postgresql83/matrix.gradle delete mode 100644 databases/postgresql83/resources/hibernate.properties delete mode 100644 databases/postgresql84/matrix.gradle delete mode 100644 databases/postgresql84/resources/hibernate.properties diff --git a/build.gradle b/build.gradle index abea8e632c..0774db1ace 100644 --- a/build.gradle +++ b/build.gradle @@ -22,6 +22,7 @@ buildscript { } dependencies { classpath 'org.hibernate.build.gradle:gradle-maven-publish-auth:2.0.1' + classpath 'org.hibernate.build.gradle:hibernate-matrix-testing:1.0.0-SNAPSHOT' } } diff --git a/buildSrc/Readme.md b/buildSrc/Readme.md deleted file mode 100644 index bd1047fd1b..0000000000 --- a/buildSrc/Readme.md +++ /dev/null @@ -1,184 +0,0 @@ -##Hibernate Matrix Testing - -### Goal - -The idea of matrix testing is to allow testing in a varied set of configurations. Specifically for Hibernate, this -correlates to running the same set of tests against against multiple databases. This goal is achieved through -2 Gradle plugins. - -Note that the second plugin (org.hibernate.build.gradle.testing.matrix.MatrixTestingPlugin) applies the first -one (org.hibernate.build.gradle.testing.database.DatabaseProfilePlugin) automatically, so generally scripts would -not even reference it. The reason for the split is historical and these 2 may get merged later... - - -### org.hibernate.build.gradle.testing.database.DatabaseProfilePlugin - -This plugin is responsible for determining which databases are available for testing in the given environment. It -does this by performing a directory search. Well actually it can perform up to 2 directory searches: - -* The standard profile directory is named _databases_ at the base directory of the root project -* A custom profile directory, which can be named by setting a system property named _hibernate-matrix-databases_ - -These directories are searched recursively. We leverage this in Hibernate to allow the standard _databases_ directory -to hold local profiles too. That is achieved by a _.gitignore_ which says to ignore any directory named -_local_ under the directory _databases_. So one option to provide custom profiles is to drop them in there. That -has the benefit of not having to specify _hibernate-matrix-databases_ -Within these directories, the plugin looks for sub-directories which either: - -* contain a file named _matrix.gradle_. _matrix.gradle_ is a limited DSL Gradle file which currently understands - just a specialized org.gradle.api.artifacts.Configuration reference named _jdbcDependency_. All that is a fancy - way to say that _matrix.gradle_ allows you to specify some dependencies this database profile needs (JDBC drivers, - etc). Any dependency artifacts named here get resolved using whatever resolvers (Maven, etc) are associated with - the build. For example - - jdbcDependency { - "mysql:mysql-connector-java:5.1.17" - } -* contain a directory named _jdbc_ which is assumed to hold jar file(s) needed for the profile. - -Such directories become the basis of a database profile made available to the build. The name of the profile -(which becomes important when we discuss the next plugin) is taken from the directory name. Database profiles can -also contain a _resources_ directory. - -An example layout using _matrix.gradle_ might be - - ├── mysql50 - │ ├── jdbc - │ │ └── mysql-connector-java-5.1.9.jar - │ └── resources - │ └── hibernate.properties - -Or - - ├── mysql50 - │ ├── matrix.gradle - │ └── resources - │ └── hibernate.properties - - -Either would result in a database profile named _mysql50_ - -Profiles can be ignored using the *hibernate-matrix-ignore* setting which accepts either - -* a comma-separated list of the database profile names to be skipped -* the magic value **all** which indicates to ignore all profiles - - -### org.hibernate.build.gradle.testing.matrix.MatrixTestingPlugin - -The MatrixTestingPlugin essentially generates a bunch of Gradle tasks dynamically and adds them to your build. It does -this based on all the database profiles found. Running `gradle tasks --all` will list all tasks available to the build -including these generated ones. - -For each database profile the plugin will generate a task named *matrix_{profile}* that executes the tests against -that particular database profile. It also generates a task named *matrix* that groups together all the -profile-specific tasks so that running `gradle matrix` will run all the profiles. - -*see section below discussing SourceSet separation* - - -### Database Allocator (JBoss internally, VPN required) - -For developers on the Red Hat VPN, one option is to use the databases in the JBoss QA lab for testing. Note that -this tends to result in **very** slow builds but the obvious trade off is not having to install and manage these -databases locally. - -The JBoss QA team developed a servlet to allow management of "database allocations" including requesting an -allocation be set up. The MatrixTestingPlugin is able to play with that feature allowing you to ask the build -to allocate the database for you. This feature is disabled by default, to enable it, you need this system property -named _hibernate-matrix-dballcoation_ which accepts either - -* a comma-separate list of profile names -* the magic value **all** which indicates to allocate for all **supported** databases (see - org.hibernate.build.qalab.DatabaseAllocator.SUPPORTED_DB_NAMES for details) - -For example, if you want to run matrix test on PostgreSQL 8.4, knowing that the database name for that is -_postgresql84_, you can use this command: - - gradle matrix_postgresql84 -Dhibernate-matrix-dballocation=postgresql84 - -which would - -1. talk to the database allocator service and make a database instance available -2. use the information returned from the allocator service to properly set up the connection information - Hibernate would need to connect to that instance. -3. run the tests against the postgresql84 profile - -For some databases we need adjust the connection url with some options after get it from the database allocator. In -these cases we can use the system property _hibernate-matrix-dballocation-url-postfix-${dbname}_. For example - `-Dhibernate-matrix-dballocation-url-postfix-sybase155="?SQLINITSTRING=set quoted_identifier on&DYNAMIC_PREPARE=true"` - -A useful parameter to the allocator service when allocating a database is the _requester_ which is basically just a -string meant to identify who is making the request. By default the Hibernate build uses _hibernate_. But you can -specify an alternate requester using the system property _hibernate-matrix-dballocation-requestee_ - - -### Testing SourceSets - -If you are not familiar with Gradle's notion of -[SourceSet](http://gradle.org/current/docs/javadoc/org/gradle/api/tasks/SourceSet.html), you should be :) - -The Hibernate build defines 2 different testing related SourceSets in a number of modules (currently hibernate-core, -hibernate-entitymanager and hibernate-envers): - -* _test_ - tests that **should not** be run against the profiles from the MatrixTestingPlugin -* _matrix_ - tests that **should** be run against the profiles from the MatrixTestingPlugin - -Tests in _test_ include unit tests as well as a few functional tests which use a database but where the particular -database should not at all affect the outcome. Tests in _matrix_ are functional tests where the outcome of the tests -are highly dependent on the database being used (how pessimistic locks are acquired, etc). - -As always, Wikipedia is a great source of information - -* [Functional Testing](http://en.wikipedia.org/wiki/Functional_testing) -* [Unit Testing](http://en.wikipedia.org/wiki/Unit_testing) - -hibernate-core directory layout (for discussion): - - hibernate-core - ├── hibernate-core.gradle - ├── src - ├── main - │ ├── antlr - │ ├── java - │ ├── javadoc - │ ├── resources - │ └── xjb - ├── matrix - │ └── java - └── test - ├── java - └── resources - -The directories of interest include - -* matrix/java - - all functional tests go into this directory - -* test/java - - all unit tests go into this directory - -* test/resources - - all resources for **functional tests and unit tests**. Yes, resource files in this directory are shared for both, so you don't need to copy one file to both place, for example, log4j.properties. - -To make _idea plugin_ (similar entries for _eclipse plugin_) works, we also have this defined in hibernate-core.gradle: - - sourceSets { - matrix { - java { - srcDir 'src/matrix/java' - } - resources { - srcDir 'src/matrix/resources' - } - } - } - - ideaModule { - sourceDirs += file( '$buildDir/generated-src/antlr/main' ) - testSourceDirs += file( 'src/matrix/java') - testSourceDirs += file( 'src/matrix/resources') - } diff --git a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/AbstractDatabaseProfileImpl.java b/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/AbstractDatabaseProfileImpl.java deleted file mode 100644 index fddaf9d7f7..0000000000 --- a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/AbstractDatabaseProfileImpl.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * 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.build.gradle.testing.database; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.gradle.api.Project; -import org.gradle.api.artifacts.Configuration; -import org.gradle.api.logging.Logging; -import org.slf4j.Logger; - -import org.hibernate.build.qalab.DatabaseAllocation; -import org.hibernate.build.qalab.DatabaseAllocator; - -/** - * Basic support for {@link DatabaseProfile} implementations - * - * @author Steve Ebersole - * @author Strong Liu - */ -public abstract class AbstractDatabaseProfileImpl implements DatabaseProfile { - private static final Logger log = Logging.getLogger( AbstractDatabaseProfileImpl.class ); - - private final String name; - private final File profileDirectory; - private final Project project; - private final Map hibernateProperties; - private final DatabaseAllocation databaseAllocation; - - @SuppressWarnings( {"unchecked"}) - protected AbstractDatabaseProfileImpl(File profileDirectory, Project project) { - this.profileDirectory = profileDirectory; - this.name = profileDirectory.getName(); - this.project = project; - - this.hibernateProperties = new HashMap(); - final File hibernatePropertiesFile = new File( - new File( profileDirectory, "resources" ), - "hibernate.properties" - ); - if ( hibernatePropertiesFile.exists() ) { - Properties props = new Properties(); - try { - FileInputStream stream = new FileInputStream( hibernatePropertiesFile ); - try { - props.load( stream ); - } - finally { - try { - stream.close(); - } - catch (IOException ignore) { - } - } - } - catch (IOException e) { - log.warn( "Unable to read Hibernate properties for database profile [" + name + "]", e ); - } - for ( String propName : props.stringPropertyNames() ) { - hibernateProperties.put( propName, props.getProperty( propName ) ); - } - } - - this.databaseAllocation = DatabaseAllocator.locate( project ).getAllocation( this ); - } - - @Override - public String getName() { - return name; - } - - @Override - public File getDirectory() { - return profileDirectory; - } - - @Override - public Map getHibernateProperties() { - return hibernateProperties; - } - - @Override - public DatabaseAllocation getDatabaseAllocation() { - return databaseAllocation; - } - - protected Configuration prepareConfiguration(String name) { - Configuration configuration = getOrCreateConfiguration( name ); - configuration.setDescription( "The JDBC dependency configuration for the [" + name + "] profile" ); - return configuration; - } - - protected Configuration getOrCreateConfiguration(String name) { - Configuration configuration = project.getConfigurations().findByName( name ); - if ( configuration == null ) { - configuration = project.getConfigurations().create( name ); - } - return configuration; - } -} diff --git a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DatabaseAllocationCleanUp.java b/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DatabaseAllocationCleanUp.java deleted file mode 100644 index 98b03e2cb0..0000000000 --- a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DatabaseAllocationCleanUp.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.build.gradle.testing.database; - -import java.util.HashSet; -import java.util.Set; - -import org.gradle.BuildAdapter; -import org.gradle.BuildResult; - -import org.hibernate.build.qalab.DatabaseAllocation; - -/** - * A Gradle {@link org.gradle.BuildListener} used to release all databases allocated when the build is finished. - * - * @author Steve Ebersole - */ -public class DatabaseAllocationCleanUp extends BuildAdapter { - private Set databaseAllocations = new HashSet(); - - public void addDatabaseAllocation(DatabaseAllocation databaseAllocation) { - databaseAllocations.add( databaseAllocation ); - } - - @Override - public void buildFinished(BuildResult result) { - super.buildFinished( result ); - for ( DatabaseAllocation databaseAllocation : databaseAllocations ) { - databaseAllocation.release(); - } - } -} diff --git a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DatabaseProfile.java b/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DatabaseProfile.java deleted file mode 100644 index 938ef5c6b7..0000000000 --- a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DatabaseProfile.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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.build.gradle.testing.database; - -import java.io.File; -import java.util.Map; - -import org.gradle.api.artifacts.Configuration; - -import org.hibernate.build.qalab.DatabaseAllocation; - -/** - * Contract for database "profiles". - * - * @author Steve Ebersole - * @author Strong Liu - */ -public interface DatabaseProfile { - public String getName(); - public File getDirectory(); - public Map getHibernateProperties(); - public Configuration getTestingRuntimeConfiguration(); - public DatabaseAllocation getDatabaseAllocation(); -} diff --git a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DatabaseProfilePlugin.java b/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DatabaseProfilePlugin.java deleted file mode 100644 index aff27982ff..0000000000 --- a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DatabaseProfilePlugin.java +++ /dev/null @@ -1,169 +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.build.gradle.testing.database; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.gradle.api.Plugin; -import org.gradle.api.Project; -import org.gradle.api.logging.Logger; -import org.gradle.api.logging.Logging; - -/** - * Plugin used to apply notion of database profiles, which are consumed by the matrix testing plugin. - * - * @author Steve Ebersole - * @author Strong Liu - */ -public class DatabaseProfilePlugin implements Plugin { - /** - * The directory containing standard database profiles. - */ - public static final String STANDARD_DATABASES_DIRECTORY = "databases"; - /** - * Names a system setting key that can be set to point to a directory containing additional, custom - * database profiles. - */ - public static final String CUSTOM_DATABASES_DIRECTORY_KEY = "hibernate-matrix-databases"; - public static final String HIBERNATE_MATRIX_IGNORE = "hibernate-matrix-ignore"; - - private static final String MATRIX_BUILD_FILE = "matrix.gradle"; - private static final String JDBC_DIR = "jdbc"; - - private static final Logger log = Logging.getLogger( DatabaseProfilePlugin.class ); - - private Project project; - private List profiles; - - public void apply(Project project) { - this.project = project; - - final LinkedHashMap profileMap = new LinkedHashMap(); - processStandardProfiles( profileMap ); - processCustomProfiles( profileMap ); - this.profiles = new ArrayList(); - - DatabaseAllocationCleanUp listener = new DatabaseAllocationCleanUp(); - project.getGradle().addBuildListener( listener ); - for ( DatabaseProfile profile : profileMap.values() ) { - this.profiles.add( profile ); - listener.addDatabaseAllocation( profile.getDatabaseAllocation() ); - } - } - - private void processStandardProfiles(Map profileMap) { - final File standardDatabasesDirectory = project.file( STANDARD_DATABASES_DIRECTORY ); - if ( standardDatabasesDirectory == null || ! standardDatabasesDirectory.exists() ) { - log.debug( "Standard databases directory [{}] did not exist", STANDARD_DATABASES_DIRECTORY ); - return; - } - - if ( ! standardDatabasesDirectory.isDirectory() ) { - log.warn( "Located standard databases directory [{}] was not a directory", STANDARD_DATABASES_DIRECTORY ); - return; - } - - processProfiles( standardDatabasesDirectory, profileMap ); - } - - private void processProfiles(File directory, Map profileMap) { - // the directory itself is a "database directory" if it contains either: - // 1) a file named 'matrix.gradle' - // 2) a directory named 'jdbc' - DatabaseProfile databaseProfile = null; - final File matrixDotGradleFile = new File( directory, MATRIX_BUILD_FILE ); - if ( matrixDotGradleFile.exists() && matrixDotGradleFile.isFile() ) { - log.debug( "Found matrix.gradle file : " + matrixDotGradleFile ); - databaseProfile = new MatrixDotGradleProfile( matrixDotGradleFile, project ); - } - final File jdbcDirectory = new File( directory, JDBC_DIR ); - if ( jdbcDirectory.exists() && jdbcDirectory.isDirectory() ) { - databaseProfile = new JdbcDirectoryProfile( jdbcDirectory, project ); - } - - if ( databaseProfile == null ) { - // we determined this directory is not a database directory, check its sub-directories - for ( File subDirectory : directory.listFiles() ) { - if ( subDirectory.isDirectory() ) { - processProfiles( subDirectory, profileMap ); - } - } - return; // EARLY EXIT!!! - } - - final String profileName = databaseProfile.getName(); - if ( ignored().contains( profileName ) ) { - log.debug( "Skipping ignored database profile [{}]", profileName ); - return; - } - - DatabaseProfile previousEntry = profileMap.put( profileName, databaseProfile ); - if ( previousEntry != null ) { - log.lifecycle( - "Found duplicate profile definitions [name={}], [{}] taking precedence over [{}]", - profileName, - databaseProfile.getDirectory().getAbsolutePath(), - previousEntry.getDirectory().getAbsolutePath() - ); - } - } - - private Set ignored; - - private Set ignored() { - if ( ignored == null ) { - final String values = System.getProperty( HIBERNATE_MATRIX_IGNORE ); - if ( values == null || values.length() == 0 ) { - ignored = Collections.emptySet(); - } - else { - ignored = new HashSet(); - Collections.addAll( ignored, values.split( "," ) ); - } - } - return ignored; - } - - private void processCustomProfiles(Map profileMap) { - final String customDatabaseDirectoryPath = System.getProperty( CUSTOM_DATABASES_DIRECTORY_KEY ); - if ( customDatabaseDirectoryPath != null && customDatabaseDirectoryPath.length() > 0 ) { - final File customDatabaseDirectory = new File( customDatabaseDirectoryPath ); - if ( customDatabaseDirectory.exists() && customDatabaseDirectory.isDirectory() ) { - processProfiles( customDatabaseDirectory, profileMap ); - } - } - } - - public Iterable getDatabaseProfiles() { - return profiles; - } -} diff --git a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DuplicateDatabaseProfileException.java b/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DuplicateDatabaseProfileException.java deleted file mode 100644 index b0f1648e2f..0000000000 --- a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/DuplicateDatabaseProfileException.java +++ /dev/null @@ -1,39 +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.build.gradle.testing.database; - -import org.hibernate.build.gradle.util.BuildException; - -/** - * Indicates that we found multiple database profiles having the same name. - * - * @author Strong Liu - * @author Steve Ebersole - */ -public class DuplicateDatabaseProfileException extends BuildException { - public DuplicateDatabaseProfileException(String message) { - super( message ); - } -} diff --git a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/JdbcDirectoryProfile.groovy b/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/JdbcDirectoryProfile.groovy deleted file mode 100644 index 69b984dfaa..0000000000 --- a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/JdbcDirectoryProfile.groovy +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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.build.gradle.testing.database; - - -import org.gradle.api.Project; -import org.gradle.api.artifacts.Configuration; -/** - * Database profile as defined by a directory named {@code jdbc} containing JDBC drivers. - * - * @author Steve Ebersole - * @author Strong Liu - */ -public class JdbcDirectoryProfile extends AbstractDatabaseProfileImpl { - private final Configuration jdbcDependencies; - - public JdbcDirectoryProfile(File jdbcDirectory, Project project) { - super( jdbcDirectory.getParentFile(), project ); - jdbcDependencies = prepareConfiguration( getName() ); - project.dependencies.add(getName(), project.files(jdbcDirectory.listFiles())) - } - - @Override - public Configuration getTestingRuntimeConfiguration() { - return jdbcDependencies; - } -} diff --git a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/MatrixDotGradleProfile.java b/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/MatrixDotGradleProfile.java deleted file mode 100644 index 4f08a12eef..0000000000 --- a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/database/MatrixDotGradleProfile.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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.build.gradle.testing.database; - -import java.io.File; -import java.util.Collections; - -import groovy.lang.Closure; -import org.gradle.api.Project; -import org.gradle.api.artifacts.Configuration; - -/** - * Database profile as defined by a {@code matrix.gradle} file - * - * @author Steve Ebersole - * @author Strong Liu - */ -public class MatrixDotGradleProfile extends AbstractDatabaseProfileImpl { - private static final String MATRIX_NODE_CONVENTION_KEY = "matrixNode"; - - private final Configuration jdbcDependencies; - - protected MatrixDotGradleProfile(File matrixDotGradleFile, Project project) { - super( matrixDotGradleFile.getParentFile(), project ); - jdbcDependencies = prepareConfiguration( getName() ); - final ConventionImpl convention = new ConventionImpl( jdbcDependencies, project ); - project.getConvention().getPlugins().put( MATRIX_NODE_CONVENTION_KEY, convention ); - try { - project.apply( Collections.singletonMap( "from", matrixDotGradleFile ) ); - } - finally { - project.getConvention().getPlugins().remove( MATRIX_NODE_CONVENTION_KEY ); - } - } - - @Override - public Configuration getTestingRuntimeConfiguration() { - return jdbcDependencies; - } - - private class ConventionImpl { - private final Configuration jdbcDependencies; - private final Project project; - - private ConventionImpl(Configuration jdbcDependencies, Project project) { - this.jdbcDependencies = jdbcDependencies; - this.project = project; - } - - @SuppressWarnings( {"UnusedDeclaration"}) - public void jdbcDependency(Object dependencyNotation, Closure closure) { - project.getDependencies().add( jdbcDependencies.getName(), dependencyNotation, closure ); - } - - @SuppressWarnings( {"UnusedDeclaration"}) - public void jdbcDependency(Object dependencyNotation) { - project.getDependencies().add( jdbcDependencies.getName(), dependencyNotation ); - } - } - -} diff --git a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/matrix/MatrixNode.java b/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/matrix/MatrixNode.java deleted file mode 100644 index 4f1e1380fe..0000000000 --- a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/matrix/MatrixNode.java +++ /dev/null @@ -1,79 +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.build.gradle.testing.matrix; - -import java.io.File; - -import org.gradle.api.Project; - -import org.hibernate.build.gradle.testing.database.DatabaseProfile; -import org.hibernate.build.gradle.util.Jdk; -import org.hibernate.build.qalab.*; -import org.hibernate.build.qalab.DatabaseAllocation; - -/** - * A testing matrix node combines a database profile and a jdk (eventually) along with managing "db allocation" - * information. - * - * @author Steve Ebersole - * @author Strong Liu - */ -public class MatrixNode { - private final DatabaseProfile databaseProfile; - private final Jdk jdk; - private final File baseOutputDirectory; - - private final DatabaseAllocation databaseAllocation; - - @SuppressWarnings( {"ResultOfMethodCallIgnored"}) - public MatrixNode(Project project, DatabaseProfile databaseProfile, Jdk jdk) { - this.databaseProfile = databaseProfile; - this.jdk = jdk; - - baseOutputDirectory = new File( new File( project.getBuildDir(), "matrix" ), databaseProfile.getName() ); - baseOutputDirectory.mkdirs(); - - this.databaseAllocation = DatabaseAllocator.locate( project ).getAllocation( databaseProfile ); - } - - public String getName() { - return databaseProfile.getName(); - } - - public DatabaseProfile getDatabaseProfile() { - return databaseProfile; - } - - public Jdk getJdk() { - return jdk; - } - - public File getBaseOutputDirectory() { - return baseOutputDirectory; - } - - public DatabaseAllocation getDatabaseAllocation() { - return databaseAllocation; - } -} diff --git a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/matrix/MatrixTestingPlugin.groovy b/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/matrix/MatrixTestingPlugin.groovy deleted file mode 100644 index 31686a0dc2..0000000000 --- a/buildSrc/src/main/groovy/org/hibernate/build/gradle/testing/matrix/MatrixTestingPlugin.groovy +++ /dev/null @@ -1,159 +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.build.gradle.testing.matrix; - -import org.gradle.api.Plugin -import org.gradle.api.Project -import org.gradle.api.Task -import org.gradle.api.artifacts.Configuration -import org.gradle.api.logging.Logger -import org.gradle.api.logging.Logging -import org.gradle.api.plugins.JavaPluginConvention -import org.gradle.api.tasks.SourceSet -import org.gradle.api.tasks.testing.Test -import org.hibernate.build.gradle.testing.database.DatabaseProfile -import org.hibernate.build.gradle.testing.database.DatabaseProfilePlugin -import org.hibernate.build.gradle.util.Jdk -import static org.gradle.api.plugins.JavaPlugin.COMPILE_CONFIGURATION_NAME -import static org.gradle.api.plugins.JavaPlugin.RUNTIME_CONFIGURATION_NAME -import static org.gradle.api.plugins.JavaPlugin.TEST_COMPILE_CONFIGURATION_NAME -import static org.gradle.api.plugins.JavaPlugin.TEST_RUNTIME_CONFIGURATION_NAME - -/** - * TODO : 1) add a base configuration of common attribute across all matrix node tasks (convention) - * TODO : 2) somehow allow applying just a single database to a project (non matrix testing). - * - * @author Steve Ebersole - * @author Strong Liu - */ -public class MatrixTestingPlugin implements Plugin { - private static final Logger log = Logging.getLogger(MatrixTestingPlugin.class); - - public static final String MATRIX_COMPILE_CONFIG_NAME = "matrixCompile"; - public static final String MATRIX_RUNTIME_CONFIG_NAME = "matrixRuntime"; - public static final String MATRIX_TASK_NAME = "matrix"; - - private Project project; - private SourceSet testSourceSet; - - private Configuration matrixCompileConfig; - private Configuration matrixRuntimeConfig; - private Task matrixTask; - - // currently, only the build jdk is supported - private Jdk theJdk = new Jdk(); - - public void apply(Project project) { - this.project = project; - - project.rootProject.plugins.apply( DatabaseProfilePlugin ); - List matrixNodes = locateMatrixNodes(); - if ( matrixNodes == null || matrixNodes.isEmpty() ) { - // no db profiles defined - return; - } - - matrixCompileConfig = prepareCompileConfiguration(); - matrixRuntimeConfig = prepareRuntimeConfiguration(); - testSourceSet = project.convention.getPlugin( JavaPluginConvention ).sourceSets - .getByName( SourceSet.TEST_SOURCE_SET_NAME ); - - matrixTask = prepareGroupingTask(); - for ( MatrixNode matrixNode: matrixNodes ) { - Task matrixNodeTask = prepareNodeTask( matrixNode ); - matrixTask.dependsOn( matrixNodeTask ); - } - } - - private List locateMatrixNodes() { - List matrixNodes = new ArrayList(); - Iterable profiles = project.rootProject.plugins[DatabaseProfilePlugin].databaseProfiles; - if ( profiles != null ) { - for ( DatabaseProfile profile : profiles ) { - matrixNodes.add( new MatrixNode( project, profile, theJdk ) ); - } - } - return matrixNodes; - } - - /** - * Prepare compile configuration for matrix source set. - */ - private Configuration prepareCompileConfiguration() { - return project.configurations.create( MATRIX_COMPILE_CONFIG_NAME ) - .setDescription( "Dependencies used to compile the matrix tests" ) - .extendsFrom( project.configurations.getByName( COMPILE_CONFIGURATION_NAME ) ) - .extendsFrom( project.configurations.getByName( TEST_COMPILE_CONFIGURATION_NAME ) ); - } - - /** - * Prepare runtime configuration for matrix source set. - */ - private Configuration prepareRuntimeConfiguration() { - return project.configurations.create( MATRIX_RUNTIME_CONFIG_NAME ) - .setDescription( "Dependencies (baseline) used to run the matrix tests" ) - .extendsFrom( matrixCompileConfig ) - .extendsFrom( project.configurations.getByName( RUNTIME_CONFIGURATION_NAME ) ) - .extendsFrom( project.configurations.getByName( TEST_RUNTIME_CONFIGURATION_NAME ) ); - } - - private Task prepareGroupingTask() { - Task matrixTask = project.tasks.create( MATRIX_TASK_NAME ); - matrixTask.group = "Verification" - matrixTask.description = "Runs the unit tests on Database Matrix" - return matrixTask; - } - - private void generateNodeTasks(List matrixNodes) { - // For now we just hard code this to locate the databases processed by - // org.hibernate.build.gradle.testing.database.DatabaseProfilePlugin. But long term would be much better to - // abstract this idea via the MatrixNode/MatrixNodeProvider interfaces; this would allow the jvm variance - // needed for jdbc3/jdbc4 testing for example. Not to mention its much more generally applicable - // - // Also the notion that the plugin as a MatrixNodeProducer might not be appropriate. probably a split there - // is in order too (config producer and jvm producer and somehow they get wired into a matrix). - // - // but again this is just a start. - } - - private Task prepareNodeTask(MatrixNode node) { - String taskName = MATRIX_TASK_NAME + '_' + node.name - log.debug( "Adding Matrix Testing task $taskName" ); - final Test nodeTask = project.tasks.create( taskName, Test ); - nodeTask.description = "Runs the matrix against ${node.name}" - nodeTask.classpath = node.databaseProfile.testingRuntimeConfiguration + testSourceSet.runtimeClasspath - nodeTask.testClassesDir = testSourceSet.output.classesDir - nodeTask.ignoreFailures = true - nodeTask.workingDir = node.baseOutputDirectory - nodeTask.testReportDir = new File(node.baseOutputDirectory, "reports") - nodeTask.testResultsDir = new File(node.baseOutputDirectory, "results") - - nodeTask.dependsOn( project.tasks.getByName( testSourceSet.classesTaskName ) ); - nodeTask.systemProperties = node.databaseAllocation.properties - nodeTask.systemProperties['hibernate.test.validatefailureexpected'] = true - nodeTask.jvmArgs = ['-Xms1024M', '-Xmx1024M']//, '-XX:MaxPermSize=512M', '-Xss4096k', '-Xverify:none', '-XX:+UseFastAccessorMethods', '-XX:+DisableExplicitGC'] - nodeTask.maxHeapSize = "1024M" - return nodeTask; - } -} diff --git a/buildSrc/src/main/groovy/org/hibernate/build/qalab/DatabaseAllocation.java b/buildSrc/src/main/groovy/org/hibernate/build/qalab/DatabaseAllocation.java deleted file mode 100644 index 91a230a94d..0000000000 --- a/buildSrc/src/main/groovy/org/hibernate/build/qalab/DatabaseAllocation.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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.build.qalab; - -import java.util.Map; - -/** - * Represents a database instances allocated in the JBoss/Red Hat Qe Lab via {@link DatabaseAllocator} - * - * @author mvecera - * @author Strong Liu - * @author Steve Ebersole - */ -public interface DatabaseAllocation { - public Map getProperties(); - - public void release(); -} diff --git a/buildSrc/src/main/groovy/org/hibernate/build/qalab/DatabaseAllocator.groovy b/buildSrc/src/main/groovy/org/hibernate/build/qalab/DatabaseAllocator.groovy deleted file mode 100644 index 8edb9dc7ff..0000000000 --- a/buildSrc/src/main/groovy/org/hibernate/build/qalab/DatabaseAllocator.groovy +++ /dev/null @@ -1,101 +0,0 @@ -/* - * 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.build.qalab - -import org.gradle.api.Project -import org.gradle.api.logging.Logger -import org.gradle.api.logging.Logging -import org.hibernate.build.gradle.testing.database.DatabaseProfile - -/** - * Helper for dealing with the "DB Allocator" service set up in the JBoss/Red Hat QE lab. - * - * Use the hibernate-matrix-dballocation setting to control db allocation. By default, - * no allocations are performed. hibernate-matrix-dballocation could be either:

    - *
  • all - allocate all non-ignored databases
  • - *
  • profile1{,profile2,...} - allocate only the named profiles, provided the name is also one of the supported names
  • - *
- * - * @author mvecera - * @author Strong Liu - * @author Steve Ebersole - */ -class DatabaseAllocator { - private static final Logger log = Logging.getLogger( DatabaseAllocator.class ); - - public static final String ALLOCATION_ENABLED = "hibernate-matrix-dballocation"; - public static final String REQUESTEE = "hibernate-matrix-dballocation-requestee"; - - public static final String DB_ALLOCATOR_KEY = "dbAllocator"; - - public static def SUPPORTED_DB_NAMES = [ - "oracle9i", "oracle10g", "oracle11gR1", "oracle11gR2", "oracle11gR2RAC", "oracle11gR1RAC", - "postgresql82", "postgresql83", "postgresql84", "postgresql91", "postgresql92", - "postgresplus92", - "mysql50", "mysql51","mysql55", - "db2-91", "db2-97", "db2-10", - "mssql2005", "mssql2008R1", "mssql2008R2", "mssql2012", - "sybase155", "sybase157" - ]; - - private Map databaseAllocationMap = new HashMap(); - private final Project rootProject; - - DatabaseAllocator(Project rootProject) { - this.rootProject = rootProject - } - - public DatabaseAllocation getAllocation(DatabaseProfile profile) { - DatabaseAllocation databaseAllocation = databaseAllocationMap.get( profile.name ); - if ( databaseAllocation == null ) { - databaseAllocation = createAllocation( profile ); - databaseAllocationMap.put( profile.name, databaseAllocation ); - } - return databaseAllocation; - } - - private DatabaseAllocation createAllocation(DatabaseProfile profile) { - if ( isAllocationEnabled( profile.name ) ) { - log.lifecycle( "using Allocator to get database [${profile.name}] connection info" ); - final File outputDirectory = new File( new File( rootProject.getBuildDir(), "matrix" ), profile.getName() ) - return new EnabledDatabaseAllocation( rootProject.getAnt(), profile, outputDirectory ); - } - return new DisabledDatabaseAllocation( profile ); - } - - private boolean isAllocationEnabled(String name) { - if ( !SUPPORTED_DB_NAMES.contains(name) ) { - return false - }; - String value = System.properties[ALLOCATION_ENABLED] - return value != null && (value.contains(name) || value.equals("all")); - } - - public static DatabaseAllocator locate(Project project) { - if ( ! project.rootProject.hasProperty( DB_ALLOCATOR_KEY ) ) { - project.rootProject.ext.setProperty( DB_ALLOCATOR_KEY, new DatabaseAllocator( project.rootProject ) ); - } - return (DatabaseAllocator) project.rootProject.properties[ DB_ALLOCATOR_KEY ]; - } -} diff --git a/buildSrc/src/main/groovy/org/hibernate/build/qalab/DisabledDatabaseAllocation.groovy b/buildSrc/src/main/groovy/org/hibernate/build/qalab/DisabledDatabaseAllocation.groovy deleted file mode 100644 index 444c780156..0000000000 --- a/buildSrc/src/main/groovy/org/hibernate/build/qalab/DisabledDatabaseAllocation.groovy +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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.build.qalab - -import org.hibernate.build.gradle.testing.database.DatabaseProfile - -/** - * @author Steve Ebersole - */ -class DisabledDatabaseAllocation implements DatabaseAllocation { - private final DatabaseProfile databaseProfile; - - DisabledDatabaseAllocation(DatabaseProfile databaseProfile) { - this.databaseProfile = databaseProfile; - } - - @Override - Map getProperties() { - return databaseProfile.hibernateProperties; - } - - @Override - void release() { - // nothing to do - } -} diff --git a/buildSrc/src/main/groovy/org/hibernate/build/qalab/EnabledDatabaseAllocation.groovy b/buildSrc/src/main/groovy/org/hibernate/build/qalab/EnabledDatabaseAllocation.groovy deleted file mode 100644 index 3ae40d3a9e..0000000000 --- a/buildSrc/src/main/groovy/org/hibernate/build/qalab/EnabledDatabaseAllocation.groovy +++ /dev/null @@ -1,150 +0,0 @@ -/* - * 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.build.qalab - -import org.gradle.api.Project -import org.hibernate.build.gradle.testing.database.DatabaseProfile -import org.hibernate.build.gradle.util.BuildException -import org.gradle.api.logging.Logging -import org.gradle.api.logging.Logger - -/** - * @author Steve Ebersole - */ -class EnabledDatabaseAllocation implements DatabaseAllocation { - private static final Logger log = Logging.getLogger( DatabaseAllocator.class ); - - private static final String DB_ALLOCATOR_URL = "http://dballocator.mw.lab.eng.bos.redhat.com:8080/Allocator/AllocatorServlet"; - private static final String ALLOCATOR_OUTPUT_FILE_NAME = "allocated-db.properties"; - private static final String DB_ALLOCATION_URL_POSTFIX = "hibernate-matrix-dballocation-url-postfix"; - - private static final String DRIVER_PROP = "hibernate.connection.driver_class"; - private static final String URL_PROP = "hibernate.connection.url"; - private static final String USERNAME_PROP = "hibernate.connection.username"; - private static final String PASSWORD_PROP = "hibernate.connection.password"; - - private static final int RETRIES = 30 - private static final int EXPIRY = 300; - - private final DatabaseProfile databaseProfile - private final AntBuilder ant; - - private final File allocatorOutputFile; - private final String requester; - private final String uuid; - - private final File tmpFile; - - private final Map properties; - - EnabledDatabaseAllocation(AntBuilder ant, DatabaseProfile databaseProfile, File outputDirectory) { - this.ant = ant; - this.databaseProfile = databaseProfile; - - outputDirectory.mkdirs() - - this.allocatorOutputFile = new File( outputDirectory, ALLOCATOR_OUTPUT_FILE_NAME ); - this.tmpFile = new File( outputDirectory, "tmpfile" ); - - if ( System.properties.containsKey("hibernate-matrix-dballocation-requestee") ) { - requester = System.properties["hibernate-matrix-dballocation-requestee"] - } - else { - requester = "hibernate" - } - - if ( allocatorOutputFile.exists() ) { - allocatorOutputFile.delete() - } - - int attempts = 0; - while ( !(allocatorOutputFile.exists() && allocatorOutputFile.length() > 0) ) { - if ( attempts >= RETRIES ) { - throw new BuildException( 'Database unavailable' ); - } - if ( attempts > 0 ) { - log.lifecycle( "Trouble accessing Allocator servlet; waiting before trying again" ); - Thread.sleep( 60000 ); - } - def allocatorUrl = DB_ALLOCATOR_URL + - "?operation=alloc&label=${databaseProfile.name}&requestee=${requester}&expiry=${EXPIRY}" - ant.get( - src: allocatorUrl, - dest: allocatorOutputFile.absolutePath, - ignoreerrors: 'true' - ); - attempts++ - } - - def allocatorProps = new Properties(); - allocatorProps.load( new FileInputStream( allocatorOutputFile ) ); - - this.uuid = allocatorProps['uuid'] - log.lifecycle( "Finished allocating for DB instance [${databaseProfile.name}], uuid is [${uuid}]" ); - - properties = new HashMap(); - properties.putAll( databaseProfile.hibernateProperties ); - properties[DRIVER_PROP] = allocatorProps["db.jdbc_class"] - properties[URL_PROP] = allocatorProps["db.jdbc_url"] + getURLPostfix(databaseProfile.name) - properties[USERNAME_PROP] = allocatorProps["db.username"] - properties[PASSWORD_PROP] = allocatorProps["db.password"] - properties["uuid"] = allocatorProps["uuid"]; - - clean(); - } - - private String getURLPostfix(String dbName) { - for ( String key: System.properties.keySet() ) { - if ( key.startsWith(DB_ALLOCATION_URL_POSTFIX) ) { - String db = key.substring(DB_ALLOCATION_URL_POSTFIX.length() + 1, key.length()) - if ( db.equalsIgnoreCase(dbName) ) { - String postfix = System.properties[key]; - log.debug("found URL postfix[%s] for DB[%s]", postfix, db ); - return postfix; - } - } - } - return "" - } - - void clean() { - log.lifecycle( "Cleaning DB [${databaseProfile.name}]..." ); - final String allocatorUrl = DB_ALLOCATOR_URL + "?operation=erase&uuid=${uuid}"; - ant.get( src: allocatorUrl, dest: tmpFile.absolutePath ); - } - - @Override - Map getProperties() { - return properties; - } - - @Override - void release() { - log.lifecycle( "De-allocating DB [${databaseProfile.name}]..." ); - final String allocatorUrl = DB_ALLOCATOR_URL + "?operation=dealloc&uuid=${uuid}"; - ant.get( src: allocatorUrl, dest: tmpFile.absolutePath ); - } - - -} diff --git a/databases/.gitignore b/databases/.gitignore deleted file mode 100644 index 9fdb372de8..0000000000 --- a/databases/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -#Ignore any sub directory named 'local'. these are used to define custom database profiles local -# to the developer's machine -/local \ No newline at end of file diff --git a/databases/derby/matrix.gradle b/databases/derby/matrix.gradle deleted file mode 100644 index 39b1873402..0000000000 --- a/databases/derby/matrix.gradle +++ /dev/null @@ -1,25 +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 - */ - -jdbcDependency "org.apache.derby:derby:10.8.2.2" \ No newline at end of file diff --git a/databases/derby/resources/hibernate.properties b/databases/derby/resources/hibernate.properties deleted file mode 100644 index 599da05bdc..0000000000 --- a/databases/derby/resources/hibernate.properties +++ /dev/null @@ -1,40 +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 -# - -hibernate.dialect org.hibernate.dialect.DerbyTenSevenDialect -hibernate.connection.driver_class org.apache.derby.jdbc.EmbeddedDriver -hibernate.connection.url jdbc:derby:testdb;create=true -hibernate.connection.username sa - -hibernate.connection.pool_size 5 - -hibernate.show_sql true -hibernate.format_sql true - -hibernate.max_fetch_depth 5 - -hibernate.cache.region_prefix hibernate.test -hibernate.cache.region.factory_class org.hibernate.testing.cache.CachingRegionFactory - - diff --git a/databases/mysql50/matrix.gradle b/databases/mysql50/matrix.gradle deleted file mode 100644 index 9439d47bdb..0000000000 --- a/databases/mysql50/matrix.gradle +++ /dev/null @@ -1,25 +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 - */ - -jdbcDependency "mysql:mysql-connector-java:5.1.17" \ No newline at end of file diff --git a/databases/mysql50/resources/hibernate.properties b/databases/mysql50/resources/hibernate.properties deleted file mode 100644 index 9b8811323c..0000000000 --- a/databases/mysql50/resources/hibernate.properties +++ /dev/null @@ -1,42 +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 -# - -hibernate.dialect org.hibernate.dialect.MySQL5InnoDBDialect -hibernate.connection.driver_class com.mysql.jdbc.Driver -hibernate.connection.url jdbc:mysql://vmg08.mw.lab.eng.bos.redhat.com:3306/dballo01 -hibernate.connection.username dballo01 -hibernate.connection.password dballo01 - - -hibernate.connection.pool_size 5 - -hibernate.show_sql true -hibernate.format_sql true - -hibernate.max_fetch_depth 5 - -hibernate.cache.region_prefix hibernate.test -hibernate.cache.region.factory_class org.hibernate.testing.cache.CachingRegionFactory - - diff --git a/databases/mysql51/matrix.gradle b/databases/mysql51/matrix.gradle deleted file mode 100644 index 9439d47bdb..0000000000 --- a/databases/mysql51/matrix.gradle +++ /dev/null @@ -1,25 +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 - */ - -jdbcDependency "mysql:mysql-connector-java:5.1.17" \ No newline at end of file diff --git a/databases/mysql51/resources/hibernate.properties b/databases/mysql51/resources/hibernate.properties deleted file mode 100644 index cc3b732cbc..0000000000 --- a/databases/mysql51/resources/hibernate.properties +++ /dev/null @@ -1,46 +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 -# - -hibernate.dialect org.hibernate.dialect.MySQL5InnoDBDialect -hibernate.connection.driver_class com.mysql.jdbc.Driver -#hibernate.connection.url jdbc:mysql://vmg02.mw.lab.eng.bos.redhat.com:3306/dballo01 -#hibernate.connection.username dballo01 -#hibernate.connection.password dballo01 - -hibernate.connection.url jdbc:mysql://127.0.0.1:3306/hibernate -hibernate.connection.username hibernate -hibernate.connection.password hibernate - - -hibernate.connection.pool_size 5 - -hibernate.show_sql true -hibernate.format_sql true - -hibernate.max_fetch_depth 5 - -hibernate.cache.region_prefix hibernate.test -hibernate.cache.region.factory_class org.hibernate.testing.cache.CachingRegionFactory - - diff --git a/databases/postgresql82/matrix.gradle b/databases/postgresql82/matrix.gradle deleted file mode 100644 index 78c7bc8678..0000000000 --- a/databases/postgresql82/matrix.gradle +++ /dev/null @@ -1,24 +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 - */ -jdbcDependency "postgresql:postgresql:8.4-701.jdbc4" \ No newline at end of file diff --git a/databases/postgresql82/resources/hibernate.properties b/databases/postgresql82/resources/hibernate.properties deleted file mode 100644 index 76bf7f0e13..0000000000 --- a/databases/postgresql82/resources/hibernate.properties +++ /dev/null @@ -1,42 +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 -# - -hibernate.dialect org.hibernate.dialect.PostgreSQLDialect -hibernate.connection.driver_class org.postgresql.Driver -hibernate.connection.url jdbc:postgresql://postgresql01.mw.lab.eng.bos.redhat.com:5432/dballo03 -hibernate.connection.username dballo03 -hibernate.connection.password dballo03 - - -hibernate.connection.pool_size 5 - -hibernate.show_sql true -hibernate.format_sql true - -hibernate.max_fetch_depth 5 - -hibernate.cache.region_prefix hibernate.test -hibernate.cache.region.factory_class org.hibernate.testing.cache.CachingRegionFactory - - diff --git a/databases/postgresql83/matrix.gradle b/databases/postgresql83/matrix.gradle deleted file mode 100644 index 78c7bc8678..0000000000 --- a/databases/postgresql83/matrix.gradle +++ /dev/null @@ -1,24 +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 - */ -jdbcDependency "postgresql:postgresql:8.4-701.jdbc4" \ No newline at end of file diff --git a/databases/postgresql83/resources/hibernate.properties b/databases/postgresql83/resources/hibernate.properties deleted file mode 100644 index 45f8ea203c..0000000000 --- a/databases/postgresql83/resources/hibernate.properties +++ /dev/null @@ -1,43 +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 -# - -hibernate.dialect org.hibernate.dialect.PostgreSQLDialect -hibernate.connection.driver_class org.postgresql.Driver - -hibernate.connection.url jdbc:postgresql://postgresql03.mw.lab.eng.bos.redhat.com:5432/dballo03 -hibernate.connection.username dballo03 -hibernate.connection.password dballo03 - - -hibernate.connection.pool_size 5 - -hibernate.show_sql true -hibernate.format_sql true - -hibernate.max_fetch_depth 5 - -hibernate.cache.region_prefix hibernate.test -hibernate.cache.region.factory_class org.hibernate.testing.cache.CachingRegionFactory - - diff --git a/databases/postgresql84/matrix.gradle b/databases/postgresql84/matrix.gradle deleted file mode 100644 index 5d30139099..0000000000 --- a/databases/postgresql84/matrix.gradle +++ /dev/null @@ -1,24 +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 - */ -jdbcDependency "postgresql:postgresql:9.1-901.jdbc4" \ No newline at end of file diff --git a/databases/postgresql84/resources/hibernate.properties b/databases/postgresql84/resources/hibernate.properties deleted file mode 100644 index 977b43b33a..0000000000 --- a/databases/postgresql84/resources/hibernate.properties +++ /dev/null @@ -1,42 +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 -# - -hibernate.dialect org.hibernate.dialect.PostgreSQL82Dialect -hibernate.connection.driver_class org.postgresql.Driver -hibernate.connection.url jdbc:postgresql://127.0.0.1/hibernate -hibernate.connection.username hibernate -hibernate.connection.password hibernate - - -hibernate.connection.pool_size 5 - -hibernate.show_sql true -hibernate.format_sql true - -hibernate.max_fetch_depth 5 - -hibernate.cache.region_prefix hibernate.test -hibernate.cache.region.factory_class org.hibernate.testing.cache.CachingRegionFactory - - diff --git a/hibernate-core/hibernate-core.gradle b/hibernate-core/hibernate-core.gradle index b49ccff347..72f3c5c9b1 100644 --- a/hibernate-core/hibernate-core.gradle +++ b/hibernate-core/hibernate-core.gradle @@ -1,6 +1,8 @@ apply plugin: 'antlr' +apply plugin: 'hibernate-matrix-testing' + apply plugin: org.hibernate.build.gradle.inject.InjectionPlugin -apply plugin: org.hibernate.build.gradle.testing.matrix.MatrixTestingPlugin + dependencies { compile( libraries.jta ) diff --git a/hibernate-entitymanager/hibernate-entitymanager.gradle b/hibernate-entitymanager/hibernate-entitymanager.gradle index e5a16948b3..0f15d2ffd5 100644 --- a/hibernate-entitymanager/hibernate-entitymanager.gradle +++ b/hibernate-entitymanager/hibernate-entitymanager.gradle @@ -1,6 +1,6 @@ import org.apache.tools.ant.filters.ReplaceTokens -apply plugin: org.hibernate.build.gradle.testing.matrix.MatrixTestingPlugin +apply plugin: 'hibernate-matrix-testing' dependencies { compile( project(':hibernate-core') ) diff --git a/hibernate-envers/hibernate-envers.gradle b/hibernate-envers/hibernate-envers.gradle index 2ae83fb18f..5a0c8ee0be 100644 --- a/hibernate-envers/hibernate-envers.gradle +++ b/hibernate-envers/hibernate-envers.gradle @@ -1,4 +1,4 @@ -apply plugin: org.hibernate.build.gradle.testing.matrix.MatrixTestingPlugin +apply plugin: 'hibernate-matrix-testing' dependencies { compile( project( ':hibernate-core' ) )