This is an automated email from the ASF dual-hosted git repository. dschneider pushed a commit to branch develop in repository https://gitbox.apache.org/repos/asf/geode.git
The following commit(s) were added to refs/heads/develop by this push: new 3b6a9aa GEODE-4559: pass the Cache to a Declarable (#1422) 3b6a9aa is described below commit 3b6a9aaf9d1ae6608a1fd9ffee01b399a6a11452 Author: Darrel Schneider <dschnei...@pivotal.io> AuthorDate: Fri Feb 23 11:32:44 2018 -0800 GEODE-4559: pass the Cache to a Declarable (#1422) * Declarable now has a default method named "initialize(Cache, Properties)". This allows a Declarable to know the cache that created it. Deprecated Declarable.init(Properties). Note that for backwards compatibility, the product calls both these methods. Also the two Declarables that the product implements, AutoBalancer and ReflectionBasedAutoSerializer, implement both these methods but after the first calls subsequent calls of init or initialize will be noops. * initialize on ReflectionBasedAutoSerializer now call setRegionService with the cache. init and initialize can now be called multiple times and each time the properties will be set again. This is for backwards compatibility. * The AutoBalancer no longer looks up the static cache. but instead of given one by the product calling setCache during initialization. --- .../connectors/jdbc/JdbcWriterIntegrationTest.java | 1 - .../java/org/apache/geode/cache/Declarable.java | 19 +++++ .../internal/InternalDistributedSystem.java | 6 -- .../org/apache/geode/internal/DeployedJar.java | 12 +-- .../internal/cache/xmlcache/CacheCreation.java | 68 +++++++++++++-- .../internal/cache/xmlcache/CacheXmlGenerator.java | 12 ++- .../internal/cache/xmlcache/CacheXmlParser.java | 15 ++-- .../cache/xmlcache/ClientCacheCreation.java | 9 +- .../cache/xmlcache/FunctionServiceCreation.java | 23 +++-- .../management/internal/cli/domain/ClassName.java | 7 +- .../functions/CreateAsyncEventQueueFunction.java | 3 +- .../cli/functions/RegionAlterFunction.java | 10 +-- .../cli/functions/RegionCreateFunction.java | 13 +-- .../geode/pdx/ReflectionBasedAutoSerializer.java | 25 +++++- .../apache/geode/cache30/CacheXml66DUnitTest.java | 6 +- .../apache/geode/cache30/ReconnectDUnitTest.java | 18 ++-- .../cache/xmlcache/CacheCreationJUnitTest.java | 98 ++++++++++++++++++++++ .../internal/cli/domain/ClassNameTest.java | 6 +- .../geode/pdx/AutoSerializableJUnitTest.java | 20 ++--- .../java/parReg/query/unittest/NewPortfolio.java | 2 +- .../test/java/parReg/query/unittest/Position.java | 4 +- .../LuceneIndexXmlParserIntegrationJUnitTest.java | 11 ++- .../cache/lucene/test/LuceneTestSerializer.java | 5 ++ .../org/apache/geode/cache/util/AutoBalancer.java | 50 ++++++++--- .../util/AutoBalancerIntegrationJUnitTest.java | 21 +++-- .../geode/cache/util/AutoBalancerJUnitTest.java | 14 ++-- 26 files changed, 369 insertions(+), 109 deletions(-) diff --git a/geode-connectors/src/test/java/org/apache/geode/connectors/jdbc/JdbcWriterIntegrationTest.java b/geode-connectors/src/test/java/org/apache/geode/connectors/jdbc/JdbcWriterIntegrationTest.java index 86851b9..8401c42 100644 --- a/geode-connectors/src/test/java/org/apache/geode/connectors/jdbc/JdbcWriterIntegrationTest.java +++ b/geode-connectors/src/test/java/org/apache/geode/connectors/jdbc/JdbcWriterIntegrationTest.java @@ -210,7 +210,6 @@ public class JdbcWriterIntegrationTest { private Region<String, PdxInstance> createRegionWithJDBCSynchronousWriter(String regionName) throws ConnectionConfigExistsException, RegionMappingExistsException { jdbcWriter = new JdbcWriter(createSqlHandler()); - jdbcWriter.init(new Properties()); RegionFactory<String, PdxInstance> regionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE); diff --git a/geode-core/src/main/java/org/apache/geode/cache/Declarable.java b/geode-core/src/main/java/org/apache/geode/cache/Declarable.java index 6632cb9..c4822c6 100644 --- a/geode-core/src/main/java/org/apache/geode/cache/Declarable.java +++ b/geode-core/src/main/java/org/apache/geode/cache/Declarable.java @@ -63,6 +63,25 @@ public interface Declarable { * * @throws IllegalArgumentException If one of the configuration options in <code>props</code> is * illegal or malformed. + * @deprecated as of Geode 1.5 implement initialize instead. */ default void init(Properties props) {}; + + /** + * Initializes a user-defined object, owned by the given cache, using the given properties. + * Note that any uncaught exception + * thrown by this method will cause the <code>Cache</code> initialization to fail. + * Note that if this method is implemented then the deprecated init method should not be + * implemented. + * The product will call both methods assuming that only one will have a non-default + * implementation. + * + * @param cache the cache that owns this declarable + * @param properties Contains the parameters declared in the declarative xml file. + * + * @throws IllegalArgumentException should be thrown if properties contains something unexpected. + * + * @since Geode 1.5 + */ + default void initialize(Cache cache, Properties properties) {}; } diff --git a/geode-core/src/main/java/org/apache/geode/distributed/internal/InternalDistributedSystem.java b/geode-core/src/main/java/org/apache/geode/distributed/internal/InternalDistributedSystem.java index acf1b2e..6a59b92 100644 --- a/geode-core/src/main/java/org/apache/geode/distributed/internal/InternalDistributedSystem.java +++ b/geode-core/src/main/java/org/apache/geode/distributed/internal/InternalDistributedSystem.java @@ -986,12 +986,6 @@ public class InternalDistributedSystem extends DistributedSystem return this.securityLogWriter; } - /* - * public Cache myCache; - * - * public void setCache(Cache cache){ myCache=cache; } public Cache getCache(){ return myCache; } - */ - /** * Returns the stat sampler */ diff --git a/geode-core/src/main/java/org/apache/geode/internal/DeployedJar.java b/geode-core/src/main/java/org/apache/geode/internal/DeployedJar.java index f48edc8..328f1f8 100644 --- a/geode-core/src/main/java/org/apache/geode/internal/DeployedJar.java +++ b/geode-core/src/main/java/org/apache/geode/internal/DeployedJar.java @@ -15,18 +15,13 @@ package org.apache.geode.internal; import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; -import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.net.URL; -import java.nio.file.Files; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; @@ -298,8 +293,8 @@ public class DeployedJar { boolean registerUninitializedFunction = true; if (Declarable.class.isAssignableFrom(clazz)) { try { - final List<Properties> propertiesList = ((InternalCache) CacheFactory.getAnyInstance()) - .getDeclarableProperties(clazz.getName()); + InternalCache cache = (InternalCache) CacheFactory.getAnyInstance(); + final List<Properties> propertiesList = cache.getDeclarableProperties(clazz.getName()); if (!propertiesList.isEmpty()) { registerUninitializedFunction = false; @@ -310,7 +305,8 @@ public class DeployedJar { @SuppressWarnings("unchecked") Function function = newFunction((Class<Function>) clazz, true); if (function != null) { - ((Declarable) function).init(properties); + ((Declarable) function).initialize(cache, properties); + ((Declarable) function).init(properties); // for backwards compatibility if (function.getId() != null) { registerableFunctions.add(function); } diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/CacheCreation.java b/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/CacheCreation.java index 304ccc8..8dfacdd 100755 --- a/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/CacheCreation.java +++ b/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/CacheCreation.java @@ -45,6 +45,7 @@ import org.apache.geode.cache.Cache; import org.apache.geode.cache.CacheClosedException; import org.apache.geode.cache.CacheTransactionManager; import org.apache.geode.cache.CacheWriterException; +import org.apache.geode.cache.CacheXmlException; import org.apache.geode.cache.Declarable; import org.apache.geode.cache.DiskStore; import org.apache.geode.cache.DiskStoreFactory; @@ -196,6 +197,25 @@ public class CacheCreation implements InternalCache { // Stores the properties used to initialize declarables. private final Map<Declarable, Properties> declarablePropertiesMap = new HashMap<>(); + private final List<DeclarableAndProperties> declarablePropertiesList = new ArrayList<>(); + + private static class DeclarableAndProperties { + private final Declarable declarable; + private final Properties properties; + + public DeclarableAndProperties(Declarable d, Properties p) { + declarable = d; + properties = p; + } + + public Declarable getDeclarable() { + return declarable; + } + + public Properties getProperties() { + return properties; + } + } private final Set<GatewaySender> gatewaySenders = new HashSet<>(); @@ -417,6 +437,13 @@ public class CacheCreation implements InternalCache { throw new IllegalStateException( "You must use client-cache in the cache.xml when ClientCacheFactory is used."); } + + initializeDeclarablesMap(cache); + + if (hasFunctionService()) { + getFunctionServiceCreation().create(); + } + if (this.hasLockLease()) { cache.setLockLease(this.lockLease); } @@ -550,14 +577,30 @@ public class CacheCreation implements InternalCache { } cache.setBackupFiles(this.backups); - cache.addDeclarableProperties(this.declarablePropertiesMap); - runInitializer(); + + runInitializer(cache); cache.setInitializer(getInitializer(), getInitializerProps()); // Create all extensions this.extensionPoint.fireCreate(cache); } + public void initializeDeclarablesMap(InternalCache cache) { + for (DeclarableAndProperties struct : this.declarablePropertiesList) { + Declarable declarable = struct.getDeclarable(); + Properties properties = struct.getProperties(); + try { + declarable.initialize(cache, properties); + declarable.init(properties); // for backwards compatibility + } catch (Exception ex) { + throw new CacheXmlException( + "Exception while initializing an instance of " + declarable.getClass().getName(), ex); + } + this.declarablePropertiesMap.put(declarable, properties); + } + cache.addDeclarableProperties(this.declarablePropertiesMap); + } + void initializeRegions(Map<String, Region<?, ?>> declarativeRegions, Cache cache) { for (Region region : declarativeRegions.values()) { RegionCreation regionCreation = (RegionCreation) region; @@ -1067,7 +1110,7 @@ public class CacheCreation implements InternalCache { } void addDeclarableProperties(final Declarable declarable, final Properties properties) { - this.declarablePropertiesMap.put(declarable, properties); + this.declarablePropertiesList.add(new DeclarableAndProperties(declarable, properties)); } @Override @@ -1435,10 +1478,21 @@ public class CacheCreation implements InternalCache { return new PoolFactoryImpl(this.poolManager).setStartDisabled(true); } + private volatile boolean hasFunctionService = false; + + boolean hasFunctionService() { + return this.hasFunctionService; + } + public void setFunctionServiceCreation(FunctionServiceCreation functionServiceCreation) { + this.hasFunctionService = true; this.functionServiceCreation = functionServiceCreation; } + public FunctionServiceCreation getFunctionServiceCreation() { + return this.functionServiceCreation; + } + private volatile boolean hasResourceManager = false; private volatile ResourceManagerCreation resourceManagerCreation; @@ -1709,9 +1763,11 @@ public class CacheCreation implements InternalCache { throw new UnsupportedOperationException(LocalizedStrings.SHOULDNT_INVOKE.toLocalizedString()); } - void runInitializer() { - if (getInitializer() != null) { - getInitializer().init(getInitializerProps()); + void runInitializer(InternalCache cache) { + Declarable initializer = getInitializer(); + if (initializer != null) { + initializer.initialize(cache, getInitializerProps()); + initializer.init(getInitializerProps()); // for backwards compatibility } } diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/CacheXmlGenerator.java b/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/CacheXmlGenerator.java index 39209ea..2d4e919 100644 --- a/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/CacheXmlGenerator.java +++ b/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/CacheXmlGenerator.java @@ -25,6 +25,7 @@ import java.io.PrintWriter; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; @@ -885,12 +886,19 @@ public class CacheXmlGenerator extends CacheXml implements XMLReader { * @throws SAXException */ private void generateFunctionService() throws SAXException { - Map<String, Function> functions = FunctionService.getRegisteredFunctions(); + Collection<Function> functions = Collections.emptyList(); + if (this.cache instanceof CacheCreation) { + if (this.creation.hasFunctionService()) { + functions = this.creation.getFunctionServiceCreation().getFunctionList(); + } + } else { + functions = FunctionService.getRegisteredFunctions().values(); + } if (!generateDefaults() && functions.isEmpty()) { return; } handler.startElement("", FUNCTION_SERVICE, FUNCTION_SERVICE, EMPTY); - for (Function function : functions.values()) { + for (Function function : functions) { if (function instanceof Declarable) { handler.startElement("", FUNCTION, FUNCTION, EMPTY); generate((Declarable) function, false); diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/CacheXmlParser.java b/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/CacheXmlParser.java index 4d31534..1968fa9 100644 --- a/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/CacheXmlParser.java +++ b/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/CacheXmlParser.java @@ -1942,13 +1942,17 @@ public class CacheXmlParser extends CacheXml implements ContentHandler { String className = (String) top; logger.trace(LogMarker.CACHE_XML_PARSER, LocalizedMessage.create( LocalizedStrings.CacheXmlParser_XML_PARSER_CREATEDECLARABLE_CLASS_NAME_0, className)); + Class c; + try { + c = InternalDataSerializer.getCachedClass(className); + } catch (Exception ex) { + throw new CacheXmlException("Could not find the class: " + className, ex); + } Object o; try { - Class c = InternalDataSerializer.getCachedClass(className); o = c.newInstance(); } catch (Exception ex) { - throw new CacheXmlException( - LocalizedStrings.CacheXmlParser_WHILE_INSTANTIATING_A_0.toLocalizedString(className), ex); + throw new CacheXmlException("Could not create an instance of " + className, ex); } if (!(o instanceof Declarable)) { throw new CacheXmlException( @@ -1956,8 +1960,7 @@ public class CacheXmlParser extends CacheXml implements ContentHandler { .toLocalizedString(className)); } Declarable d = (Declarable) o; - d.init(props); - + // init call done later in GemFireCacheImpl.addDeclarableProperties cache.addDeclarableProperties(d, props); return d; @@ -2417,7 +2420,7 @@ public class CacheXmlParser extends CacheXml implements ContentHandler { .toLocalizedString()); } FunctionServiceCreation fsc = (FunctionServiceCreation) top; - fsc.create(); + this.cache.setFunctionServiceCreation(fsc); } /** diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/ClientCacheCreation.java b/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/ClientCacheCreation.java index ffee134..147d41c 100644 --- a/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/ClientCacheCreation.java +++ b/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/ClientCacheCreation.java @@ -186,6 +186,13 @@ public class ClientCacheCreation extends CacheCreation implements ClientCache { throw new IllegalStateException( "You must use ClientCacheFactory when the cache.xml uses client-cache."); } + + initializeDeclarablesMap(cache); + + if (hasFunctionService()) { + getFunctionServiceCreation().create(); + } + // create connection pools Map<String, Pool> pools = getPools(); if (!pools.isEmpty()) { @@ -256,7 +263,7 @@ public class ClientCacheCreation extends CacheCreation implements ClientCache { } cache.readyDynamicRegionFactory(); - runInitializer(); + runInitializer(cache); } public String getDefaultPoolName() { diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/FunctionServiceCreation.java b/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/FunctionServiceCreation.java index a9164de..5edab81 100755 --- a/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/FunctionServiceCreation.java +++ b/geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/FunctionServiceCreation.java @@ -14,8 +14,10 @@ */ package org.apache.geode.internal.cache.xmlcache; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import org.apache.geode.cache.execute.Function; import org.apache.geode.cache.execute.FunctionService; @@ -26,24 +28,29 @@ import org.apache.geode.cache.execute.FunctionService; */ public class FunctionServiceCreation { - private final Map<String, Function> functions = new ConcurrentHashMap<String, Function>(); + private final List<Function> functions = new ArrayList<>(); public FunctionServiceCreation() {} public void registerFunction(Function f) { - this.functions.put(f.getId(), f); - // Register to FunctionService also so that if somebody does not call - // FunctionService.create() - FunctionService.registerFunction(f); + this.functions.add(f); } public void create() { - for (Function function : this.functions.values()) { + for (Function function : this.functions) { FunctionService.registerFunction(function); } } - public Map<String, Function> getFunctions() { + List<Function> getFunctionList() { return this.functions; } + + public Map<String, Function> getFunctions() { + Map<String, Function> result = new HashMap<>(); + for (Function function : this.functions) { + result.put(function.getId(), function); + } + return result; + } } diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/domain/ClassName.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/domain/ClassName.java index 3641d74..1555c05 100644 --- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/domain/ClassName.java +++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/domain/ClassName.java @@ -24,6 +24,7 @@ import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang.StringUtils; +import org.apache.geode.cache.Cache; import org.apache.geode.cache.Declarable; import org.apache.geode.internal.ClassPathLoader; @@ -109,12 +110,14 @@ public class ClassName<T> implements Serializable { && this.getInitProperties().equals(that.getInitProperties()); } - public T newInstance() { + public T newInstance(Cache cache) { try { Class<T> loadedClass = (Class<T>) ClassPathLoader.getLatest().forName(className); T object = loadedClass.newInstance(); if (object instanceof Declarable) { - ((Declarable) object).init(initProperties); + Declarable declarable = (Declarable) object; + declarable.initialize(cache, initProperties); + declarable.init(initProperties); // for backwards compatibility } return object; } catch (Exception e) { diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/CreateAsyncEventQueueFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/CreateAsyncEventQueueFunction.java index 696f7a9..dac4564 100644 --- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/CreateAsyncEventQueueFunction.java +++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/CreateAsyncEventQueueFunction.java @@ -105,7 +105,8 @@ public class CreateAsyncEventQueueFunction implements InternalFunction { "Listener properties were provided, but the listener specified does not implement Declarable."); } - ((Declarable) listenerInstance).init(listenerProperties); + ((Declarable) listenerInstance).initialize(cache, listenerProperties); + ((Declarable) listenerInstance).init(listenerProperties); // for backwards compatibility Map<Declarable, Properties> declarablesMap = new HashMap<Declarable, Properties>(); declarablesMap.put((Declarable) listenerInstance, listenerProperties); diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionAlterFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionAlterFunction.java index 55b3d89..8d113a1 100644 --- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionAlterFunction.java +++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionAlterFunction.java @@ -148,7 +148,7 @@ public class RegionAlterFunction implements InternalFunction { if (entryIdleCustomExpiry.equals(ClassName.EMPTY)) { mutator.setCustomEntryIdleTimeout(null); } else { - mutator.setCustomEntryIdleTimeout(entryIdleCustomExpiry.newInstance()); + mutator.setCustomEntryIdleTimeout(entryIdleCustomExpiry.newInstance(cache)); } } @@ -157,7 +157,7 @@ public class RegionAlterFunction implements InternalFunction { if (entryTTLCustomExpiry.equals(ClassName.EMPTY)) { mutator.setCustomEntryTimeToLive(null); } else { - mutator.setCustomEntryTimeToLive(entryTTLCustomExpiry.newInstance()); + mutator.setCustomEntryTimeToLive(entryTTLCustomExpiry.newInstance(cache)); } } @@ -248,7 +248,7 @@ public class RegionAlterFunction implements InternalFunction { // Add new cache listeners for (ClassName<CacheListener> newCacheListener : newCacheListeners) { if (!newCacheListener.equals(ClassName.EMPTY)) { - mutator.addCacheListener(newCacheListener.newInstance()); + mutator.addCacheListener(newCacheListener.newInstance(cache)); } } if (logger.isDebugEnabled()) { @@ -261,7 +261,7 @@ public class RegionAlterFunction implements InternalFunction { if (cacheLoader.equals(ClassName.EMPTY)) { mutator.setCacheLoader(null); } else { - mutator.setCacheLoader(cacheLoader.newInstance()); + mutator.setCacheLoader(cacheLoader.newInstance(cache)); } if (logger.isDebugEnabled()) { @@ -274,7 +274,7 @@ public class RegionAlterFunction implements InternalFunction { if (cacheWriter.equals(ClassName.EMPTY)) { mutator.setCacheWriter(null); } else { - mutator.setCacheWriter(cacheWriter.newInstance()); + mutator.setCacheWriter(cacheWriter.newInstance(cache)); } if (logger.isDebugEnabled()) { diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java index 1b42caa..fd04756 100644 --- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java +++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java @@ -190,12 +190,13 @@ public class RegionCreateFunction implements InternalFunction { } if (regionCreateArgs.getEntryIdleTimeCustomExpiry() != null) { - factory - .setCustomEntryIdleTimeout(regionCreateArgs.getEntryIdleTimeCustomExpiry().newInstance()); + factory.setCustomEntryIdleTimeout( + regionCreateArgs.getEntryIdleTimeCustomExpiry().newInstance(cache)); } if (regionCreateArgs.getEntryTTLCustomExpiry() != null) { - factory.setCustomEntryTimeToLive(regionCreateArgs.getEntryTTLCustomExpiry().newInstance()); + factory + .setCustomEntryTimeToLive(regionCreateArgs.getEntryTTLCustomExpiry().newInstance(cache)); } final RegionFunctionArgs.ExpirationAttrs entryExpirationTTL = @@ -287,7 +288,7 @@ public class RegionCreateFunction implements InternalFunction { if (cacheListeners != null && !cacheListeners.isEmpty()) { List<CacheListener<K, V>> newListeners = new ArrayList<>(); for (ClassName<CacheListener> cacheListener : cacheListeners) { - newListeners.add(cacheListener.newInstance()); + newListeners.add(cacheListener.newInstance(cache)); } factory.initCacheListeners(newListeners.toArray(new CacheListener[0])); } @@ -302,12 +303,12 @@ public class RegionCreateFunction implements InternalFunction { final ClassName<CacheLoader> cacheLoader = regionCreateArgs.getCacheLoader(); if (cacheLoader != null) { - factory.setCacheLoader(cacheLoader.newInstance()); + factory.setCacheLoader(cacheLoader.newInstance(cache)); } final ClassName<CacheWriter> cacheWriter = regionCreateArgs.getCacheWriter(); if (cacheWriter != null) { - factory.setCacheWriter(cacheWriter.newInstance()); + factory.setCacheWriter(cacheWriter.newInstance(cache)); } // If a region path indicates a sub-region, diff --git a/geode-core/src/main/java/org/apache/geode/pdx/ReflectionBasedAutoSerializer.java b/geode-core/src/main/java/org/apache/geode/pdx/ReflectionBasedAutoSerializer.java index 8c8f93c..120e2ab 100644 --- a/geode-core/src/main/java/org/apache/geode/pdx/ReflectionBasedAutoSerializer.java +++ b/geode-core/src/main/java/org/apache/geode/pdx/ReflectionBasedAutoSerializer.java @@ -19,6 +19,7 @@ import java.util.Collections; import java.util.List; import java.util.Properties; +import org.apache.geode.cache.Cache; import org.apache.geode.cache.Declarable; import org.apache.geode.cache.RegionService; import org.apache.geode.pdx.internal.AutoSerializableManager; @@ -356,7 +357,6 @@ public class ReflectionBasedAutoSerializer implements PdxSerializer, Declarable return manager.readData(reader, clazz); } - /** * Used for declarative class initialization from cache.xml. The following property may be * specified: @@ -369,12 +369,35 @@ public class ReflectionBasedAutoSerializer implements PdxSerializer, Declarable * serialize data that is not portable to .NET is made. * * @param props properties used to configure the auto serializer + * @deprecated as of Geode 1.5 use initialize instead */ + @Override public void init(Properties props) { this.manager.init(props); } /** + * Used for declarative class initialization from cache.xml. The following property may be + * specified: + * <ul> + * <li><b>classes</b> - a comma-delimited list of strings which represent the patterns used to + * select classes for serialization, patterns to select identity fields and patterns to exclude + * fields. See {@link ReflectionBasedAutoSerializer#reconfigure(String...) reconfigure} for + * specifics.</li> + * <li><b>check-portability</b> - if true then an exception will be thrown if an attempt to + * serialize data that is not portable to .NET is made. + * + * @param cache the cache that owns this serializer + * @param props properties used to configure the auto serializer + * @since Geode 1.5 + */ + @Override + public void initialize(Cache cache, Properties props) { + this.manager.setRegionService(cache); + this.manager.init(props); + } + + /** * Return a <code>Properties</code> object with a representation of the current config. Depending * on how this <code>ReflectionBasedAutoSerializer</code> was configured, the returned property * value will have the correct semantics but may differ from the the original configuration diff --git a/geode-core/src/test/java/org/apache/geode/cache30/CacheXml66DUnitTest.java b/geode-core/src/test/java/org/apache/geode/cache30/CacheXml66DUnitTest.java index 5806c98..7ad2f05 100644 --- a/geode-core/src/test/java/org/apache/geode/cache30/CacheXml66DUnitTest.java +++ b/geode-core/src/test/java/org/apache/geode/cache30/CacheXml66DUnitTest.java @@ -1879,11 +1879,11 @@ public abstract class CacheXml66DUnitTest extends CacheXmlTestCase { } /** - * Tests that a cache created with FunctionService and registered FabricFunction has correct - * registered Function + * Tests that a cache created with FunctionService and registered functions has correct registered + * functions. */ @Test - public void testCacheCreationWithFuntionService() throws Exception { + public void testCacheCreationWithFunctionService() throws Exception { CacheCreation cache = new CacheCreation(); FunctionServiceCreation fsc = new FunctionServiceCreation(); TestFunction function1 = new TestFunction(true, TestFunction.TEST_FUNCTION2); diff --git a/geode-core/src/test/java/org/apache/geode/cache30/ReconnectDUnitTest.java b/geode-core/src/test/java/org/apache/geode/cache30/ReconnectDUnitTest.java index f878e79..4db8f92 100755 --- a/geode-core/src/test/java/org/apache/geode/cache30/ReconnectDUnitTest.java +++ b/geode-core/src/test/java/org/apache/geode/cache30/ReconnectDUnitTest.java @@ -1027,8 +1027,6 @@ public class ReconnectDUnitTest extends JUnit4CacheTestCase { final int locPort = locatorPort; - final String xmlFileLoc = (new File(".")).getAbsolutePath(); - SerializableRunnable createCache = new SerializableRunnable("Create Cache and Regions") { public void run() { locatorPort = locPort; @@ -1074,7 +1072,8 @@ public class ReconnectDUnitTest extends JUnit4CacheTestCase { } /** - * GEODE-2155 Auto-reconnect fails with NPE due to a cache listener not implementing Declarable + * GEODE-2155 Auto-reconnect fails with NPE due to a cache listener Declarable.init method + * throwing an exception. */ @Test public void testReconnectFailsDueToBadCacheXML() throws Exception { @@ -1085,8 +1084,6 @@ public class ReconnectDUnitTest extends JUnit4CacheTestCase { final int locPort = locatorPort; - final String xmlFileLoc = (new File(".")).getAbsolutePath(); - SerializableRunnable createCache = new SerializableRunnable("Create Cache and Regions") { public void run() { locatorPort = locPort; @@ -1097,7 +1094,7 @@ public class ReconnectDUnitTest extends JUnit4CacheTestCase { ReconnectDUnitTest.savedCache = (GemFireCacheImpl) getCache(); Region myRegion = createRegion("myRegion", createAtts()); myRegion.put("MyKey", "MyValue"); - myRegion.getAttributesMutator().addCacheListener(new NonDeclarableListener()); + myRegion.getAttributesMutator().addCacheListener(new ListenerWhoseInitMethodAlwaysThrows()); } }; @@ -1276,13 +1273,14 @@ public class ReconnectDUnitTest extends JUnit4CacheTestCase { } /** - * A non-Declarable listener will be rejected by the XML parser when rebuilding the cache, causing - * auto-reconnect to fail. + * A listener whose init always throws an exception. + * Since init is always called during cache.xml parsing + * this listener is not able to be used from cache.xml. */ - public static class NonDeclarableListener extends CacheListenerAdapter { + public static class ListenerWhoseInitMethodAlwaysThrows extends CacheListenerAdapter { @Override public void init(Properties props) { - throw new RuntimeException("Simulate non-declarable listener"); + throw new RuntimeException("Cause parsing to fail"); }; } diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/xmlcache/CacheCreationJUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/xmlcache/CacheCreationJUnitTest.java index 38b2304..0c51878 100644 --- a/geode-core/src/test/java/org/apache/geode/internal/cache/xmlcache/CacheCreationJUnitTest.java +++ b/geode-core/src/test/java/org/apache/geode/internal/cache/xmlcache/CacheCreationJUnitTest.java @@ -14,12 +14,16 @@ */ package org.apache.geode.internal.cache.xmlcache; +import static com.googlecode.catchexception.CatchException.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Properties; import org.junit.Before; import org.junit.Test; @@ -28,6 +32,8 @@ import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.apache.geode.cache.CacheXmlException; +import org.apache.geode.cache.Declarable; import org.apache.geode.cache.Region; import org.apache.geode.cache.server.CacheServer; import org.apache.geode.cache.wan.GatewayReceiver; @@ -49,6 +55,98 @@ public class CacheCreationJUnitTest { CacheServerLauncher.clearStatics(); } + @SuppressWarnings("deprecation") + @Test + public void verifyRunInitializerWithInitializerAndNullPropsCallsInitAndInitialize() { + @SuppressWarnings("resource") + CacheCreation cacheCreation = new CacheCreation(); + Declarable initializer = mock(Declarable.class); + Properties props = null; + cacheCreation.setInitializer(initializer, props); + + cacheCreation.runInitializer(this.cache); + + verify(initializer, times(1)).init(eq(props)); + verify(initializer, times(1)).initialize(eq(this.cache), eq(props)); + } + + @SuppressWarnings("deprecation") + @Test + public void verifyRunInitializerWithInitializerAndPropsCallsInitAndInitialize() { + @SuppressWarnings("resource") + CacheCreation cacheCreation = new CacheCreation(); + Declarable initializer = mock(Declarable.class); + Properties props = new Properties(); + props.setProperty("key", "value"); + cacheCreation.setInitializer(initializer, props); + + cacheCreation.runInitializer(this.cache); + + verify(initializer, times(1)).init(eq(props)); + verify(initializer, times(1)).initialize(eq(this.cache), eq(props)); + } + + @Test + public void verifyInitializeDeclarablesMapWithNoDeclarablesPassesEmptyMap() { + @SuppressWarnings("resource") + CacheCreation cacheCreation = new CacheCreation(); + Map<Declarable, Properties> expected = Collections.emptyMap(); + + cacheCreation.initializeDeclarablesMap(this.cache); + + verify(this.cache, times(1)).addDeclarableProperties(eq(expected)); + } + + @Test + public void verifyInitializeDeclarablesMapWithDeclarablesPassesExpectedMap() { + @SuppressWarnings("resource") + CacheCreation cacheCreation = new CacheCreation(); + Map<Declarable, Properties> expected = new HashMap<>(); + Declarable d1 = mock(Declarable.class); + cacheCreation.addDeclarableProperties(d1, null); + expected.put(d1, null); + Declarable d2 = mock(Declarable.class); + Properties p2 = new Properties(); + p2.setProperty("k2", "v2"); + cacheCreation.addDeclarableProperties(d2, p2); + expected.put(d2, p2); + + cacheCreation.initializeDeclarablesMap(this.cache); + + verify(this.cache, times(1)).addDeclarableProperties(eq(expected)); + } + + @Test + public void verifyInitializeDeclarablesMapWithDeclarableCallInitAndInitialize() { + @SuppressWarnings("resource") + CacheCreation cacheCreation = new CacheCreation(); + Declarable d2 = mock(Declarable.class); + Properties p2 = new Properties(); + p2.setProperty("k2", "v2"); + cacheCreation.addDeclarableProperties(d2, p2); + + cacheCreation.initializeDeclarablesMap(this.cache); + + verify(d2, times(1)).init(eq(p2)); + verify(d2, times(1)).initialize(eq(this.cache), eq(p2)); + } + + @Test + public void verifyInitializeDeclarablesMapWithDeclarableThatThrowsWillThrowCacheXmlException() { + @SuppressWarnings("resource") + CacheCreation cacheCreation = new CacheCreation(); + Declarable d2 = mock(Declarable.class); + Properties p2 = null; + cacheCreation.addDeclarableProperties(d2, p2); + Throwable cause = new RuntimeException("expected"); + doThrow(cause).when(d2).initialize(this.cache, null); + + catchException(cacheCreation).initializeDeclarablesMap(this.cache); + + assertThat((Exception) caughtException()).isExactlyInstanceOf(CacheXmlException.class) + .hasMessageStartingWith("Exception while initializing an instance of").hasCause(cause); + } + @Test public void declarativeRegionIsCreated() { CacheCreation cacheCreation = new CacheCreation(); diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/domain/ClassNameTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/domain/ClassNameTest.java index 07ebae6..73cb525 100644 --- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/domain/ClassNameTest.java +++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/domain/ClassNameTest.java @@ -45,7 +45,7 @@ public class ClassNameTest { @Test public void emptyCanNotInstantiate() { - assertThatThrownBy(() -> ClassName.EMPTY.newInstance()).isInstanceOf(RuntimeException.class) + assertThatThrownBy(() -> ClassName.EMPTY.newInstance(null)).isInstanceOf(RuntimeException.class) .hasMessageContaining("Error instantiating class"); } @@ -101,7 +101,7 @@ public class ClassNameTest { @Test public void getInstance() { ClassName<String> klass = new ClassName("java.lang.String"); - String s = klass.newInstance(); + String s = klass.newInstance(null); assertThat(s.toString()).isEqualTo(""); } @@ -109,7 +109,7 @@ public class ClassNameTest { public void getInstanceWithProps() { String json = "{\"k\":\"v\"}"; ClassName<MyCacheWriter> cacheWriter = new ClassName<>(MyCacheWriter.class.getName(), json); - MyCacheWriter obj = cacheWriter.newInstance(); + MyCacheWriter obj = cacheWriter.newInstance(null); assertThat(obj.getProperties()).containsEntry("k", "v").containsOnlyKeys("k"); } } diff --git a/geode-core/src/test/java/org/apache/geode/pdx/AutoSerializableJUnitTest.java b/geode-core/src/test/java/org/apache/geode/pdx/AutoSerializableJUnitTest.java index 4514a9c..979c83e 100644 --- a/geode-core/src/test/java/org/apache/geode/pdx/AutoSerializableJUnitTest.java +++ b/geode-core/src/test/java/org/apache/geode/pdx/AutoSerializableJUnitTest.java @@ -1058,7 +1058,7 @@ public class AutoSerializableJUnitTest { setupSerializer(); Properties props = new Properties(); props.put("classes", "org.apache.geode.pdx.DomainObject"); - serializer.init(props); + serializer.initialize(null, props); assertEquals(4, manager.getFields(DomainObject.class).size()); } @@ -1071,7 +1071,7 @@ public class AutoSerializableJUnitTest { setupSerializer(); Properties props = new Properties(); props.put("classes", "org.apache.geode.pdx.DomainObject#exclude=long.*"); - serializer.init(props); + serializer.initialize(this.c, props); assertEquals(3, manager.getFields(DomainObject.class).size()); } @@ -1081,7 +1081,7 @@ public class AutoSerializableJUnitTest { setupSerializer(); Properties props = new Properties(); props.put("classes", "org.apache.geode.pdx.DomainObject#exclude=string.* ,"); - serializer.init(props); + serializer.initialize(this.c, props); assertEquals(1, manager.getFields(DomainObject.class).size()); } @@ -1094,7 +1094,7 @@ public class AutoSerializableJUnitTest { setupSerializer(); Properties props = new Properties(); props.put("classes", "org.apache.geode.pdx.DomainObjectPdxAuto#identity=long.*"); - serializer.init(props); + serializer.initialize(this.c, props); DomainObject objOut = new DomainObjectPdxAuto(4); objOut.set("string_0", "test string value"); @@ -1119,7 +1119,7 @@ public class AutoSerializableJUnitTest { Properties props = new Properties(); props.put("classes", "org.apache.geode.pdx.DomainObjectPdxAuto#identity=long.*#exclude=string.*"); - serializer.init(props); + serializer.initialize(this.c, props); assertEquals(27, manager.getFields(DomainObjectPdxAuto.class).size()); @@ -1147,7 +1147,7 @@ public class AutoSerializableJUnitTest { Properties props = new Properties(); props.put("classes", "org.apache.geode.pdx.DomainObjectPdxAuto#identity=long.*#exclude=string.*#, com.another.class.Foo"); - serializer.init(props); + serializer.initialize(this.c, props); assertEquals(27, manager.getFields(DomainObjectPdxAuto.class).size()); @@ -1175,7 +1175,7 @@ public class AutoSerializableJUnitTest { Properties props = new Properties(); props.put("classes", "org.apache.geode.pdx.DomainObjectPdxAuto#identity=long.*#exclude=string.*, com.another.class.Foo"); - serializer.init(props); + serializer.initialize(this.c, props); assertEquals(27, manager.getFields(DomainObjectPdxAuto.class).size()); @@ -1203,7 +1203,7 @@ public class AutoSerializableJUnitTest { Properties props = new Properties(); props.put("classes", "org.apache.geode.pdx.DomainObjectPdxAuto#exclude=string.*, " + "org.apache.geode.pdx.DomainObjectPdxAuto#exclude=long.*"); - serializer.init(props); + serializer.initialize(this.c, props); assertEquals(26, manager.getFields(DomainObjectPdxAuto.class).size()); } @@ -1217,7 +1217,7 @@ public class AutoSerializableJUnitTest { Properties props = new Properties(); props.put("classes", "Pdx#exclude=string.*#exclude=badField, Pdx#identity=id.*, PdxAuto#exclude=long.*#identity=id.*"); - serializer.init(props); + serializer.initialize(this.c, props); Properties result = serializer.getConfig(); assertEquals( @@ -1225,7 +1225,7 @@ public class AutoSerializableJUnitTest { result.getProperty("classes")); manager.resetCaches(); - serializer.init(result); + serializer.initialize(this.c, result); result = serializer.getConfig(); assertEquals( diff --git a/geode-core/src/test/java/parReg/query/unittest/NewPortfolio.java b/geode-core/src/test/java/parReg/query/unittest/NewPortfolio.java index 6ddc134..3db9f89 100755 --- a/geode-core/src/test/java/parReg/query/unittest/NewPortfolio.java +++ b/geode-core/src/test/java/parReg/query/unittest/NewPortfolio.java @@ -121,7 +121,7 @@ public class NewPortfolio implements Serializable { props.setProperty("secId", Integer.toString(secId)); Position pos = new Position(); - pos.init(props); + pos.initialize(null, props); this.positions.put(pos.getSecId(), pos); } } diff --git a/geode-core/src/test/java/parReg/query/unittest/Position.java b/geode-core/src/test/java/parReg/query/unittest/Position.java index 7ee10d0..0647ed4 100755 --- a/geode-core/src/test/java/parReg/query/unittest/Position.java +++ b/geode-core/src/test/java/parReg/query/unittest/Position.java @@ -17,6 +17,7 @@ package parReg.query.unittest; import java.io.Serializable; import java.util.*; +import org.apache.geode.cache.Cache; import org.apache.geode.cache.Declarable; /** @@ -40,7 +41,8 @@ public class Position implements Declarable, Serializable, Comparable { private final int NUM_OF_SECURITIES = 200; private final int MAX_PRICE = 100; - public void init(Properties props) { + @Override + public void initialize(Cache cache, Properties props) { this.secId = props.getProperty("secId"); this.qty = Double.parseDouble(props.getProperty("qty")); this.mktValue = Double.parseDouble(props.getProperty("mktValue")); diff --git a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/xml/LuceneIndexXmlParserIntegrationJUnitTest.java b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/xml/LuceneIndexXmlParserIntegrationJUnitTest.java index d79bd4c..c7838f8 100644 --- a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/xml/LuceneIndexXmlParserIntegrationJUnitTest.java +++ b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/xml/LuceneIndexXmlParserIntegrationJUnitTest.java @@ -19,6 +19,7 @@ import static org.apache.geode.distributed.ConfigurationProperties.*; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -44,6 +45,7 @@ import org.apache.geode.cache.lucene.LuceneSerializer; import org.apache.geode.cache.lucene.LuceneService; import org.apache.geode.cache.lucene.LuceneServiceProvider; import org.apache.geode.cache.lucene.test.LuceneTestSerializer; +import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.cache.extension.Extension; import org.apache.geode.internal.cache.xmlcache.CacheCreation; import org.apache.geode.internal.cache.xmlcache.CacheXmlParser; @@ -166,8 +168,13 @@ public class LuceneIndexXmlParserIntegrationJUnitTest { private RegionCreation createRegionCreation(String regionName) throws FileNotFoundException { CacheXmlParser parser = CacheXmlParser.parse(new FileInputStream(getXmlFileForTest())); - CacheCreation cache = parser.getCacheCreation(); - return (RegionCreation) cache.getRegion(regionName); + CacheCreation cacheCreation = parser.getCacheCreation(); + // Some of the tests in this class needs to have the declarables initialized. + // cacheCreation.create(InternalCache) would do this but it was too much work + // to mock the InternalCache for all the ways create used it. + // So instead we just call initializeDeclarablesMap which is also what create does. + cacheCreation.initializeDeclarablesMap(mock(InternalCache.class)); + return (RegionCreation) cacheCreation.getRegion(regionName); } private void validateExpectedIndexes(RegionCreation region, diff --git a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/test/LuceneTestSerializer.java b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/test/LuceneTestSerializer.java index 83132ca..a415c86 100644 --- a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/test/LuceneTestSerializer.java +++ b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/test/LuceneTestSerializer.java @@ -61,6 +61,11 @@ public class LuceneTestSerializer implements LuceneSerializer { } @Override + public String toString() { + return "LuceneTestSerializer [props=" + props + "]"; + } + + @Override public Collection<Document> toDocuments(LuceneIndex index, Object value) { return Collections.emptyList(); } diff --git a/geode-rebalancer/src/main/java/org/apache/geode/cache/util/AutoBalancer.java b/geode-rebalancer/src/main/java/org/apache/geode/cache/util/AutoBalancer.java index 7f7db01..1a061d7 100644 --- a/geode-rebalancer/src/main/java/org/apache/geode/cache/util/AutoBalancer.java +++ b/geode-rebalancer/src/main/java/org/apache/geode/cache/util/AutoBalancer.java @@ -31,6 +31,7 @@ import org.springframework.scheduling.support.CronSequenceGenerator; import org.apache.geode.GemFireConfigException; import org.apache.geode.annotations.Experimental; +import org.apache.geode.cache.Cache; import org.apache.geode.cache.CacheClosedException; import org.apache.geode.cache.Declarable; import org.apache.geode.cache.GemFireCache; @@ -39,7 +40,6 @@ import org.apache.geode.cache.control.RebalanceResults; import org.apache.geode.cache.partition.PartitionMemberInfo; import org.apache.geode.distributed.DistributedLockService; import org.apache.geode.distributed.internal.locks.DLockService; -import org.apache.geode.internal.cache.GemFireCacheImpl; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.cache.PartitionedRegion; import org.apache.geode.internal.cache.partitioned.InternalPRInfo; @@ -132,6 +132,8 @@ public class AutoBalancer implements Declarable { private final TimeProvider clock; private final CacheOperationFacade cacheFacade; + private boolean initialized; + private static final Logger logger = LogService.getLogger(); public AutoBalancer() { @@ -147,7 +149,29 @@ public class AutoBalancer implements Declarable { } @Override + public void initialize(Cache cache, Properties props) { + this.cacheFacade.setCache(cache); + internalInitialize(props); + } + + /** + * @deprecated as of Geode 1.5 use initialize instead. + */ public void init(Properties props) { + internalInitialize(props); + } + + private void internalInitialize(Properties props) { + if (this.initialized) { + // For backwards compatibility we need to keep the external + // init method. But the product will call both initialize and + // init. So if we are already initialized subsequent calls + // are a noop. Once the deprecated init method is removed, this + // boolean check can also be removed. + return; + } + this.initialized = true; + if (logger.isDebugEnabled()) { logger.debug("Initializing " + this.getClass().getSimpleName() + " with " + props); } @@ -443,21 +467,14 @@ public class AutoBalancer implements Declarable { } InternalCache getCache() { - // TODO: delete this double-checking - if (cache == null) { - synchronized (this) { - if (cache == null) { - cache = GemFireCacheImpl.getInstance(); - if (cache == null) { - throw new IllegalStateException("Missing cache instance."); - } - } - } + InternalCache result = cache; + if (result == null) { + throw new IllegalStateException("Missing cache instance."); } - if (cache.isClosed()) { + if (result.isClosed()) { throw new CacheClosedException(); } - return cache; + return result; } @Override @@ -501,6 +518,11 @@ public class AutoBalancer implements Declarable { return dls; } + + @Override + public void setCache(Cache cache) { + this.cache = (InternalCache) cache; + } } private static class SystemClockTimeProvider implements TimeProvider { @@ -529,6 +551,8 @@ public class AutoBalancer implements Declarable { interface CacheOperationFacade { boolean acquireAutoBalanceLock(); + void setCache(Cache cache); + DistributedLockService getDLS(); void rebalance(); diff --git a/geode-rebalancer/src/test/java/org/apache/geode/cache/util/AutoBalancerIntegrationJUnitTest.java b/geode-rebalancer/src/test/java/org/apache/geode/cache/util/AutoBalancerIntegrationJUnitTest.java index ad0f4f5..1a8a505 100755 --- a/geode-rebalancer/src/test/java/org/apache/geode/cache/util/AutoBalancerIntegrationJUnitTest.java +++ b/geode-rebalancer/src/test/java/org/apache/geode/cache/util/AutoBalancerIntegrationJUnitTest.java @@ -21,6 +21,7 @@ import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.*; import java.io.ByteArrayInputStream; +import java.util.Properties; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -86,6 +87,10 @@ public class AutoBalancerIntegrationJUnitTest { public void testAutoRebalaceStatsOnLockSuccess() throws InterruptedException { assertEquals(0, cache.getInternalResourceManager().getStats().getAutoRebalanceAttempts()); AutoBalancer balancer = new AutoBalancer(); + final String someSchedule = "1 * * * 1 *"; + final Properties props = new Properties(); + props.put(AutoBalancer.SCHEDULE, someSchedule); + balancer.initialize(cache, props); balancer.getOOBAuditor().execute(); assertEquals(1, cache.getInternalResourceManager().getStats().getAutoRebalanceAttempts()); } @@ -95,6 +100,10 @@ public class AutoBalancerIntegrationJUnitTest { acquireLockInDifferentThread(1); assertEquals(0, cache.getInternalResourceManager().getStats().getAutoRebalanceAttempts()); AutoBalancer balancer = new AutoBalancer(); + final String someSchedule = "1 * * * 1 *"; + final Properties props = new Properties(); + props.put(AutoBalancer.SCHEDULE, someSchedule); + balancer.initialize(cache, props); balancer.getOOBAuditor().execute(); assertEquals(0, cache.getInternalResourceManager().getStats().getAutoRebalanceAttempts()); } @@ -102,27 +111,27 @@ public class AutoBalancerIntegrationJUnitTest { @Test public void testAutoBalanceStatUpdate() { assertEquals(0, cache.getInternalResourceManager().getStats().getAutoRebalanceAttempts()); - new GeodeCacheFacade().incrementAttemptCounter(); + new GeodeCacheFacade(cache).incrementAttemptCounter(); assertEquals(1, cache.getInternalResourceManager().getStats().getAutoRebalanceAttempts()); } @Test public void testLockSuccess() throws InterruptedException { acquireLockInDifferentThread(1); - DistributedLockService dls = new GeodeCacheFacade().getDLS(); + DistributedLockService dls = new GeodeCacheFacade(cache).getDLS(); assertFalse(dls.lock(AutoBalancer.AUTO_BALANCER_LOCK, 0, -1)); } @Test public void canReacquireLock() throws InterruptedException { acquireLockInDifferentThread(2); - DistributedLockService dls = new GeodeCacheFacade().getDLS(); + DistributedLockService dls = new GeodeCacheFacade(cache).getDLS(); assertFalse(dls.lock(AutoBalancer.AUTO_BALANCER_LOCK, 0, -1)); } @Test public void testLockAlreadyTakenElsewhere() throws InterruptedException { - DistributedLockService dls = new GeodeCacheFacade().getDLS(); + DistributedLockService dls = new GeodeCacheFacade(cache).getDLS(); assertTrue(dls.lock(AutoBalancer.AUTO_BALANCER_LOCK, 0, -1)); final AtomicBoolean success = new AtomicBoolean(true); @@ -130,7 +139,7 @@ public class AutoBalancerIntegrationJUnitTest { Thread thread = new Thread(new Runnable() { @Override public void run() { - CacheOperationFacade cacheFacade = new GeodeCacheFacade(); + CacheOperationFacade cacheFacade = new GeodeCacheFacade(cache); success.set(cacheFacade.acquireAutoBalanceLock()); } }); @@ -191,7 +200,7 @@ public class AutoBalancerIntegrationJUnitTest { Thread thread = new Thread(new Runnable() { @Override public void run() { - CacheOperationFacade cacheFacade = new GeodeCacheFacade(); + CacheOperationFacade cacheFacade = new GeodeCacheFacade(cache); for (int i = 0; i < num; i++) { boolean result = cacheFacade.acquireAutoBalanceLock(); if (result) { diff --git a/geode-rebalancer/src/test/java/org/apache/geode/cache/util/AutoBalancerJUnitTest.java b/geode-rebalancer/src/test/java/org/apache/geode/cache/util/AutoBalancerJUnitTest.java index 958d8f9..3ef1abb 100644 --- a/geode-rebalancer/src/test/java/org/apache/geode/cache/util/AutoBalancerJUnitTest.java +++ b/geode-rebalancer/src/test/java/org/apache/geode/cache/util/AutoBalancerJUnitTest.java @@ -294,7 +294,7 @@ public class AutoBalancerJUnitTest { AutoBalancer balancer = new AutoBalancer(); Properties props = getBasicConfig(); props.put(AutoBalancer.SIZE_THRESHOLD_PERCENT, "-1"); - balancer.init(props); + balancer.initialize(null, props); } @Test(expected = GemFireConfigException.class) @@ -302,7 +302,7 @@ public class AutoBalancerJUnitTest { AutoBalancer balancer = new AutoBalancer(); Properties props = getBasicConfig(); props.put(AutoBalancer.MINIMUM_SIZE, "-1"); - balancer.init(props); + balancer.initialize(null, props); } @Test(expected = GemFireConfigException.class) @@ -310,7 +310,7 @@ public class AutoBalancerJUnitTest { AutoBalancer balancer = new AutoBalancer(); Properties props = getBasicConfig(); props.put(AutoBalancer.SIZE_THRESHOLD_PERCENT, "0"); - balancer.init(props); + balancer.initialize(null, props); } @Test(expected = GemFireConfigException.class) @@ -318,7 +318,7 @@ public class AutoBalancerJUnitTest { AutoBalancer balancer = new AutoBalancer(); Properties props = getBasicConfig(); props.put(AutoBalancer.SIZE_THRESHOLD_PERCENT, "100"); - balancer.init(props); + balancer.initialize(null, props); } @Test @@ -336,7 +336,7 @@ public class AutoBalancerJUnitTest { }); AutoBalancer autoR = new AutoBalancer(mockScheduler, mockAuditor, null, null); - autoR.init(props); + autoR.initialize(null, props); } @Test @@ -560,7 +560,7 @@ public class AutoBalancerJUnitTest { assertEquals(3, latch.getCount()); AutoBalancer autoR = new AutoBalancer(null, mockAuditor, mockClock, null); - autoR.init(props); + autoR.initialize(null, props); assertTrue(latch.await(1, TimeUnit.SECONDS)); } @@ -594,7 +594,7 @@ public class AutoBalancerJUnitTest { assertEquals(2, latch.getCount()); AutoBalancer autoR = new AutoBalancer(null, mockAuditor, mockClock, null); - autoR.init(props); + autoR.initialize(null, props); assertTrue(latch.await(1, TimeUnit.SECONDS)); // after destroy no more execute will be called. -- To stop receiving notification emails like this one, please contact dschnei...@apache.org.