JBoss Cache SVN: r5810 - in benchmarks/benchmark-fwk/trunk: cache-products and 6 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-05-08 07:23:24 -0400 (Thu, 08 May 2008)
New Revision: 5810
Added:
benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/
benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/config.sh
benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/lib/
benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/lib/commons-collections-3.1.jar
benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/lib/commons-logging.jar
benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/lib/concurrent-1.3.4.jar
benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/lib/whirlycache-1.0.1.jar
benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/src/
benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/src/org/
benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/src/org/cachebench/
benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/src/org/cachebench/cachewrappers/
benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/src/org/cachebench/cachewrappers/WhirlyCacheTest.java
benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/src/org/cachebench/cachewrappers/WhirlyCacheWrapper.java
Modified:
benchmarks/benchmark-fwk/trunk/build.xml
Log:
Added WhirlyCache 1.0.1
Modified: benchmarks/benchmark-fwk/trunk/build.xml
===================================================================
--- benchmarks/benchmark-fwk/trunk/build.xml 2008-05-08 11:22:33 UTC (rev 5809)
+++ benchmarks/benchmark-fwk/trunk/build.xml 2008-05-08 11:23:24 UTC (rev 5810)
@@ -359,6 +359,73 @@
</target>
+ <!-- Module whirlycache-1.0.1 -->
+
+ <dirname property="module.whirlycache101-plugin.basedir" file="${ant.file}"/>
+
+
+ <property name="compiler.args.whirlycache101-plugin" value="${compiler.args}"/>
+
+ <property name="whirlycache101-plugin.output.dir"
+ value="${module.whirlycache101-plugin.basedir}/classes/production/whirlycache-1.0.1"/>
+ <property name="whirlycache101-plugin.testoutput.dir"
+ value="${module.whirlycache101-plugin.basedir}/classes/test/whirlycache-1.0.1"/>
+
+ <path id="whirlycache101-plugin.module.bootclasspath">
+ <!-- Paths to be included in compilation bootclasspath -->
+ </path>
+
+ <path id="whirlycache101-plugin.module.classpath">
+ <fileset dir="${module.whirlycache101-plugin.basedir}/cache-products/whirlycache-1.0.1/lib" includes="**/*.jar"/>
+ <pathelement location="${framework.output.dir}"/>
+ <pathelement location="${framework.testoutput.dir}"/>
+ <pathelement location="${whirlycache101-plugin.output.dir}"/>
+ <pathelement location="${module.whirlycache101-plugin.basedir}/cache-products/whirlycache-1.0.1/conf"/>
+ </path>
+
+
+ <patternset id="excluded.from.module.whirlycache101-plugin">
+ <patternset refid="ignored.files"/>
+ </patternset>
+
+ <patternset id="excluded.from.compilation.whirlycache101-plugin">
+ <patternset refid="excluded.from.module.whirlycache101-plugin"/>
+ </patternset>
+
+ <path id="whirlycache101-plugin.module.sourcepath">
+ <dirset dir="${module.whirlycache101-plugin.basedir}/cache-products/whirlycache-1.0.1">
+ <include name="src"/>
+ </dirset>
+ </path>
+
+
+ <target name="compile.module.whirlycache101-plugin"
+ depends="compile.module.whirlycache101-plugin.production,compile.module.whirlycache101-plugin.tests"
+ description="Compile module whirlycache-1.0.1"/>
+
+ <target name="compile.module.whirlycache101-plugin.production" depends="compile.module.framework"
+ description="Compile module whirlycache-1.0.1; production classes">
+ <mkdir dir="${whirlycache101-plugin.output.dir}"/>
+ <javac destdir="${whirlycache101-plugin.output.dir}" debug="${compiler.debug}"
+ nowarn="${compiler.generate.no.warnings}" memorymaximumsize="${compiler.max.memory}" fork="true">
+ <compilerarg line="${compiler.args.whirlycache101-plugin}"/>
+ <bootclasspath refid="whirlycache101-plugin.module.bootclasspath"/>
+ <classpath refid="whirlycache101-plugin.module.classpath"/>
+ <src refid="whirlycache101-plugin.module.sourcepath"/>
+ <patternset refid="excluded.from.compilation.whirlycache101-plugin"/>
+ </javac>
+
+ <copy todir="${whirlycache101-plugin.output.dir}">
+ <fileset dir="${module.whirlycache101-plugin.basedir}/cache-products/whirlycache-1.0.1/src">
+ <patternset refid="compiler.resources"/>
+ <type type="file"/>
+ </fileset>
+ </copy>
+ </target>
+
+ <target name="compile.module.whirlycache101-plugin.tests" depends="compile.module.whirlycache101-plugin.production"
+ description="compile module whirlycache-1.0.1; test classes" unless="skip.tests"/>
+
<!-- Module jbosscache-1.4.1 -->
<dirname property="module.jbosscache140-plugin.basedir" file="${ant.file}"/>
@@ -548,7 +615,7 @@
</target>
<target name="all"
- depends="init, clean, compile.module.framework, compile.module.ehcache141-plugin.production, compile.module.jbosscache140-plugin, compile.module.jbosscache200-plugin, compile.module.jbosscache210-plugin.production, compile.module.jbosscache220-plugin.production, compile.module.terracotta-plugin"
+ depends="init, clean, compile.module.framework, compile.module.whirlycache101-plugin.production, compile.module.ehcache141-plugin.production, compile.module.jbosscache140-plugin, compile.module.jbosscache200-plugin, compile.module.jbosscache210-plugin.production, compile.module.jbosscache220-plugin.production, compile.module.terracotta-plugin"
description="build all"/>
<target name="checkClusterAddresses" depends="compile.module.framework.production"
Added: benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/config.sh
===================================================================
--- benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/config.sh (rev 0)
+++ benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/config.sh 2008-05-08 11:23:24 UTC (rev 5810)
@@ -0,0 +1,18 @@
+#!/bin/bash
+
+#see "$CACHE_ROOT/cache-products/cache.sh" for details
+
+THIS_DIR="./cache-products/whirlycache-1.0.1"
+
+#setting up classpath
+for JAR in $THIS_DIR/lib/*
+do
+ CLASSPATH=$CLASSPATH:$JAR
+done
+
+CLASSPATH="$CLASSPATH:./classes/production/whirlycache-1.0.1"
+CLASSPATH="$CLASSPATH:$THIS_DIR/conf"
+#--classpath was set
+
+#additional JVM options
+JVM_OPTIONS="$JVM_OPTIONS -Xmx1024m -Djava.net.preferIPv4Stack=true" JVM_OPTIONS="$JVM_OPTIONS -DcacheBenchFwk.cacheWrapperClassName=org.cachebench.cachewrappers.WhirlyCacheWrapper"
Added: benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/lib/commons-collections-3.1.jar
===================================================================
(Binary files differ)
Property changes on: benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/lib/commons-collections-3.1.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/lib/commons-logging.jar
===================================================================
(Binary files differ)
Property changes on: benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/lib/commons-logging.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/lib/concurrent-1.3.4.jar
===================================================================
(Binary files differ)
Property changes on: benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/lib/concurrent-1.3.4.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/lib/whirlycache-1.0.1.jar
===================================================================
(Binary files differ)
Property changes on: benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/lib/whirlycache-1.0.1.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/src/org/cachebench/cachewrappers/WhirlyCacheTest.java
===================================================================
--- benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/src/org/cachebench/cachewrappers/WhirlyCacheTest.java (rev 0)
+++ benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/src/org/cachebench/cachewrappers/WhirlyCacheTest.java 2008-05-08 11:23:24 UTC (rev 5810)
@@ -0,0 +1,26 @@
+package org.cachebench.cachewrappers;
+
+import org.cachebench.CacheWrapper;
+
+public class WhirlyCacheTest
+{
+
+ public static void main(String[] args) throws Exception
+ {
+
+
+ CacheWrapper w = new WhirlyCacheWrapper();
+ w.init(null);
+ w.setUp();
+ String k = "k", v = "v";
+
+ w.put(k, v);
+
+ System.out.println("Value is " + w.get(k));
+
+ w.empty();
+
+ System.out.println("Value is " + w.get(k));
+
+ }
+}
\ No newline at end of file
Added: benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/src/org/cachebench/cachewrappers/WhirlyCacheWrapper.java
===================================================================
--- benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/src/org/cachebench/cachewrappers/WhirlyCacheWrapper.java (rev 0)
+++ benchmarks/benchmark-fwk/trunk/cache-products/whirlycache-1.0.1/src/org/cachebench/cachewrappers/WhirlyCacheWrapper.java 2008-05-08 11:23:24 UTC (rev 5810)
@@ -0,0 +1,77 @@
+package org.cachebench.cachewrappers;
+
+import com.whirlycott.cache.Cache;
+import com.whirlycott.cache.CacheManager;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.cachebench.CacheWrapper;
+
+import java.util.Map;
+
+
+public class WhirlyCacheWrapper implements CacheWrapper
+{
+ private Cache cache;
+ private Log logger = LogFactory.getLog(WhirlyCacheWrapper.class);
+
+ /* (non-Javadoc)
+ * @see org.cachebench.CacheWrapper#init(java.util.Properties)
+ */
+ public void init(Map parameters) throws Exception
+ {
+ setUp();
+ }
+
+ /* (non-Javadoc)
+ * @see org.cachebench.CacheWrapper#setUp()
+ */
+ public void setUp() throws Exception
+ {
+ cache = CacheManager.getInstance().getCache();
+ logger.debug("Finish Initializing the cache");
+ }
+
+ /* (non-Javadoc)
+ * @see org.cachebench.CacheWrapper#tearDown()
+ */
+ public void tearDown() throws Exception
+ {
+ CacheManager.getInstance().destroy();
+ }
+
+ public void empty() throws Exception
+ {
+ cache.clear();
+ }
+
+ /* (non-Javadoc)
+ * @see org.cachebench.CacheWrapper#put(java.lang.Object, java.lang.Object)
+ */
+ public void put(Object key, Object value) throws Exception
+ {
+ cache.store(key, value);
+ }
+
+ /* (non-Javadoc)
+ * @see org.cachebench.CacheWrapper#get(java.lang.Object)
+ */
+ public Object get(Object key) throws Exception
+ {
+ return cache.retrieve(key);
+ }
+
+ public int getNumMembers()
+ {
+ return -1;
+ }
+
+ public String getInfo()
+ {
+ return cache.toString();
+ }
+
+ public Object getReplicatedData(String key) throws Exception
+ {
+ return get(key);
+ }
+}
\ No newline at end of file
16 years, 7 months
JBoss Cache SVN: r5809 - benchmarks/benchmark-fwk/trunk.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-05-08 07:22:33 -0400 (Thu, 08 May 2008)
New Revision: 5809
Removed:
benchmarks/benchmark-fwk/trunk/build/
Log:
Removed unnecessary build directory
16 years, 7 months
JBoss Cache SVN: r5808 - in core/trunk/src: main/java/org/jboss/cache/buddyreplication and 16 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-05-08 06:05:42 -0400 (Thu, 08 May 2008)
New Revision: 5808
Modified:
core/trunk/src/main/java/org/jboss/cache/CacheManagerImpl.java
core/trunk/src/main/java/org/jboss/cache/DataContainer.java
core/trunk/src/main/java/org/jboss/cache/InvocationContext.java
core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java
core/trunk/src/main/java/org/jboss/cache/RegionManager.java
core/trunk/src/main/java/org/jboss/cache/Version.java
core/trunk/src/main/java/org/jboss/cache/buddyreplication/BuddyManager.java
core/trunk/src/main/java/org/jboss/cache/commands/read/GravitateDataCommand.java
core/trunk/src/main/java/org/jboss/cache/commands/remote/ClusteredGetCommand.java
core/trunk/src/main/java/org/jboss/cache/config/XmlParsingConfigurationRegistry.java
core/trunk/src/main/java/org/jboss/cache/eviction/EvictionQueueList.java
core/trunk/src/main/java/org/jboss/cache/factories/XmlConfigurationParser.java
core/trunk/src/main/java/org/jboss/cache/interceptors/BaseTransactionalContextInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/CacheStoreInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/DataGravitatorInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/EvictionInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/InterceptorChain.java
core/trunk/src/main/java/org/jboss/cache/interceptors/InvalidationInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/OrderedSynchronizationHandler.java
core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java
core/trunk/src/main/java/org/jboss/cache/invocation/NodeInvocationDelegate.java
core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java
core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java
core/trunk/src/main/java/org/jboss/cache/loader/AbstractCacheLoader.java
core/trunk/src/main/java/org/jboss/cache/loader/AdjListJDBCCacheLoader.java
core/trunk/src/main/java/org/jboss/cache/loader/AdjListJDBCCacheLoaderConfig.java
core/trunk/src/main/java/org/jboss/cache/loader/CacheLoaderManager.java
core/trunk/src/main/java/org/jboss/cache/loader/ClusteredCacheLoader.java
core/trunk/src/main/java/org/jboss/cache/loader/FileCacheLoader.java
core/trunk/src/main/java/org/jboss/cache/loader/JDBCCacheLoaderOld.java
core/trunk/src/main/java/org/jboss/cache/loader/JDBCCacheLoaderOldConfig.java
core/trunk/src/main/java/org/jboss/cache/loader/SingletonStoreCacheLoader.java
core/trunk/src/main/java/org/jboss/cache/loader/bdbje/BdbjeCacheLoader.java
core/trunk/src/main/java/org/jboss/cache/loader/jdbm/JdbmCacheLoader.java
core/trunk/src/main/java/org/jboss/cache/marshall/AbstractMarshaller.java
core/trunk/src/main/java/org/jboss/cache/marshall/MarshalledValueHelper.java
core/trunk/src/main/java/org/jboss/cache/marshall/Marshaller.java
core/trunk/src/main/java/org/jboss/cache/marshall/MethodCall.java
core/trunk/src/main/java/org/jboss/cache/remoting/jgroups/ChannelMessageListener.java
core/trunk/src/main/java/org/jboss/cache/statetransfer/DefaultStateTransferIntegrator.java
core/trunk/src/main/java/org/jboss/cache/transaction/TransactionEntry.java
core/trunk/src/main/java/org/jboss/cache/transaction/TransactionTable.java
core/trunk/src/test/java/org/jboss/cache/invocation/InterceptorChainTest.java
Log:
Code cleanups based on IntelliJ inspections
Modified: core/trunk/src/main/java/org/jboss/cache/CacheManagerImpl.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/CacheManagerImpl.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/CacheManagerImpl.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -105,7 +105,7 @@
public Cache<Object, Object> getCache(String configName, boolean create) throws Exception
{
- Cache<Object, Object> cache = null;
+ Cache<Object, Object> cache;
synchronized (caches)
{
cache = caches.get(configName);
@@ -236,10 +236,10 @@
{
Integer count = checkouts.get(configName);
if (count == null)
- count = new Integer(0);
- Integer newVal = new Integer(count.intValue() + 1);
+ count = 0;
+ Integer newVal = count + 1;
checkouts.put(configName, newVal);
- return newVal.intValue();
+ return newVal;
}
}
@@ -248,12 +248,12 @@
synchronized (checkouts)
{
Integer count = checkouts.get(configName);
- if (count == null || count.intValue() < 1)
+ if (count == null || count < 1)
throw new IllegalStateException("invalid count of " + count + " for " + configName);
- Integer newVal = new Integer(count.intValue() - 1);
+ Integer newVal = count - 1;
checkouts.put(configName, newVal);
- return newVal.intValue();
+ return newVal;
}
}
Modified: core/trunk/src/main/java/org/jboss/cache/DataContainer.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/DataContainer.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/DataContainer.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -367,6 +367,7 @@
/**
* Returns a debug string with optional details of contents.
*/
+ @SuppressWarnings("deprecation")
public String toString(boolean details)
{
StringBuffer sb = new StringBuffer();
Modified: core/trunk/src/main/java/org/jboss/cache/InvocationContext.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/InvocationContext.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/InvocationContext.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -25,6 +25,7 @@
*
* @author <a href="mailto:manik@jboss.org">Manik Surtani (manik(a)jboss.org)</a>
*/
+@SuppressWarnings("deprecation")
public class InvocationContext implements Cloneable
{
private static final Log log = LogFactory.getLog(InvocationContext.class);
Modified: core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -227,6 +227,7 @@
return !configuration.isInactiveOnStartup() && !isUsingBuddyReplication && (configuration.isFetchInMemoryState() || loaderFetch);
}
+ @SuppressWarnings("deprecation")
private void initialiseChannelAndRpcDispatcher(boolean fetchState) throws CacheException
{
channel = configuration.getRuntimeConfig().getChannel();
Modified: core/trunk/src/main/java/org/jboss/cache/RegionManager.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/RegionManager.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/RegionManager.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -542,8 +542,8 @@
throw new CacheException("Region " + fqn + " is already being activated/deactivated");
}
- NodeSPI parent = null;
- NodeSPI subtreeRoot = null;
+ NodeSPI parent;
+ NodeSPI subtreeRoot;
boolean parentLocked = false;
boolean subtreeLocked = false;
NodeLock parentLock = null;
@@ -816,7 +816,7 @@
// JBAS-1288
// Try to establish a default region if there isn't one already
- boolean needDefault = true;
+ boolean needDefault;
List<EvictionRegionConfig> ercs = evictionConfig.getEvictionRegionConfigs();
// APPROACH 1: Scan for a default region, try to add if not there.
@@ -890,13 +890,15 @@
/**
* Returns a string containing debug information on every region.
+ *
+ * @return Regions as a string
*/
public String dumpRegions()
{
StringBuilder sb = new StringBuilder();
for (Region r : regionsRegistry.values())
{
- sb.append("\tRegion " + r);
+ sb.append("\tRegion ").append(r);
sb.append("\n");
}
return sb.toString();
Modified: core/trunk/src/main/java/org/jboss/cache/Version.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/Version.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/Version.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -134,10 +134,9 @@
public static short encodeVersion(int major, int minor, int patch)
{
- short version = (short) ((major << MAJOR_SHIFT)
+ return (short) ((major << MAJOR_SHIFT)
+ (minor << MINOR_SHIFT)
+ patch);
- return version;
}
public static String decodeVersion(short version)
@@ -145,8 +144,7 @@
int major = (version & MAJOR_MASK) >> MAJOR_SHIFT;
int minor = (version & MINOR_MASK) >> MINOR_SHIFT;
int patch = (version & PATCH_MASK);
- String versionString = major + "." + minor + "." + patch;
- return versionString;
+ return major + "." + minor + "." + patch;
}
public static boolean isBefore124(short version)
Modified: core/trunk/src/main/java/org/jboss/cache/buddyreplication/BuddyManager.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/buddyreplication/BuddyManager.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/buddyreplication/BuddyManager.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -758,6 +758,7 @@
log.trace("removeFromGroup notification complete");
}
+ @SuppressWarnings("deprecation")
private void addBuddies(List<Address> buddies) throws CacheException
{
if (log.isDebugEnabled())
@@ -869,8 +870,6 @@
for (int i = 0; i < timeouts.length; i++)
{
- timeoutException = null;
-
boolean force = (i == timeouts.length - 1);
try
Modified: core/trunk/src/main/java/org/jboss/cache/commands/read/GravitateDataCommand.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/commands/read/GravitateDataCommand.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/commands/read/GravitateDataCommand.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -100,9 +100,9 @@
Fqn backupRoot = Fqn.fromRelativeElements(BuddyManager.BUDDY_BACKUP_SUBTREE_FQN, childName);
if (BuddyFqnTransformer.isDeadBackupRoot(backupRoot))
{
- //actualNode = searchDeadRoot(backupRoot, fqn);
+ @SuppressWarnings("unchecked")
Set<Integer> deadChildNames = new TreeSet<Integer>(spi.getChildrenNames(backupRoot));
- Integer[] elems = deadChildNames.toArray(new Integer[]{});
+ Integer[] elems = deadChildNames.toArray(new Integer[deadChildNames.size()]);
// these are integers. we need to start with the highest/most recent.
for (int i = elems.length - 1; i > -1; i--)
Modified: core/trunk/src/main/java/org/jboss/cache/commands/remote/ClusteredGetCommand.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/commands/remote/ClusteredGetCommand.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/commands/remote/ClusteredGetCommand.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -29,7 +29,7 @@
public static final int METHOD_ID = 22;
private DataCommand dataCommand;
- private Boolean searchBackupSubtrees;
+ private boolean searchBackupSubtrees;
private DataContainer dataContainer;
private InterceptorChain interceptorChain;
@@ -85,7 +85,8 @@
{
results.add(true);
results.add(callResults);
- } else
+ }
+ else
{
results.add(false);
results.add(null);
@@ -153,10 +154,7 @@
if (dataCommand != null ? !dataCommand.equals(that.dataCommand) : that.dataCommand != null)
return false;
- if (searchBackupSubtrees != null ? !searchBackupSubtrees.equals(that.searchBackupSubtrees) : that.searchBackupSubtrees != null)
- return false;
-
- return true;
+ return searchBackupSubtrees == that.searchBackupSubtrees;
}
@Override
@@ -164,7 +162,7 @@
{
int result;
result = (dataCommand != null ? dataCommand.hashCode() : 0);
- result = 31 * result + (searchBackupSubtrees != null ? searchBackupSubtrees.hashCode() : 0);
+ result = 31 * result + (searchBackupSubtrees ? 1 : 0);
return result;
}
Modified: core/trunk/src/main/java/org/jboss/cache/config/XmlParsingConfigurationRegistry.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/config/XmlParsingConfigurationRegistry.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/config/XmlParsingConfigurationRegistry.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -88,7 +88,7 @@
public Configuration getConfiguration(String configName)
{
- Configuration config = null;
+ Configuration config;
synchronized (configs)
{
config = configs.get(configName);
Modified: core/trunk/src/main/java/org/jboss/cache/eviction/EvictionQueueList.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/eviction/EvictionQueueList.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/eviction/EvictionQueueList.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -290,8 +290,7 @@
public void set(Object o)
{
this.doConcurrentModCheck();
- NodeEntry e = (NodeEntry) o;
- cursor.node = e;
+ cursor.node = (NodeEntry) o;
}
public void add(Object o)
Modified: core/trunk/src/main/java/org/jboss/cache/factories/XmlConfigurationParser.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/XmlConfigurationParser.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/factories/XmlConfigurationParser.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -212,7 +212,7 @@
if (list.getLength() > 1) throw new ConfigurationException("Has multiple " + XmlHelper.ROOT + " tag");
Node node = list.item(0);
- Element element = null;
+ Element element;
if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE)
{
element = (Element) node;
@@ -440,7 +440,7 @@
Element singletonStoreElement = (Element) singletonStoreNode;
boolean singletonStoreEnabled = XmlHelper.readBooleanContents(singletonStoreElement, "enabled");
String singletonStoreClass = XmlHelper.readStringContents(singletonStoreElement, "class");
- Properties singletonStoreproperties = null;
+ Properties singletonStoreproperties;
try
{
singletonStoreproperties = XmlHelper.readPropertiesContents(singletonStoreElement, "properties");
@@ -567,7 +567,7 @@
}
}
- EvictionPolicy policy = null;
+ EvictionPolicy policy;
try
{
policy = (EvictionPolicy) Util.loadClass(evictionClass).newInstance();
@@ -581,7 +581,7 @@
throw new RuntimeException("Eviction class is not properly loaded in classloader", e);
}
- EvictionPolicyConfig epc = null;
+ EvictionPolicyConfig epc;
try
{
epc = policy.getEvictionConfigurationClass().newInstance();
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/BaseTransactionalContextInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/BaseTransactionalContextInterceptor.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/BaseTransactionalContextInterceptor.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -60,7 +60,7 @@
protected boolean isRollingBack(Transaction tx)
{
if (tx == null) return false;
- int status = -1;
+ int status;
try
{
status = tx.getStatus();
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/CacheStoreInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/CacheStoreInterceptor.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/CacheStoreInterceptor.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -279,7 +279,6 @@
@Override
public Object handlePutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
{
- Object result;
Object returnValue = invokeNextInterceptor(ctx, command);
if (inTransaction())
{
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/DataGravitatorInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/DataGravitatorInterceptor.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/DataGravitatorInterceptor.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -301,6 +301,7 @@
replicateCall(null, cleanupCommand, false, false, false, true, -1);
}
+ @SuppressWarnings("deprecation")
private GravitateResult gravitateData(Fqn fqn) throws Exception
{
if (trace) log.trace("Requesting data gravitation for Fqn " + fqn);
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/EvictionInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/EvictionInterceptor.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/EvictionInterceptor.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -136,7 +136,7 @@
else
{
Fqn fqn = command.getFqn();
- Region r = null;
+ Region r;
if (fqn != null && command.getKey() != null && (r = getRegion(fqn, NodeEventType.REMOVE_ELEMENT_EVENT)) != null)
{
registerEvictionEventToRegionManager(new EvictedEventNode(fqn, NodeEventType.REMOVE_ELEMENT_EVENT, 1), r);
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/InterceptorChain.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/InterceptorChain.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/InterceptorChain.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -11,7 +11,6 @@
import org.jboss.cache.invocation.InvocationContextContainer;
import org.jboss.cache.util.CachePrinter;
-import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
@@ -132,13 +131,10 @@
* Returns an unmofiable list with all the interceptors in sequence.
* If first in chain is null an empty list is returned.
*/
- public List<CommandInterceptor> getInterceptorsAsList()
+ public List<CommandInterceptor> asList()
{
- List<CommandInterceptor> result;
- if (firstInChain == null)
- {
- result = Collections.EMPTY_LIST;
- }
+ if (firstInChain == null) return Collections.emptyList();
+
List<CommandInterceptor> retval = new LinkedList<CommandInterceptor>();
CommandInterceptor tmp = firstInChain;
do
@@ -147,8 +143,7 @@
tmp = tmp.getNext();
}
while (tmp != null);
- result = Collections.unmodifiableList(retval);
- return result;
+ return Collections.unmodifiableList(retval);
}
@@ -196,35 +191,6 @@
}
/**
- * Returns the chain as a list.
- */
- public List<CommandInterceptor> asList()
- {
- List<CommandInterceptor> result;
- if (this.firstInChain == null)
- {
- result = null;
- }
- int num = 1;
- CommandInterceptor tmp = this.firstInChain;
- while ((tmp = tmp.getNext()) != null)
- {
- num++;
- }
- List<CommandInterceptor> retval = new ArrayList<CommandInterceptor>(num);
- tmp = this.firstInChain;
- num = 0;
- do
- {
- retval.add(tmp);
- tmp = tmp.getNext();
- }
- while (tmp != null);
- result = retval;
- return result;
- }
-
- /**
* Appends at the end.
*/
public void appendIntereceptor(CommandInterceptor ci)
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/InvalidationInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/InvalidationInterceptor.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/InvalidationInterceptor.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -80,13 +80,7 @@
private boolean skipInvalidation(InvocationContext ctx)
{
Option optionOverride = ctx.getOptionOverrides();
- if (optionOverride != null && optionOverride.isCacheModeLocal() && (ctx.getTransaction() == null))
- {
- // skip replication!!
- return true;
- }
- if (trace) log.trace("(" + rpcManager.getLocalAddress() + ") Command " + ctx.getCommand());
- return false;
+ return optionOverride != null && optionOverride.isCacheModeLocal() && (ctx.getTransaction() == null);
}
@Override
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/OrderedSynchronizationHandler.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/OrderedSynchronizationHandler.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/OrderedSynchronizationHandler.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -84,9 +84,7 @@
@Override
public String toString()
{
- StringBuffer sb = new StringBuffer();
- sb.append("tx=" + getTxAsString() + ", handlers=" + handlers);
- return sb.toString();
+ return "tx=" + getTxAsString() + ", handlers=" + handlers;
}
private String getTxAsString()
Modified: core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -126,7 +126,7 @@
public List<CommandInterceptor> getInterceptorChain()
{
- return invoker.getInterceptorsAsList();
+ return invoker.asList();
}
public void removeInterceptor(int position)
Modified: core/trunk/src/main/java/org/jboss/cache/invocation/NodeInvocationDelegate.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/invocation/NodeInvocationDelegate.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/invocation/NodeInvocationDelegate.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -278,7 +278,7 @@
// TODO: Revisit. Is this really threadsafe? See comment in putIfAbsent() - same solution should be applied here too.
assertValid();
Fqn nf = Fqn.fromRelativeFqn(getFqn(), f);
- Option o1 = null;
+ Option o1;
try
{
o1 = spi.getInvocationContext().getOptionOverrides().clone();
@@ -292,7 +292,7 @@
if (child == null)
{
- Option o2 = null;
+ Option o2;
try
{
o2 = o1.clone();
Modified: core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -348,6 +348,7 @@
}
@Deprecated
+ @SuppressWarnings("deprecation")
public boolean getUseRegionBasedMarshalling()
{
return getConfiguration().isUseRegionBasedMarshalling();
@@ -537,6 +538,8 @@
getConfiguration().setTransactionManagerLookupClass(cl);
}
+ @Deprecated
+ @SuppressWarnings("deprecation")
public void setUseRegionBasedMarshalling(boolean isTrue)
{
getConfiguration().setUseRegionBasedMarshalling(isTrue);
Modified: core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -122,7 +122,7 @@
public static String getDefaultCacheObjectName(Configuration config, String cacheImplClass)
{
// get the cache's registration name
- String tmpName = null;
+ String tmpName;
if (config.getClusterName() == null)
{
tmpName = NO_CLUSTER_PREFIX + getUniqueId(cacheImplClass);
Modified: core/trunk/src/main/java/org/jboss/cache/loader/AbstractCacheLoader.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/loader/AbstractCacheLoader.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/loader/AbstractCacheLoader.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -87,7 +87,7 @@
boolean moveToBuddy = subtree.isChildOf(BuddyManager.BUDDY_BACKUP_SUBTREE_FQN) && subtree.size() > 1;
// store new state
- Fqn fqn = null;
+ Fqn fqn;
//NodeData nd = null;
Object objectFromStream = cache.getMarshaller().objectFromObjectStream(in);
if (objectFromStream instanceof NodeDataMarker)
Modified: core/trunk/src/main/java/org/jboss/cache/loader/AdjListJDBCCacheLoader.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/loader/AdjListJDBCCacheLoader.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/loader/AdjListJDBCCacheLoader.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -371,13 +371,8 @@
{
try
{
- // ObjectInputStream ois = null;
- // ois = new ObjectInputStream(is);
- // Object marshalledNode = ois.readObject();
-
// deserialize result
- Map<Object, Object> oldNode = (Map<Object, Object>) unmarshall(is);
- return oldNode;
+ return (Map<Object, Object>) unmarshall(is);
}
catch (Exception e)
{
Modified: core/trunk/src/main/java/org/jboss/cache/loader/AdjListJDBCCacheLoaderConfig.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/loader/AdjListJDBCCacheLoaderConfig.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/loader/AdjListJDBCCacheLoaderConfig.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -11,6 +11,7 @@
* @author <a href="mailto:manik@jboss.org">Manik Surtani (manik(a)jboss.org)</a>
* @author <a href="mailto:galder.zamarreno@jboss.com">Galder Zamarreno</a>
*/
+@SuppressWarnings("deprecation")
public class AdjListJDBCCacheLoaderConfig extends IndividualCacheLoaderConfig
{
/**
Modified: core/trunk/src/main/java/org/jboss/cache/loader/CacheLoaderManager.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/loader/CacheLoaderManager.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/loader/CacheLoaderManager.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -132,7 +132,7 @@
*/
private CacheLoader createCacheLoader() throws Exception
{
- CacheLoader tmpLoader = null;
+ CacheLoader tmpLoader;
// if we only have a single cache loader configured in the chaining cacheloader then
// don't use a chaining cache loader at all.
@@ -199,6 +199,7 @@
* @return a cache loader
* @throws Exception
*/
+ @SuppressWarnings("deprecation")
private CacheLoader createCacheLoader(CacheLoaderConfig.IndividualCacheLoaderConfig cfg, CacheSPI cache) throws Exception
{
// create loader
@@ -339,7 +340,7 @@
if (preloadChildren)
{
// 3. Then recursively for all child nodes, preload them as well
- Set children = null;
+ Set children;
try
{
children = loader.getChildrenNames(fqn);
Modified: core/trunk/src/main/java/org/jboss/cache/loader/ClusteredCacheLoader.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/loader/ClusteredCacheLoader.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/loader/ClusteredCacheLoader.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -109,6 +109,7 @@
}
}
+ @SuppressWarnings("deprecation")
private Object callRemote(DataCommand dataCommand) throws Exception
{
if (trace) log.trace("cache=" + cache.getLocalAddress() + "; calling with " + dataCommand);
Modified: core/trunk/src/main/java/org/jboss/cache/loader/FileCacheLoader.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/loader/FileCacheLoader.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/loader/FileCacheLoader.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -421,7 +421,7 @@
if (!child.exists()) return new HashMap(0); // no node attribs exist hence the empty HashMap.
//if(!child.exists()) return null;
- Map m = null;
+ Map m;
try
{
//m = (Map) unmarshall(child);
Modified: core/trunk/src/main/java/org/jboss/cache/loader/JDBCCacheLoaderOld.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/loader/JDBCCacheLoaderOld.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/loader/JDBCCacheLoaderOld.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -65,6 +65,7 @@
* @deprecated please use the {@link org.jboss.cache.loader.JDBCCacheLoader}.
*/
@Deprecated
+@SuppressWarnings("deprecation")
public class JDBCCacheLoaderOld extends AdjListJDBCCacheLoader
{
private static final Log log = LogFactory.getLog(JDBCCacheLoaderOld.class);
Modified: core/trunk/src/main/java/org/jboss/cache/loader/JDBCCacheLoaderOldConfig.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/loader/JDBCCacheLoaderOldConfig.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/loader/JDBCCacheLoaderOldConfig.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -9,6 +9,7 @@
* @deprecated please use JDBCCacheLoaderConfig
*/
@Deprecated
+@SuppressWarnings("deprecation")
public class JDBCCacheLoaderOldConfig extends AdjListJDBCCacheLoaderConfig
{
/**
Modified: core/trunk/src/main/java/org/jboss/cache/loader/SingletonStoreCacheLoader.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/loader/SingletonStoreCacheLoader.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/loader/SingletonStoreCacheLoader.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -210,15 +210,8 @@
final boolean debugEnabled = log.isDebugEnabled();
if (debugEnabled) log.debug("start pushing in-memory state to cache cacheLoader");
- try
- {
- pushState(cache.getRoot());
- if (debugEnabled) log.debug("in-memory state passed to cache cacheLoader successfully");
- }
- catch (Exception e)
- {
- throw e;
- }
+ pushState(cache.getRoot());
+ if (debugEnabled) log.debug("in-memory state passed to cache cacheLoader successfully");
return null;
}
@@ -334,10 +327,6 @@
{
throw new Exception("task timed out", e);
}
- catch (ExecutionException e)
- {
- throw e;
- }
catch (InterruptedException e)
{
/* Re-assert the thread's interrupted status */
Modified: core/trunk/src/main/java/org/jboss/cache/loader/bdbje/BdbjeCacheLoader.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/loader/bdbje/BdbjeCacheLoader.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/loader/bdbje/BdbjeCacheLoader.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -1085,7 +1085,7 @@
private Map<Object, Object> makeDataObject(DatabaseEntry entry)
{
Map<Object, Object> map = (Map<Object, Object>) serialBinding.entryToObject(entry);
- if (true && map == null)
+ if (map == null)
{
map = new HashMap<Object, Object>();
}
Modified: core/trunk/src/main/java/org/jboss/cache/loader/jdbm/JdbmCacheLoader.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/loader/jdbm/JdbmCacheLoader.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/loader/jdbm/JdbmCacheLoader.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -67,7 +67,6 @@
private static final String NAME = "JdbmCacheLoader";
private JdbmCacheLoaderConfig config;
- private String cacheDbName;
private RecordManager recman;
private BTree tree;
@@ -118,6 +117,7 @@
/* Parse config string. */
File homeDir;
int offset = locationStr.indexOf('#');
+ String cacheDbName;
if (offset >= 0 && offset < locationStr.length() - 1)
{
homeDir = new File(locationStr.substring(0, offset));
Modified: core/trunk/src/main/java/org/jboss/cache/marshall/AbstractMarshaller.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/marshall/AbstractMarshaller.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/marshall/AbstractMarshaller.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -75,6 +75,7 @@
}
@Start
+ @SuppressWarnings("deprecation")
protected void init()
{
this.useRegionBasedMarshalling = configuration.isUseRegionBasedMarshalling();
@@ -204,8 +205,6 @@
// Strip out the buddy group portion
fqn = BuddyFqnTransformer.getActualFqn(fqn);
}
- Region r = regionManager.getRegion(fqn, Region.Type.MARSHALLING, false);
- return r;
- //return r != null && r.isActive() ? r : null;
+ return regionManager.getRegion(fqn, Region.Type.MARSHALLING, false);
}
}
Modified: core/trunk/src/main/java/org/jboss/cache/marshall/MarshalledValueHelper.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/marshall/MarshalledValueHelper.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/marshall/MarshalledValueHelper.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -1,6 +1,7 @@
package org.jboss.cache.marshall;
import org.jboss.cache.Fqn;
+import org.jboss.cache.commands.ReplicableCommand;
import org.jboss.cache.transaction.GlobalTransaction;
import org.jgroups.Address;
@@ -28,6 +29,6 @@
type.equals(Byte.class) || type.equals(Short.class) || type.equals(Integer.class) ||
type.equals(Long.class) || type.equals(Float.class) || type.equals(Double.class) ||
(type.isArray() && isTypeExcluded(type.getComponentType())) || type.equals(Fqn.class) || type.equals(GlobalTransaction.class) || type.equals(Address.class) ||
- type.equals(MethodCall.class) || type.equals(MarshalledValue.class);
+ ReplicableCommand.class.isAssignableFrom(type) || type.equals(MarshalledValue.class);
}
}
Modified: core/trunk/src/main/java/org/jboss/cache/marshall/Marshaller.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/marshall/Marshaller.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/marshall/Marshaller.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -13,7 +13,7 @@
* The reason why this is implemented specially in JBoss Cache rather than resorting to
* Java serialization or even the more efficient JBoss serialization is that a lot of efficiency
* can be gained when a majority of the serialization that occurs has to do with a small set
- * of known types such as {@link org.jboss.cache.Fqn} or {@link MethodCall}, and class type information
+ * of known types such as {@link org.jboss.cache.Fqn} or {@link org.jboss.cache.commands.ReplicableCommand}, and class type information
* can be replaced with simple magic numbers.
* <p/>
* Unknown types (typically user data) falls back to JBoss serialization.
@@ -23,7 +23,7 @@
* information to allow streams to interoperate between different versions of JBoss Cache (see {@link VersionAwareMarshaller}
* <p/>
* This interface implements the JGroups building-block interface {@link org.jgroups.blocks.RpcDispatcher.Marshaller} which
- * is used to marshall {@link MethodCall}s, their parameters and their response values.
+ * is used to marshall {@link org.jboss.cache.commands.ReplicableCommand}s, their parameters and their response values.
* <p/>
* The interface is also used by the {@link org.jboss.cache.loader.CacheLoader} framework to efficiently serialize data to be persisted, as well as
* the {@link org.jboss.cache.statetransfer.StateTransferManager} when serializing the cache for transferring state en-masse.
Modified: core/trunk/src/main/java/org/jboss/cache/marshall/MethodCall.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/marshall/MethodCall.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/marshall/MethodCall.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -6,7 +6,6 @@
*/
package org.jboss.cache.marshall;
-import org.apache.commons.logging.LogFactory;
import org.jboss.cache.commands.tx.OptimisticPrepareCommand;
import org.jboss.cache.commands.tx.PrepareCommand;
@@ -31,7 +30,6 @@
@Deprecated
public class MethodCall extends org.jgroups.blocks.MethodCall
{
- private static boolean trace = LogFactory.getLog(MethodCall.class).isTraceEnabled();
/**
* It's unclear why this class would be serialized.
*/
@@ -99,7 +97,7 @@
ret.append("; Args: (");
if (args != null && args.length > 0)
{
- if (trace)
+ if (log.isTraceEnabled())
{
boolean first = true;
for (Object arg : args)
Modified: core/trunk/src/main/java/org/jboss/cache/remoting/jgroups/ChannelMessageListener.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/remoting/jgroups/ChannelMessageListener.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/remoting/jgroups/ChannelMessageListener.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -130,7 +130,7 @@
public byte[] getState()
{
MarshalledValueOutputStream out = null;
- byte[] result = null;
+ byte[] result;
ExposedByteArrayOutputStream baos = new ExposedByteArrayOutputStream(16 * 1024);
try
{
@@ -184,7 +184,7 @@
{
MarshalledValueOutputStream out = null;
String sourceRoot = state_id;
- byte[] result = null;
+ byte[] result;
boolean hasDifferentSourceAndIntegrationRoots = state_id.indexOf(StateTransferManager.PARTIAL_STATE_DELIMITER) > 0;
if (hasDifferentSourceAndIntegrationRoots)
Modified: core/trunk/src/main/java/org/jboss/cache/statetransfer/DefaultStateTransferIntegrator.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/statetransfer/DefaultStateTransferIntegrator.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/statetransfer/DefaultStateTransferIntegrator.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -278,27 +278,15 @@
}
}
+ @SuppressWarnings("unchecked")
private List<NodeData> readNodesAsList(ObjectInputStream in) throws Exception
{
Object obj = cache.getMarshaller().objectFromObjectStream(in);
if (obj instanceof NodeDataMarker) return null;
- List list = (List) obj;
- return list;
+ return (List<NodeData>) obj;
}
-// private NodeData readNode(ObjectInputStream in) throws IOException, ClassNotFoundException
-// {
-// NodeData nd = (NodeData) in.readObject();
-// if (nd != null && nd.isExceptionMarker())
-// {
-// NodeDataExceptionMarker ndem = (NodeDataExceptionMarker) nd;
-// throw new CacheException("State provider node " + ndem.getCacheNodeIdentity()
-// + " threw exception during loadState", ndem.getCause());
-// }
-// return nd;
-// }
-
private NodeData integrateStateTransferChildren(NodeSPI parent, int offset, Iterator<NodeData> nodeDataIterator)
throws IOException, ClassNotFoundException
{
Modified: core/trunk/src/main/java/org/jboss/cache/transaction/TransactionEntry.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/transaction/TransactionEntry.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/transaction/TransactionEntry.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -17,7 +17,6 @@
import org.jboss.cache.interceptors.OrderedSynchronizationHandler;
import org.jboss.cache.lock.IdentityLock;
import org.jboss.cache.lock.NodeLock;
-import org.jboss.cache.marshall.MethodCall;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
@@ -65,7 +64,7 @@
private boolean forceSyncReplication = false;
/**
- * List<MethodCall> of modifications ({@link MethodCall}). They will be replicated on TX commit
+ * List<ReversibleCommand> of modifications ({@link ReversibleCommand}). They will be replicated on TX commit
*/
private final List<ReversibleCommand> modificationList = new LinkedList<ReversibleCommand>();
Modified: core/trunk/src/main/java/org/jboss/cache/transaction/TransactionTable.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/transaction/TransactionTable.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/main/java/org/jboss/cache/transaction/TransactionTable.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -272,7 +272,7 @@
if (entry != null)
entry.releaseAllLocksLIFO(gtx);
else
- log.error("No transaction entry present!!", new Throwable());
+ log.error("No transaction entry present!!");
}
@@ -411,7 +411,7 @@
public static boolean isActive(Transaction tx)
{
if (tx == null) return false;
- int status = -1;
+ int status;
try
{
status = tx.getStatus();
@@ -429,7 +429,7 @@
public static boolean isPreparing(Transaction tx)
{
if (tx == null) return false;
- int status = -1;
+ int status;
try
{
status = tx.getStatus();
Modified: core/trunk/src/test/java/org/jboss/cache/invocation/InterceptorChainTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/invocation/InterceptorChainTest.java 2008-05-08 09:16:18 UTC (rev 5807)
+++ core/trunk/src/test/java/org/jboss/cache/invocation/InterceptorChainTest.java 2008-05-08 10:05:42 UTC (rev 5808)
@@ -53,7 +53,7 @@
expectedList.add(pessimisticInterceptor);
expectedList.add(callInterceptor);
- assert chain.getInterceptorsAsList().equals(expectedList);
+ assert chain.asList().equals(expectedList);
}
public void testAddAtPosition() throws Throwable
16 years, 7 months
JBoss Cache SVN: r5807 - core/trunk/src/test/java/org/jboss/cache.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-05-08 05:16:18 -0400 (Thu, 08 May 2008)
New Revision: 5807
Removed:
core/trunk/src/test/java/org/jboss/cache/LifeCycleTest.java
Log:
Deleted: core/trunk/src/test/java/org/jboss/cache/LifeCycleTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/LifeCycleTest.java 2008-05-08 09:07:31 UTC (rev 5806)
+++ core/trunk/src/test/java/org/jboss/cache/LifeCycleTest.java 2008-05-08 09:16:18 UTC (rev 5807)
@@ -1,473 +0,0 @@
-package org.jboss.cache;
-
-import org.jboss.cache.config.Configuration;
-import org.jboss.cache.misc.TestingUtil;
-import org.jboss.cache.notifications.annotation.CacheListener;
-import org.jboss.cache.notifications.annotation.CacheStarted;
-import org.jboss.cache.notifications.annotation.CacheStopped;
-import org.jboss.cache.notifications.event.Event;
-import static org.testng.AssertJUnit.*;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.Test;
-
-import javax.transaction.NotSupportedException;
-import javax.transaction.RollbackException;
-import javax.transaction.SystemException;
-import javax.transaction.TransactionManager;
-import java.util.Arrays;
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * Tests restart (stop-destroy-create-start) of CacheSPI
- *
- * @author Bela Ban
- * @version $Id$
- */
-@Test(groups = {"functional"})
-public class LifeCycleTest
-{
- private CacheSPI[] c;
-
- @AfterMethod
- public void tearDown()
- {
- TestingUtil.killCaches(c);
- c = null;
- }
-
- private void createAndRegisterCache(Configuration.CacheMode mode, boolean start) throws Exception
- {
- Cache cache = createCache(mode);
- List<Cache> caches = new LinkedList<Cache>();
- if (c != null) caches.addAll(Arrays.asList(c));
- caches.add(cache);
- c = caches.toArray(new CacheSPI[]{});
- if (start)
- {
- cache.start();
- if (c.length > 1) TestingUtil.blockUntilViewsReceived(c, 10000);
- }
- }
-
-
- public void testLocalRestartNoTransactions() throws Exception
- {
- createAndRegisterCache(Configuration.CacheMode.LOCAL, true);
-
- c[0].put("/a/b/c", null);
- assertTrue(c[0].getNumberOfNodes() > 0);
- assertEquals(0, c[0].getNumberOfLocksHeld());
-
- restartCache(c[0]);
-
- assertEquals(0, c[0].getNumberOfNodes());
- assertEquals(0, c[0].getNumberOfLocksHeld());
- }
-
- public void testLocalRestartWithTransactions() throws Exception
- {
- createAndRegisterCache(Configuration.CacheMode.LOCAL, true);
-
- TransactionManager tm = beginTransaction();
-
- c[0].put("/a/b/c", null);
- assertTrue(c[0].getNumberOfNodes() > 0);
- assertEquals(4, c[0].getNumberOfLocksHeld());
-
- restartCache(c[0]);
-
- //assertEquals(4, cache.getNumberOfLocksHeld());
- assertEquals(0, c[0].getNumberOfNodes());
-
- tm.rollback();
- assertEquals(0, c[0].getNumberOfLocksHeld());
- }
-
- public void testStartNoCreate() throws Exception
- {
- createAndRegisterCache(Configuration.CacheMode.LOCAL, false);
- c[0].start();
-
- c[0].put("/a/b/c", null);
- assertTrue(c[0].getNumberOfNodes() > 0);
- assertEquals(0, c[0].getNumberOfLocksHeld());
-
- restartCache(c[0]);
-
- assertEquals(0, c[0].getNumberOfNodes());
- assertEquals(0, c[0].getNumberOfLocksHeld());
- }
-
- public void testReStartNoCreate() throws Exception
- {
- createAndRegisterCache(Configuration.CacheMode.LOCAL, false);
- c[0].start();
- c[0].stop();
- c[0].start();
-
- c[0].put("/a/b/c", null);
- assertTrue(c[0].getNumberOfNodes() > 0);
- assertEquals(0, c[0].getNumberOfLocksHeld());
-
- restartCache(c[0]);
-
- assertEquals(0, c[0].getNumberOfNodes());
- assertEquals(0, c[0].getNumberOfLocksHeld());
- }
-
- public void testDuplicateInvocation() throws Exception
- {
- createAndRegisterCache(Configuration.CacheMode.LOCAL, false);
- c[0].create();
- c[0].start();
- c[0].create();
- c[0].start();
-
- c[0].put("/a/b/c", null);
- assertTrue(c[0].getNumberOfNodes() > 0);
- assertEquals(0, c[0].getNumberOfLocksHeld());
-
- restartCache(c[0]);
-
- assertEquals(0, c[0].getNumberOfNodes());
- assertEquals(0, c[0].getNumberOfLocksHeld());
-
- c[0].stop();
- c[0].destroy();
- c[0].stop();
- c[0].destroy();
- }
-
- public void testFailedStart() throws Exception
- {
-
- createAndRegisterCache(Configuration.CacheMode.LOCAL, false);
- assertEquals("Correct state", CacheStatus.INSTANTIATED, c[0].getCacheStatus());
-
- DisruptLifecycleListener listener = new DisruptLifecycleListener();
- c[0].addCacheListener(listener);
-
- c[0].create();
-
- listener.disrupt = true;
-
- assertEquals("Correct state", CacheStatus.CREATED, c[0].getCacheStatus());
- try
- {
- c[0].start();
- fail("Listener did not prevent start");
- }
- catch (CacheException good)
- {
- }
-
- assertEquals("Correct state", CacheStatus.FAILED, c[0].getCacheStatus());
-
- c[0].addCacheListener(listener);
- listener.disrupt = false;
-
- c[0].start();
-
- assertEquals("Correct state", CacheStatus.STARTED, c[0].getCacheStatus());
-
- c[0].put("/a/b/c", null);
- assertTrue(c[0].getNumberOfNodes() > 0);
- assertEquals(0, c[0].getNumberOfLocksHeld());
-
- listener.disrupt = true;
- c[0].addCacheListener(listener);
-
- try
- {
- c[0].stop();
- fail("Listener did not prevent stop");
- }
- catch (CacheException good)
- {
- }
-
- assertEquals("Correct state", CacheStatus.FAILED, c[0].getCacheStatus());
-
- listener.disrupt = false;
-
- c[0].stop();
- assertEquals("Correct state", CacheStatus.STOPPED, c[0].getCacheStatus());
- c[0].destroy();
- assertEquals("Correct state", CacheStatus.DESTROYED, c[0].getCacheStatus());
- }
-
- public void testInvalidStateInvocations() throws Exception
- {
- createAndRegisterCache(Configuration.CacheMode.LOCAL, false);
- try
- {
- c[0].get(Fqn.ROOT, "k");
- fail("Cache isn't ready!");
- }
- catch (IllegalStateException good)
- {
- }
-
- c[0].create();
- try
- {
- c[0].get(Fqn.ROOT, "k");
- fail("Cache isn't ready!");
- }
- catch (IllegalStateException good)
- {
- }
-
- c[0].start();
- c[0].get(Fqn.ROOT, "k"); // should work
-
- c[0].stop();
-
- try
- {
- c[0].get(Fqn.ROOT, "k");
- fail("Cache isn't ready!");
- }
- catch (IllegalStateException good)
- {
- }
-
- c[0].destroy();
- try
- {
- c[0].get(Fqn.ROOT, "k");
- fail("Cache isn't ready!");
- }
- catch (IllegalStateException good)
- {
- }
- }
-
- public void testRemoteInvalidStateInvocations() throws Exception
- {
- createAndRegisterCache(Configuration.CacheMode.REPL_SYNC, true);
- createAndRegisterCache(Configuration.CacheMode.REPL_SYNC, true);
- try
- {
- // now DIRECTLY change the status of c2.
- // emulate the race condition where the remote cache is stopping but hasn't disconnected from the channel.
- LifecycleManager ci1 = (LifecycleManager) TestingUtil.extractField(c[1], "lifecycleManager");
- ci1.setCacheStatus(CacheStatus.STOPPING);
-
- // Thanks to JBCACHE-1179, this should only log a warning and not throw an exception
- c[0].put(Fqn.ROOT, "k", "v");
- }
- finally
- {
- // reset c[1] to running so the tearDown method can clean it up
- LifecycleManager ci1 = (LifecycleManager) TestingUtil.extractField(c[1], "lifecycleManager");
- ci1.setCacheStatus(CacheStatus.STARTED);
- }
- }
-
- public void testRemoteInvalidStateInvocations2() throws Exception
- {
- createAndRegisterCache(Configuration.CacheMode.REPL_SYNC, true);
- createAndRegisterCache(Configuration.CacheMode.REPL_SYNC, true);
- TestingUtil.blockUntilViewsReceived(c, 10000);
- try
- {
- // now DIRECTLY change the status of c2.
- // emulate the race condition where the remote cache is stopping but hasn't disconnected from the channel.
-
- // there is a lousy race condition here - we need to make sure cache[1]'s start() method doesn't set status to STARTED
- // after we attempt to change this.
- TestingUtil.blockUntilCacheStatusAchieved(c[1], CacheStatus.STARTED, 1000);
- LifecycleManager ci1 = (LifecycleManager) TestingUtil.extractField(c[1], "lifecycleManager");
- ci1.setCacheStatus(CacheStatus.STARTING);
- try
- {
- // This call should wait for up to StateRetrievalTimeout secs or until c[1] has entered the STARTED state, and then barf.
- c[0].put(Fqn.ROOT, "k", "v");
- fail("Should barf!");
- }
- catch (Exception good)
- {
-
- }
-
- // now kick off another thread to sleep for a few secs and then set c[1] to STARTED
- final int sleepTime = 500;
- new Thread()
- {
- public void run()
- {
- TestingUtil.sleepThread(sleepTime);
- LifecycleManager ci1 = (LifecycleManager) TestingUtil.extractField(c[1], "lifecycleManager");
- ci1.setCacheStatus(CacheStatus.STARTED);
- }
- }.start();
-
- // should succeed but should take at least 1000ms.
- long startTime = System.currentTimeMillis();
- c[0].put(Fqn.ROOT, "k", "v");
- assert System.currentTimeMillis() > (startTime + sleepTime) : "Should wait till c[1] has STARTED state";
-
- }
- finally
- {
- // reset c[1] to running so the tearDown method can clean it up
- LifecycleManager ci1 = (LifecycleManager) TestingUtil.extractField(c[1], "lifecycleManager");
- ci1.setCacheStatus(CacheStatus.STARTED);
- }
- }
-
- public void testInvalidStateTxCommit() throws Exception
- {
- createAndRegisterCache(Configuration.CacheMode.LOCAL, true);
- c[0].getTransactionManager().begin();
- c[0].put(Fqn.ROOT, "k1", "v1");
- c[0].put(Fqn.ROOT, "k2", "v2");
-
- // now DIRECTLY change the status of c.
- LifecycleManager ci0 = (LifecycleManager) TestingUtil.extractField(c[0], "lifecycleManager");
- ci0.setCacheStatus(CacheStatus.STOPPING);
-
- try
- {
- c[0].getTransactionManager().commit();
- fail("Cache isn't STARTED!");
- }
- catch (RollbackException good)
- {
- }
- }
-
- @SuppressWarnings("unchecked")
- public void testStopInstanceWhileOtherInstanceSends() throws Exception
- {
- final Fqn fqn = Fqn.fromString("/a");
- final List<Boolean> running = new LinkedList<Boolean>();
- final List<Exception> exceptions = new LinkedList<Exception>();
- running.add(true);
-
- createAndRegisterCache(Configuration.CacheMode.REPL_SYNC, true);
- createAndRegisterCache(Configuration.CacheMode.REPL_SYNC, true);
-
- c[0].put(fqn, "k", "v");
-
- assert "v".equals(c[0].get(fqn, "k"));
- assert "v".equals(c[1].get(fqn, "k"));
-
- // now kick start a thread on c[1] that will constantly update the fqn
-
- Thread updater = new Thread()
- {
- public void run()
- {
- int i = 0;
- while (running.get(0))
- {
- try
- {
- i++;
- if (running.get(0)) c[1].put(fqn, "k", "v" + i);
- }
- catch (ReplicationException re)
- {
- // this sometimes happens when JGroups suspects the remote node. This is ok, as long as we don't get an ISE.
- }
- catch (SuspectException se)
- {
- // this sometimes happens when JGroups suspects the remote node. This is ok, as long as we don't get an ISE.
- }
- catch (Exception e)
- {
- exceptions.add(e);
- }
- TestingUtil.sleepThread(20);
-
- }
- }
- };
-
- updater.start();
-
- c[0].stop();
- running.add(false);
- running.remove(true);
- updater.join();
-
- for (Exception e : exceptions) throw e;
- }
-
- public void testInvalidStateTxRollback() throws Exception
- {
- createAndRegisterCache(Configuration.CacheMode.LOCAL, true);
- c[0].getTransactionManager().begin();
- c[0].put(Fqn.ROOT, "k1", "v1");
- c[0].put(Fqn.ROOT, "k2", "v2");
-
- // now DIRECTLY change the status of c.
- LifecycleManager ci0 = (LifecycleManager) TestingUtil.extractField(c[0], "lifecycleManager");
- ci0.setCacheStatus(CacheStatus.STOPPING);
-
- // rollbacks should just log a message
- c[0].getTransactionManager().rollback();
- }
-
-
- private CacheSPI<Object, Object> createCache(Configuration.CacheMode cache_mode)
- {
- CacheSPI<Object, Object> retval = (CacheSPI<Object, Object>) new DefaultCacheFactory().createCache(false);
- retval.getConfiguration().setCacheMode(cache_mode);
- retval.getConfiguration().setTransactionManagerLookupClass("org.jboss.cache.transaction.DummyTransactionManagerLookup");
- return retval;
- }
-
-
- private TransactionManager beginTransaction() throws SystemException, NotSupportedException
- {
- TransactionManager mgr = c[0].getConfiguration().getRuntimeConfig().getTransactionManager();
- mgr.begin();
- return mgr;
- }
-
-
- private void startCache(CacheSPI c)
- {
- c.create();
- c.start();
- }
-
- private void stopCache(CacheSPI c)
- {
- c.stop();
- c.destroy();
- }
-
- private void restartCache(CacheSPI c) throws Exception
- {
- stopCache(c);
- startCache(c);
- }
-
- @CacheListener
- public class DisruptLifecycleListener
- {
- private boolean disrupt;
-
- @CacheStarted
- public void cacheStarted(Event e)
- {
- if (disrupt) throw new IllegalStateException("I don't want to start");
- }
-
- @CacheStopped
- public void cacheStopped(Event e)
- {
- if (disrupt) throw new IllegalStateException("I don't want to stop");
- }
-
- public void setDisrupt(boolean disrupt)
- {
- this.disrupt = disrupt;
- }
- }
-}
16 years, 7 months
JBoss Cache SVN: r5806 - in core/trunk/src: main/java/org/jboss/cache/factories and 8 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-05-08 05:07:31 -0400 (Thu, 08 May 2008)
New Revision: 5806
Modified:
core/trunk/src/main/java/org/jboss/cache/config/ConfigurationComponent.java
core/trunk/src/main/java/org/jboss/cache/factories/BootstrapFactory.java
core/trunk/src/main/java/org/jboss/cache/factories/ComponentFactory.java
core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java
core/trunk/src/main/java/org/jboss/cache/factories/annotations/NonVolatile.java
core/trunk/src/main/java/org/jboss/cache/loader/CacheLoaderManager.java
core/trunk/src/main/java/org/jboss/cache/loader/ChainingCacheLoader.java
core/trunk/src/test/java/org/jboss/cache/cluster/ReplicationQueueTest.java
core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshaller200Test.java
core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshallerTestBase.java
core/trunk/src/test/java/org/jboss/cache/marshall/MarshalledValueTest.java
core/trunk/src/test/java/org/jboss/cache/marshall/MethodIdPreservationTest.java
core/trunk/src/test/java/org/jboss/cache/marshall/VersionAwareMarshallerTest.java
core/trunk/src/test/java/org/jboss/cache/notifications/RemoteCacheListenerTest.java
core/trunk/src/test/java/org/jboss/cache/optimistic/NodeInterceptorGetChildrenNamesTest.java
core/trunk/src/test/java/org/jboss/cache/statetransfer/FailedStateTransferTest.java
core/trunk/src/test/java/org/jboss/cache/transaction/PrepareCommitContentionTest.java
Log:
ComponentRegistry refactoring
Modified: core/trunk/src/main/java/org/jboss/cache/config/ConfigurationComponent.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/config/ConfigurationComponent.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/main/java/org/jboss/cache/config/ConfigurationComponent.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -10,7 +10,7 @@
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.CacheSPI;
import org.jboss.cache.CacheStatus;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.factories.annotations.Start;
@@ -35,7 +35,7 @@
protected transient Log log = LogFactory.getLog(getClass());
private transient CacheSPI cache; // back-reference to test whether the cache is running.
private final Set<ConfigurationComponent> children = Collections.synchronizedSet(new HashSet<ConfigurationComponent>());
- private ComponentKernel cr;
+ private ComponentRegistry cr;
// a workaround to get over immutability checks
private boolean accessible;
@@ -138,7 +138,7 @@
}
@Inject
- private void injectDependencies(ComponentKernel cr)
+ private void injectDependencies(ComponentRegistry cr)
{
this.cr = cr;
}
Modified: core/trunk/src/main/java/org/jboss/cache/factories/BootstrapFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/BootstrapFactory.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/main/java/org/jboss/cache/factories/BootstrapFactory.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -12,15 +12,15 @@
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
* @since 2.2.0
*/
-@DefaultFactoryFor(classes = {CacheSPI.class, Configuration.class, ComponentKernel.class})
+@DefaultFactoryFor(classes = {CacheSPI.class, Configuration.class, ComponentRegistry.class})
@NonVolatile
public class BootstrapFactory extends ComponentFactory
{
CacheSPI cacheSPI;
Configuration configuration;
- ComponentKernel componentRegistry;
+ ComponentRegistry componentRegistry;
- public BootstrapFactory(CacheSPI cacheSPI, Configuration configuration, ComponentKernel componentRegistry)
+ public BootstrapFactory(CacheSPI cacheSPI, Configuration configuration, ComponentRegistry componentRegistry)
{
this.cacheSPI = cacheSPI;
this.configuration = configuration;
@@ -34,7 +34,7 @@
if (componentType.equals(Configuration.class)) return (T) configuration;
- if (componentType.equals(ComponentKernel.class)) return (T) componentRegistry;
+ if (componentType.equals(ComponentRegistry.class)) return (T) componentRegistry;
throw new CacheException("Don't know how to handle type " + componentType);
}
Modified: core/trunk/src/main/java/org/jboss/cache/factories/ComponentFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/ComponentFactory.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/main/java/org/jboss/cache/factories/ComponentFactory.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -16,17 +16,17 @@
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
* @see Inject
- * @see ComponentKernel
+ * @see ComponentRegistry
* @since 2.1.0
*/
public abstract class ComponentFactory
{
protected final Log log = LogFactory.getLog(getClass());
- protected ComponentKernel componentRegistry;
+ protected ComponentRegistry componentRegistry;
protected Configuration configuration;
@Inject
- private void injectDependencies(Configuration configuration, ComponentKernel componentRegistry)
+ private void injectDependencies(Configuration configuration, ComponentRegistry componentRegistry)
{
this.configuration = configuration;
this.componentRegistry = componentRegistry;
Modified: core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -138,7 +138,7 @@
}
}
- public static InterceptorChainFactory getInstance(ComponentKernel componentRegistry, Configuration configuration)
+ public static InterceptorChainFactory getInstance(ComponentRegistry componentRegistry, Configuration configuration)
{
InterceptorChainFactory icf = new InterceptorChainFactory();
icf.componentRegistry = componentRegistry;
Modified: core/trunk/src/main/java/org/jboss/cache/factories/annotations/NonVolatile.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/annotations/NonVolatile.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/main/java/org/jboss/cache/factories/annotations/NonVolatile.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -6,7 +6,7 @@
import java.lang.annotation.Target;
/**
- * This annotation is used for components that will be registered in the {@link org.jboss.cache.factories.ComponentKernel},
+ * This annotation is used for components that will be registered in the {@link org.jboss.cache.factories.ComponentRegistry},
* that are resilient to changes in configuration. Examples are the {@link org.jboss.cache.CacheSPI} implementation used, which does
* not change regardless of the configuration.
*
Modified: core/trunk/src/main/java/org/jboss/cache/loader/CacheLoaderManager.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/loader/CacheLoaderManager.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/main/java/org/jboss/cache/loader/CacheLoaderManager.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -16,7 +16,7 @@
import org.jboss.cache.config.CacheLoaderConfig.IndividualCacheLoaderConfig;
import org.jboss.cache.config.CacheLoaderConfig.IndividualCacheLoaderConfig.SingletonStoreConfig;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.factories.annotations.Start;
import org.jboss.cache.factories.annotations.Stop;
@@ -72,10 +72,10 @@
private boolean fetchPersistentState;
private Configuration configuration;
private RegionManager regionManager;
- private ComponentKernel registry;
+ private ComponentRegistry registry;
@Inject
- public void injectDependencies(CacheSPI cache, Configuration configuration, RegionManager regionManager, ComponentKernel registry)
+ public void injectDependencies(CacheSPI cache, Configuration configuration, RegionManager regionManager, ComponentRegistry registry)
{
this.regionManager = regionManager;
this.config = configuration.getCacheLoaderConfig();
Modified: core/trunk/src/main/java/org/jboss/cache/loader/ChainingCacheLoader.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/loader/ChainingCacheLoader.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/main/java/org/jboss/cache/loader/ChainingCacheLoader.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -11,7 +11,7 @@
import org.jboss.cache.RegionManager;
import org.jboss.cache.config.CacheLoaderConfig;
import org.jboss.cache.config.CacheLoaderConfig.IndividualCacheLoaderConfig;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.factories.annotations.Inject;
import java.io.ObjectInputStream;
@@ -37,7 +37,7 @@
private final List<CacheLoader> cacheLoaders = new ArrayList<CacheLoader>(2);
private final List<CacheLoader> writeCacheLoaders = new ArrayList<CacheLoader>(2);
private final List<CacheLoaderConfig.IndividualCacheLoaderConfig> cacheLoaderConfigs = new ArrayList<CacheLoaderConfig.IndividualCacheLoaderConfig>(2);
- private ComponentKernel registry;
+ private ComponentRegistry registry;
/**
* Sets the configuration. Will be called before {@link #create()} and {@link #start()}
@@ -55,7 +55,7 @@
}
@Inject
- public void injectDependencies(ComponentKernel registry)
+ public void injectDependencies(ComponentRegistry registry)
{
this.registry = registry;
}
Modified: core/trunk/src/test/java/org/jboss/cache/cluster/ReplicationQueueTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/cluster/ReplicationQueueTest.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/test/java/org/jboss/cache/cluster/ReplicationQueueTest.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -7,7 +7,7 @@
import org.jboss.cache.RPCManager;
import org.jboss.cache.commands.ReplicableCommand;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.misc.TestingUtil;
import org.jgroups.Address;
import static org.testng.AssertJUnit.assertNotNull;
@@ -25,7 +25,7 @@
private static final int COUNT = 10;
Cache cache, cache2;
ReplicationQueue replQ;
- ComponentKernel registry;
+ ComponentRegistry registry;
RPCManager originalRpcManager;
@BeforeMethod
Modified: core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshaller200Test.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshaller200Test.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshaller200Test.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -10,7 +10,7 @@
import org.jboss.cache.Region;
import org.jboss.cache.RegionManager;
import org.jboss.cache.commands.remote.ClusteredGetCommand;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.testng.annotations.Test;
import java.io.ByteArrayInputStream;
@@ -87,7 +87,7 @@
final CacheMarshaller200 cm200 = new CacheMarshaller200();
c.setInactiveOnStartup(false);
c.setUseRegionBasedMarshalling(true);
- ComponentKernel cr = new ComponentKernel(c);
+ ComponentRegistry cr = new ComponentRegistry(c);
cr.registerComponent(cm200, CacheMarshaller200.class);
cr.start();
Modified: core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshallerTestBase.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshallerTestBase.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshallerTestBase.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -12,7 +12,7 @@
import org.jboss.cache.commands.remote.ReplicateCommand;
import org.jboss.cache.commands.write.PutKeyValueCommand;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import org.testng.annotations.AfterMethod;
@@ -40,7 +40,7 @@
c.setUseRegionBasedMarshalling(false);
c.setInactiveOnStartup(false);
c.setReplVersionString(currentVersion);
- cr = new ComponentKernel(c);
+ cr = new ComponentRegistry(c);
//c.setUseReferenceCounting(true);
marshaller = createVAMandRestartCache(regionManager);
}
Modified: core/trunk/src/test/java/org/jboss/cache/marshall/MarshalledValueTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/marshall/MarshalledValueTest.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/test/java/org/jboss/cache/marshall/MarshalledValueTest.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -9,7 +9,7 @@
import org.jboss.cache.commands.write.PutKeyValueCommand;
import org.jboss.cache.config.CacheLoaderConfig;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.factories.UnitTestCacheConfigurationFactory;
import org.jboss.cache.interceptors.MarshalledValueInterceptor;
import org.jboss.cache.interceptors.base.CommandInterceptor;
@@ -217,7 +217,7 @@
MarshalledValue mv = new MarshalledValue(pojo);
Configuration c = new Configuration();
- ComponentKernel cr = new ComponentKernel(c);
+ ComponentRegistry cr = new ComponentRegistry(c);
Marshaller marshaller = new CacheMarshaller210();
cr.registerComponent(marshaller, Marshaller.class);
Modified: core/trunk/src/test/java/org/jboss/cache/marshall/MethodIdPreservationTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/marshall/MethodIdPreservationTest.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/test/java/org/jboss/cache/marshall/MethodIdPreservationTest.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -6,7 +6,7 @@
import org.jboss.cache.commands.write.PutDataMapCommand;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.factories.CommandsFactory;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import static org.testng.AssertJUnit.assertEquals;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -46,7 +46,7 @@
prepareComand = new PrepareCommand(null, list, null, true);
CacheMarshaller210 cm210 = new CacheMarshaller210();
- ComponentKernel registry = new ComponentKernel(new Configuration());
+ ComponentRegistry registry = new ComponentRegistry(new Configuration());
CommandsFactory factory = new CommandsFactory();
cm210.injectCommandsFactory(factory);
Modified: core/trunk/src/test/java/org/jboss/cache/marshall/VersionAwareMarshallerTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/marshall/VersionAwareMarshallerTest.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/test/java/org/jboss/cache/marshall/VersionAwareMarshallerTest.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -8,7 +8,7 @@
import org.jboss.cache.Version;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.util.stream.MarshalledValueInputStream;
import static org.testng.AssertJUnit.assertEquals;
import org.testng.annotations.AfterMethod;
@@ -29,7 +29,7 @@
@BeforeMethod
public void setUp()
{
- cr = new ComponentKernel(new Configuration());
+ cr = new ComponentRegistry(new Configuration());
}
@AfterMethod
Modified: core/trunk/src/test/java/org/jboss/cache/notifications/RemoteCacheListenerTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/notifications/RemoteCacheListenerTest.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/test/java/org/jboss/cache/notifications/RemoteCacheListenerTest.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -29,7 +29,7 @@
import org.jboss.cache.Fqn;
import org.jboss.cache.Node;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.lock.IsolationLevel;
import org.jboss.cache.misc.TestingUtil;
import org.jboss.cache.notifications.event.Event;
@@ -110,7 +110,7 @@
public void testSeparateNotifiersAndListeners()
{
assert cache1 != cache2;
- ComponentKernel cr1, cr2;
+ ComponentRegistry cr1, cr2;
cr1 = TestingUtil.extractComponentRegistry(cache1);
cr2 = TestingUtil.extractComponentRegistry(cache2);
assert cr1 != cr2;
Modified: core/trunk/src/test/java/org/jboss/cache/optimistic/NodeInterceptorGetChildrenNamesTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/optimistic/NodeInterceptorGetChildrenNamesTest.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/test/java/org/jboss/cache/optimistic/NodeInterceptorGetChildrenNamesTest.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -2,7 +2,7 @@
import org.jboss.cache.CacheSPI;
import org.jboss.cache.Fqn;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.interceptors.OptimisticCreateIfNotExistsInterceptor;
import org.jboss.cache.interceptors.OptimisticNodeInterceptor;
import org.jboss.cache.interceptors.base.CommandInterceptor;
@@ -37,7 +37,7 @@
listener = new TestListener();
cache = createCacheWithListener(listener);
- ComponentKernel cr = TestingUtil.extractComponentRegistry(cache);
+ ComponentRegistry cr = TestingUtil.extractComponentRegistry(cache);
CommandInterceptor interceptor = new OptimisticCreateIfNotExistsInterceptor();
cr.registerComponent(interceptor, OptimisticCreateIfNotExistsInterceptor.class);
Modified: core/trunk/src/test/java/org/jboss/cache/statetransfer/FailedStateTransferTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/statetransfer/FailedStateTransferTest.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/test/java/org/jboss/cache/statetransfer/FailedStateTransferTest.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -27,7 +27,7 @@
import org.jboss.cache.DefaultCacheFactory;
import org.jboss.cache.Version;
import org.jboss.cache.config.Configuration.CacheMode;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.factories.UnitTestCacheConfigurationFactory;
import org.jboss.cache.lock.TimeoutException;
import org.jboss.cache.misc.TestingUtil;
@@ -60,7 +60,7 @@
caches.put("secretive", cache);
// inject our own message listener and re-wire deps
- ComponentKernel cr = TestingUtil.extractComponentRegistry(cache);
+ ComponentRegistry cr = TestingUtil.extractComponentRegistry(cache);
// cr.unregisterComponent(ChannelMessageListener.class);
cr.registerComponent(new SecretiveStateCacheMessageListener(), ChannelMessageListener.class);
// cr.updateDependencies();
Modified: core/trunk/src/test/java/org/jboss/cache/transaction/PrepareCommitContentionTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/transaction/PrepareCommitContentionTest.java 2008-05-08 09:06:54 UTC (rev 5805)
+++ core/trunk/src/test/java/org/jboss/cache/transaction/PrepareCommitContentionTest.java 2008-05-08 09:07:31 UTC (rev 5806)
@@ -9,7 +9,7 @@
import org.jboss.cache.commands.tx.CommitCommand;
import org.jboss.cache.commands.tx.PrepareCommand;
import static org.jboss.cache.config.Configuration.CacheMode.REPL_SYNC;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.factories.UnitTestCacheConfigurationFactory;
import org.jboss.cache.misc.TestingUtil;
import org.jgroups.Address;
@@ -58,7 +58,7 @@
public void testOOBFlag() throws Exception
{
DelegatingRPCManager delegatingRPCManager = new DelegatingRPCManager();
- ComponentKernel cr = TestingUtil.extractComponentRegistry(c1);
+ ComponentRegistry cr = TestingUtil.extractComponentRegistry(c1);
RPCManager origRpcManager = cr.getComponent(RPCManager.class);
delegatingRPCManager.delegate = origRpcManager;
cr.registerComponent(delegatingRPCManager, RPCManager.class);
16 years, 7 months
JBoss Cache SVN: r5805 - in core/trunk/src: main/java/org/jboss/cache/factories and 6 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-05-08 05:06:54 -0400 (Thu, 08 May 2008)
New Revision: 5805
Added:
core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java
Removed:
core/trunk/src/main/java/org/jboss/cache/factories/ComponentKernel.java
Modified:
core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java
core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java
core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java
core/trunk/src/main/java/org/jboss/cache/invocation/AbstractInvocationDelegate.java
core/trunk/src/main/java/org/jboss/cache/marshall/CommandAwareRpcDispatcher.java
core/trunk/src/main/java/org/jboss/cache/marshall/InactiveRegionAwareRpcDispatcher.java
core/trunk/src/main/java/org/jboss/cache/marshall/VersionAwareMarshaller.java
core/trunk/src/test/java/org/jboss/cache/factories/LifeCycleTest.java
core/trunk/src/test/java/org/jboss/cache/marshall/AbstractVersionAwareMarshallerTest.java
core/trunk/src/test/java/org/jboss/cache/misc/TestingUtil.java
Log:
ComponentRegistry refactoring
Modified: core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java 2008-05-08 09:04:25 UTC (rev 5804)
+++ core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java 2008-05-08 09:06:54 UTC (rev 5805)
@@ -10,7 +10,7 @@
import org.jboss.cache.config.ConfigurationException;
import org.jboss.cache.factories.BootstrapFactory;
import org.jboss.cache.factories.ComponentFactory;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.factories.XmlConfigurationParser;
import org.jboss.cache.invocation.CacheInvocationDelegate;
@@ -20,10 +20,10 @@
* Default implementation of the {@link org.jboss.cache.CacheFactory} interface.
* <p/>
* This is a special instance of a {@link ComponentFactory} which contains bootstrap information for the
- * {@link org.jboss.cache.factories.ComponentKernel}.
+ * {@link org.jboss.cache.factories.ComponentRegistry}.
* <p/>
* E.g., {@link #bootstrap(LifecycleManager , CacheSPI, org.jboss.cache.config.Configuration)} is used to create a cache, a
- * {@link org.jboss.cache.factories.ComponentKernel}, and then wire dependencies as needed.
+ * {@link org.jboss.cache.factories.ComponentRegistry}, and then wire dependencies as needed.
* <p/>
* In JBoss Cache 2.0.x, this was a singleton and you had to use {@link #getInstance()} to obtain an instance. From
* JBoss Cache 2.1.x onwards, this is no longer a singleton and you can use the default no-arg constructor to obtain
@@ -126,7 +126,7 @@
private void bootstrap(CacheSPI spi, Configuration configuration)
{
// injection bootstrap stuff
- componentRegistry = new ComponentKernel(configuration);
+ componentRegistry = new ComponentRegistry(configuration);
componentRegistry.registerDefaultClassLoader(defaultClassLoader);
this.configuration = configuration;
BootstrapFactory bf = new BootstrapFactory(spi, configuration, componentRegistry);
Modified: core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java 2008-05-08 09:04:25 UTC (rev 5804)
+++ core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java 2008-05-08 09:06:54 UTC (rev 5805)
@@ -11,7 +11,7 @@
import org.jboss.cache.commands.ReplicableCommand;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.config.RuntimeConfig;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.factories.annotations.Start;
import org.jboss.cache.factories.annotations.Stop;
@@ -93,13 +93,13 @@
private boolean isUsingBuddyReplication;
private boolean isInLocalMode;
- private ComponentKernel componentRegistry;
+ private ComponentRegistry componentRegistry;
@Inject
private void setupDependencies(ChannelMessageListener messageListener, Configuration configuration, Notifier notifier,
CacheSPI spi, Marshaller marshaller, TransactionTable txTable,
TransactionManager txManager, InvocationContextContainer container, InterceptorChain interceptorChain,
- ComponentKernel componentRegistry)
+ ComponentRegistry componentRegistry)
{
this.messageListener = messageListener;
this.configuration = configuration;
Deleted: core/trunk/src/main/java/org/jboss/cache/factories/ComponentKernel.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/ComponentKernel.java 2008-05-08 09:04:25 UTC (rev 5804)
+++ core/trunk/src/main/java/org/jboss/cache/factories/ComponentKernel.java 2008-05-08 09:06:54 UTC (rev 5805)
@@ -1,931 +0,0 @@
-package org.jboss.cache.factories;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.cache.CacheException;
-import org.jboss.cache.CacheStatus;
-import org.jboss.cache.Version;
-import org.jboss.cache.config.Configuration;
-import org.jboss.cache.config.ConfigurationException;
-import org.jboss.cache.config.RuntimeConfig;
-import org.jboss.cache.factories.annotations.DefaultFactoryFor;
-import org.jboss.cache.factories.annotations.Destroy;
-import org.jboss.cache.factories.annotations.Inject;
-import org.jboss.cache.factories.annotations.NonVolatile;
-import org.jboss.cache.factories.annotations.Start;
-import org.jboss.cache.factories.annotations.Stop;
-import org.jboss.cache.util.BeanUtils;
-import org.jboss.cache.util.reflect.CachedMethod;
-import org.jboss.cache.util.reflect.ReflectionUtil;
-
-import javax.management.MBeanServerFactory;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * A registry where components which have been created are stored. Components are stored as singletons, registered under
- * a specific name.
- * <p/>
- * Components can be retrieved from the registry using {@link #getComponent(Class)}.
- * <p/>
- * Components can be registered using {@link #registerComponent(Object, Class)}, which will cause any dependencies to be
- * wired in as well. Components that need to be created as a result of wiring will be done using {@link #getOrCreateComponent(Class)},
- * which will look up the default factory for the component type (factories annotated with the appropriate {@link DefaultFactoryFor} annotation.
- * <p/>
- * Default factories are treated as components too and will need to be wired before being used.
- * <p/>
- * The registry can exist in one of 5 states, as defined by the {@link CacheStatus} enumeration. In terms of the cache,
- * state changes in the following manner:
- * <ul>
- * <li>CONSTRUCTED - when first constructed</li>
- * <li>WIRED - when created using the DefaultCacheFactory</li>
- * <li>When {@link org.jboss.cache.Cache#create()} is called, the components are rewired.</li>
- * <li>STARTED - when {@link org.jboss.cache.Cache#start()} is called</li>
- * <li>STOPPED - when {@link org.jboss.cache.Cache#stop()} is called</li>
- * <li>DESTROYED - when {@link org.jboss.cache.Cache#destroy()} is called.</li>
- * </ul>
- * <p/>
- * Cache configuration can only be changed and will only be reinjected if the cache is not in the {@link org.jboss.cache.CacheStatus#STARTED} state.
- *
- * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
- * @since 2.1.0
- */
-@NonVolatile
-public class ComponentKernel
-{
- /**
- * Contains class definitions of component factories that can be used to construct certain components
- */
- Map<Class, Class<? extends ComponentFactory>> defaultFactories = null;
-
- private static final Log log = LogFactory.getLog(ComponentKernel.class);
- private static final boolean trace = log.isTraceEnabled();
- protected static final Object NULL_COMPONENT = new Object();
-
- // component and method containers
- final Map<String, Component> componentLookup = new HashMap<String, Component>();
- final List<PrioritizedMethod> startMethods = new ArrayList<PrioritizedMethod>();
- final List<PrioritizedMethod> stopMethods = new ArrayList<PrioritizedMethod>();
- final List<PrioritizedMethod> destroyMethods = new ArrayList<PrioritizedMethod>();
-
- CacheStatus state = CacheStatus.INSTANTIATED;
-
- /**
- * Hook to shut down the cache when the JVM exits.
- */
- private Thread shutdownHook;
- /**
- * A flag that the shutdown hook sets before calling cache.stop(). Allows stop() to identify if it has been called
- * from a shutdown hook.
- */
- private boolean invokedFromShutdownHook;
-
-
- /**
- * Creates an instance of the component registry. The configuration passed in is automatically registered.
- *
- * @param configuration configuration with which this is created
- */
- public ComponentKernel(Configuration configuration)
- {
- try
- {
- // bootstrap.
- registerDefaultClassLoader(null);
- registerComponent(this, ComponentKernel.class);
- registerComponent(configuration, Configuration.class);
- }
- catch (Exception e)
- {
- throw new CacheException("Unable to construct ComponentRegistry", e);
- }
- }
-
- /**
- * Retrieves the state of the registry
- *
- * @return state of the registry
- */
- public CacheStatus getState()
- {
- return state;
- }
-
- /**
- * Wires an object instance with dependencies annotated with the {@link org.jboss.cache.factories.annotations.Inject} annotation, creating more components
- * as needed based on the Configuration passed in if these additional components don't exist in the
- * {@link org.jboss.cache.factories.ComponentKernel}. Strictly for components that don't otherwise live in the registry and have a lifecycle, such as Nodes.
- *
- * @param target object to wire
- * @throws ConfigurationException if there is a problem wiring the instance
- */
- public void wireDependencies(Object target) throws ConfigurationException
- {
- try
- {
- List<CachedMethod> methods = ReflectionUtil.getAllCachedMethods(target.getClass(), Inject.class);
-
- // search for anything we need to inject
- for (CachedMethod method : methods) invokeInjectionMethod(target, method);
- }
- catch (Exception e)
- {
- throw new ConfigurationException("Unable to configure component (type: " + target.getClass() + ", instance " + target + ")", e);
- }
- }
-
- /**
- * Registers the default class loader. This method *must* be called before any other components are registered,
- * typically called by bootstrap code. Defensively, it is called in the constructor of ComponentRegistry with a null
- * parameter.
- *
- * @param loader a class loader to use by default. If this is null, the class loader used to load this instance of ComponentRegistry is used.
- */
- public void registerDefaultClassLoader(ClassLoader loader)
- {
- registerComponent(loader == null ? getClass().getClassLoader() : loader, ClassLoader.class);
- // make sure the class loader is non-volatile, so it survives restarts.
- componentLookup.get(ClassLoader.class.getName()).nonVolatile = true;
- }
-
- /**
- * This is hard coded for now, since scanning the classpath for factories annotated with {@link org.jboss.cache.factories.annotations.DefaultFactoryFor}
- * does not work with all class loaders. This is a temporary solution until a more elegant one can be designed.
- * <p/>
- * BE SURE TO ADD ANY NEW FACTORY TYPES ANNOTATED WITH DefaultFactoryFor TO THIS SET!!
- * <p/>
- *
- * @return set of known factory types.
- */
- private Set<Class<? extends ComponentFactory>> getHardcodedFactories()
- {
- Set<Class<? extends ComponentFactory>> s = new HashSet<Class<? extends ComponentFactory>>();
- s.add(BootstrapFactory.class);
- s.add(BuddyManagerFactory.class);
- s.add(EmptyConstructorFactory.class);
- s.add(InterceptorChainFactory.class);
- s.add(RuntimeConfigAwareFactory.class);
- s.add(TransactionManagerFactory.class);
- s.add(ReplicationQueueFactory.class);
- return s;
- }
-
- /**
- * Registers a component in the registry under the given type, and injects any dependencies needed. If a component
- * of this type already exists, it is overwritten.
- *
- * @param component component to register
- * @param type type of component
- */
- public void registerComponent(Object component, Class type)
- {
- Component c = new Component();
- String name = type.getName();
- c.name = name;
- c.nonVolatile = component.getClass().isAnnotationPresent(NonVolatile.class);
- c.instance = component;
- Component old = componentLookup.get(name);
-
- if (old != null)
- {
- // if they are equal don't bother
- if (old.instance.equals(component))
- {
- if (trace)
- log.trace("Attempting to register a component equal to one that already exists under the same name (" + name + "). Not doing anything.");
- return;
- }
- }
-
- if (trace) log.trace("Registering component " + c + " under name " + name);
-
- if (old != null)
- {
- if (trace) log.trace("Replacing old component " + old);
- old.instance = component;
- }
- else
- {
- componentLookup.put(name, c);
- }
- addComponentDependencies(c);
- // inject dependencies for this component
- c.injectDependencies();
- }
-
- /**
- * Adds component dependencies for a given component, by populating {@link Component#injectionMethods}.
- *
- * @param c component to add dependencies to
- */
- protected void addComponentDependencies(Component c)
- {
- Class type = c.instance.getClass();
- List<CachedMethod> methods = ReflectionUtil.getAllCachedMethods(type, Inject.class);
-
- for (CachedMethod m : methods) c.injectionMethods.add(m);
- }
-
- @SuppressWarnings("unchecked")
- protected void invokeInjectionMethod(Object o, CachedMethod m)
- {
- Class[] dependencies = m.getParameterTypes();
- Object[] params = new Object[dependencies.length];
-
- for (int i = 0; i < dependencies.length; i++)
- {
- params[i] = getOrCreateComponent(dependencies[i]);
- }
-
- ReflectionUtil.invokeAccessibly(o, m.getMethod(), params);
- }
-
- /**
- * Retrieves a component if one exists, and if not, attempts to find a factory capable of constructing the component
- * (factories annotated with the {@link DefaultFactoryFor} annotation that is capable of creating the component class).
- * <p/>
- * If an instance needs to be constructed, dependencies are then automatically wired into the instance, based on methods
- * on the component type annotated with {@link Inject}.
- * <p/>
- * Summing it up, component retrieval happens in the following order:<br />
- * 1. Look for a component that has already been created and registered.
- * 2. Look for an appropriate component that exists in the {@link Configuration} that may be injected from an external system.
- * 3. Look for a class definition passed in to the {@link org.jboss.cache.config.Configuration} - such as an EvictionPolicy implementation
- * 4. Attempt to create it by looking for an appropriate factory (annotated with {@link DefaultFactoryFor})
- * <p/>
- *
- * @param componentClass type of component to be retrieved. Should not be null.
- * @return a fully wired component instance, or null if one cannot be found or constructed.
- * @throws ConfigurationException if there is a problem with consructing or wiring the instance.
- */
- protected <T> T getOrCreateComponent(Class<T> componentClass)
- {
-
- T component = getComponent(componentClass);
-
- if (component == null)
- {
- // first see if this has been injected externally.
- component = getFromConfiguration(componentClass);
- boolean attemptedFactoryConstruction = false;
-
- if (component == null)
- {
- // create this component and add it to the registry
- ComponentFactory factory = getFactory(componentClass);
- component = factory.construct(componentClass);
- attemptedFactoryConstruction = true;
-
- }
-
- if (component != null)
- {
- registerComponent(component, componentClass);
- }
- else if (attemptedFactoryConstruction)
- {
- if (trace) log.trace("Registering a null for component " + componentClass.getSimpleName());
- registerNullComponent(componentClass);
- }
- }
-
- return component;
- }
-
- /**
- * Retrieves a component factory instance capable of constructing components of a specified type. If the factory doesn't
- * exist in the registry, one is created.
- *
- * @param componentClass type of component to construct
- * @return component factory capable of constructing such components
- */
- protected ComponentFactory getFactory(Class componentClass)
- {
- if (defaultFactories == null) scanDefaultFactories();
- Class<? extends ComponentFactory> cfClass = defaultFactories.get(componentClass);
- if (cfClass == null)
- throw new ConfigurationException("No registered default factory for component " + componentClass + " found!");
- // a component factory is a component too! See if one has been created and exists in the registry
- ComponentFactory cf = getComponent(cfClass);
- if (cf == null)
- {
- // hasn't yet been created. Create and put in registry
- cf = instantiateFactory(cfClass);
- if (cf != null)
- {
- // we simply register this factory. Registration will take care of constructing any dependencies.
- registerComponent(cf, cfClass);
- }
- }
-
- if (cf == null)
- throw new ConfigurationException("Unable to locate component factory for component " + componentClass);
-
- // ensure the component factory is in the STARTED state!
- Component c = componentLookup.get(cfClass.getName());
- if (c.instance != cf)
- throw new ConfigurationException("Component factory " + cfClass + " incorrectly registered!");
- return cf;
- }
-
- /**
- * Scans the class path for classes annotated with {@link org.jboss.cache.factories.annotations.DefaultFactoryFor}, and
- * analyses which components can be created by such factories.
- */
- void scanDefaultFactories()
- {
- defaultFactories = new HashMap<Class, Class<? extends ComponentFactory>>();
-
- Set<Class<? extends ComponentFactory>> factories = getHardcodedFactories();
-
- for (Class<? extends ComponentFactory> factory : factories)
- {
- DefaultFactoryFor dFFAnnotation = factory.getAnnotation(DefaultFactoryFor.class);
- for (Class targetClass : dFFAnnotation.classes()) defaultFactories.put(targetClass, factory);
- }
- }
-
- /**
- * No such thing as a meta factory yet. Factories are created using this method which attempts to use an empty public
- * constructor.
- *
- * @param factory class of factory to be created
- * @return factory instance
- */
- ComponentFactory instantiateFactory(Class<? extends ComponentFactory> factory)
- {
- try
- {
- return factory.newInstance();
- }
- catch (Exception e)
- {
- // unable to get a hold of an instance!!
- throw new ConfigurationException("Unable to instantiate factory " + factory, e);
- }
- }
-
- /**
- * registers a special "null" component that has no dependencies.
- *
- * @param type type of component to register as a null
- */
- void registerNullComponent(Class type)
- {
- registerComponent(NULL_COMPONENT, type);
- }
-
- /**
- * Retrieves a component from the {@link Configuration} or {@link RuntimeConfig}.
- *
- * @param componentClass component type
- * @return component, or null if it cannot be found
- */
- @SuppressWarnings("unchecked")
- protected <T> T getFromConfiguration(Class<T> componentClass)
- {
- if (log.isDebugEnabled())
- log.debug("Looking in configuration for an instance of " + componentClass + " that may have been injected from an external source.");
- Method getter = BeanUtils.getterMethod(Configuration.class, componentClass);
- T returnValue = null;
-
- if (getter != null)
- {
- try
- {
- returnValue = (T) getter.invoke(getConfiguration());
- }
- catch (Exception e)
- {
- log.warn("Unable to invoke getter " + getter + " on Configuration.class!", e);
- }
- }
-
- // now try the RuntimeConfig - a legacy "registry" of sorts.
- if (returnValue == null)
- {
- getter = BeanUtils.getterMethod(RuntimeConfig.class, componentClass);
- if (getter != null)
- {
- try
- {
- returnValue = (T) getter.invoke(getConfiguration().getRuntimeConfig());
- }
- catch (Exception e)
- {
- log.warn("Unable to invoke getter " + getter + " on RuntimeConfig.class!", e);
- }
- }
- }
- return returnValue;
- }
-
- /**
- * Retrieves the configuration component.
- *
- * @return a Configuration object
- */
- protected Configuration getConfiguration()
- {
- // this is assumed to always be present as a part of the bootstrap/construction of a ComponentRegistry.
- return getComponent(Configuration.class);
- }
-
- /**
- * Retrieves a component of a specified type from the registry, or null if it cannot be found.
- *
- * @param type type to find
- * @return component, or null
- */
- @SuppressWarnings("unchecked")
- public <T> T getComponent(Class<T> type)
- {
- Component wrapper = componentLookup.get(type.getName());
- if (wrapper == null) return null;
-
- return (T) (wrapper.instance == NULL_COMPONENT ? null : wrapper.instance);
- }
-
- /**
- * Marks state as wired. Used by the DefaultCacheFactory after it has added the BootstrapFactory and CacheSPI components.
- */
- public void wire()
- {
- state = CacheStatus.CREATED;
- }
-
- /**
- * Rewires components. Can only be called if the current state is WIRED or STARTED.
- */
- public void rewire()
- {
- // need to re-inject everything again.
- for (Component c : new HashSet<Component>(componentLookup.values()))
- {
- // inject dependencies for this component
- c.injectDependencies();
- }
- }
-
- /**
- * Scans each registered component for lifecycle methods, and adds them to the appropriate lists, and then sorts them
- * by priority.
- */
- private void populateLifecycleMethods()
- {
- // cache a list of the start annotated methods
- startMethods.clear();
- for (Component c : componentLookup.values())
- {
- List<Method> methods = ReflectionUtil.getAllMethods(c.instance.getClass(), Start.class);
- for (Method m : methods)
- {
- PrioritizedMethod em = new PrioritizedMethod();
- em.component = c;
- em.method = m;
- em.priority = m.getAnnotation(Start.class).priority();
- startMethods.add(em);
- }
- }
-
- // cache a list of the stop annotated methods
- stopMethods.clear();
- for (Component c : componentLookup.values())
- {
- List<Method> methods = ReflectionUtil.getAllMethods(c.instance.getClass(), Stop.class);
- for (Method m : methods)
- {
- PrioritizedMethod em = new PrioritizedMethod();
- em.component = c;
- em.method = m;
- em.priority = m.getAnnotation(Stop.class).priority();
- stopMethods.add(em);
- }
- }
-
- // cache a list of the destroy annotated methods
- destroyMethods.clear();
- for (Component c : componentLookup.values())
- {
- List<Method> methods = ReflectionUtil.getAllMethods(c.instance.getClass(), Destroy.class);
- for (Method m : methods)
- {
- PrioritizedMethod em = new PrioritizedMethod();
- em.component = c;
- em.method = m;
- em.priority = m.getAnnotation(Destroy.class).priority();
- destroyMethods.add(em);
- }
- }
-
- Collections.sort(startMethods);
- Collections.sort(stopMethods);
- Collections.sort(destroyMethods);
- }
-
- /**
- * Removes any components not annotated as @NonVolatile.
- */
- public void resetNonVolatile()
- {
- // destroy all components to clean up resources
- for (Component c : new HashSet<Component>(componentLookup.values()))
- {
- // the component is volatile!!
- if (!c.nonVolatile)
- {
- componentLookup.remove(c.name);
- }
- }
-
- if (trace) log.trace("Reset volatile components");
- }
-
- // ------------------------------ START: Publicly available lifecycle methods -----------------------------
- // These methods perform a check for appropriate transition and then delegate to similarly named internal methods.
-
- /**
- * Creates the components needed by a cache instance and sets the cache status to {@link org.jboss.cache.CacheStatus#CREATED}
- * when it is done.
- */
- public void create()
- {
- if (!state.createAllowed())
- {
- if (state.needToDestroyFailedCache())
- destroy();
- else
- return;
- }
-
- try
- {
- internalCreate();
- }
- catch (Throwable t)
- {
- handleLifecycleTransitionFailure(t);
- }
- }
-
- /**
- * This starts the components in the cache, connecting to channels, starting service threads, etc. If the cache is
- * not in the {@link org.jboss.cache.CacheStatus#CREATED} state, {@link #create()} will be invoked first.
- */
- public void start()
- {
- boolean createdInStart = false;
- if (!state.startAllowed())
- {
- if (state.needToDestroyFailedCache())
- destroy(); // this will take us back to DESTROYED
-
- if (state.needCreateBeforeStart())
- {
- create();
- createdInStart = true;
- }
- else
- return;
- }
-
- try
- {
- internalStart(createdInStart);
- }
- catch (Throwable t)
- {
- handleLifecycleTransitionFailure(t);
- }
- }
-
- /**
- * Stops the cache and sets the cache status to {@link org.jboss.cache.CacheStatus#STOPPED} once it is done. If the cache is not in
- * the {@link org.jboss.cache.CacheStatus#STARTED} state, this is a no-op.
- */
- public void stop()
- {
- if (!state.stopAllowed())
- {
- return;
- }
-
- // Trying to stop() from FAILED is valid, but may not work
- boolean failed = state == CacheStatus.FAILED;
-
- try
- {
- internalStop();
- }
- catch (Throwable t)
- {
- if (failed)
- {
- log.warn("Attempted to stop() from FAILED state, but caught exception; try calling destroy()", t);
- }
- handleLifecycleTransitionFailure(t);
- }
- finally
- {
- if (!failed) state = CacheStatus.STOPPED;
- }
- }
-
- /**
- * Destroys the cache and frees up any resources. Sets the cache status to {@link CacheStatus#DESTROYED} when it is done.
- * <p/>
- * If the cache is in {@link org.jboss.cache.CacheStatus#STARTED} when this method is called, it will first call {@link #stop()}
- * to stop the cache.
- */
- public void destroy()
- {
- if (!state.destroyAllowed())
- {
- if (state.needStopBeforeDestroy())
- {
- try
- {
- stop();
- }
- catch (CacheException e)
- {
- log.warn("Needed to call stop() before destroying but stop() threw exception. Proceeding to destroy", e);
- }
- }
- else
- return;
- }
-
- try
- {
- internalDestroy();
- }
- finally
- {
- // We always progress to destroyed
- state = CacheStatus.DESTROYED;
- }
- }
- // ------------------------------ END: Publicly available lifecycle methods -----------------------------
-
- // ------------------------------ START: Actual internal lifecycle methods --------------------------------
-
- /**
- * Sets the cacheStatus to FAILED and rethrows the problem as one
- * of the declared types. Converts any non-RuntimeException Exception
- * to CacheException.
- *
- * @param t throwable thrown during failure
- */
- private void handleLifecycleTransitionFailure(Throwable t)
- {
- state = CacheStatus.FAILED;
- if (t instanceof CacheException)
- throw (CacheException) t;
- else if (t instanceof RuntimeException)
- throw (RuntimeException) t;
- else if (t instanceof Error)
- throw (Error) t;
- else
- throw new CacheException(t);
- }
-
- /**
- * The actual create implementation.
- */
- private void internalCreate()
- {
- state = CacheStatus.CREATING;
- resetNonVolatile();
- rewire();
- state = CacheStatus.CREATED;
- }
-
- private void internalStart(boolean createdInStart) throws CacheException, IllegalArgumentException
- {
- if (!createdInStart)
- {
- // re-wire all dependencies in case stuff has changed since the cache was created
- // remove any components whose construction may have depended upon a configuration that may have changed.
- resetNonVolatile();
- rewire();
- }
-
- state = CacheStatus.STARTING;
-
- // start all internal components
- // first cache all start, stop and destroy methods.
- populateLifecycleMethods();
-
- // fire all START methods according to priority
- for (PrioritizedMethod em : startMethods) em.invoke();
-
- addShutdownHook();
-
- log.info("JBoss Cache version: " + Version.printVersion());
- state = CacheStatus.STARTED;
- }
-
- private void addShutdownHook()
- {
- ArrayList al = MBeanServerFactory.findMBeanServer(null);
- boolean registerShutdownHook = (getConfiguration().getShutdownHookBehavior() == Configuration.ShutdownHookBehavior.DEFAULT && al.size() == 0)
- || getConfiguration().getShutdownHookBehavior() == Configuration.ShutdownHookBehavior.REGISTER;
-
- if (registerShutdownHook)
- {
- if (log.isTraceEnabled())
- log.trace("Registering a shutdown hook. Configured behavior = " + getConfiguration().getShutdownHookBehavior());
- shutdownHook = new Thread()
- {
- @Override
- public void run()
- {
- try
- {
- invokedFromShutdownHook = true;
- ComponentKernel.this.stop();
- }
- finally
- {
- invokedFromShutdownHook = false;
- }
- }
- };
-
- Runtime.getRuntime().addShutdownHook(shutdownHook);
- }
- else
- {
- if (log.isTraceEnabled())
- log.trace("Not registering a shutdown hook. Configured behavior = " + getConfiguration().getShutdownHookBehavior());
- }
- }
-
- /**
- * Actual stop
- */
- private void internalStop()
- {
- state = CacheStatus.STOPPING;
- // if this is called from a source other than the shutdown hook, deregister the shutdown hook.
- if (!invokedFromShutdownHook && shutdownHook != null) Runtime.getRuntime().removeShutdownHook(shutdownHook);
-
- // fire all STOP methods according to priority
- for (PrioritizedMethod em : stopMethods) em.invoke();
-
- state = CacheStatus.STOPPED;
- }
-
- /**
- * Actual destroy
- */
- private void internalDestroy()
- {
-
- state = CacheStatus.DESTROYING;
-
- resetNonVolatile();
-
- // fire all DESTROY methods according to priority
- for (PrioritizedMethod em : destroyMethods) em.invoke();
-
- state = CacheStatus.DESTROYED;
- }
-
- // ------------------------------ END: Actual internal lifecycle methods --------------------------------
-
- /**
- * Asserts whether invocations are allowed on the cache or not. Returns <tt>true</tt> if invocations are to be allowed,
- * <tt>false</tt> otherwise. If the origin of the call is remote and the cache status is {@link org.jboss.cache.CacheStatus#STARTING},
- * this method will block for up to {@link org.jboss.cache.config.Configuration#getStateRetrievalTimeout()} millis, checking
- * for a valid state.
- *
- * @param originLocal true if the call originates locally (i.e., from the {@link org.jboss.cache.invocation.CacheInvocationDelegate} or false if it originates remotely, i.e., from the {@link org.jboss.cache.marshall.CommandAwareRpcDispatcher}.
- * @return true if invocations are allowed, false otherwise.
- */
- public boolean invocationsAllowed(boolean originLocal)
- {
- log.trace("Testing if invocations are allowed.");
- if (state.allowInvocations()) return true;
-
- // if this is a locally originating call and the cache is not in a valid state, return false.
- if (originLocal) return false;
-
- log.trace("Is remotely originating.");
-
- // else if this is a remote call and the status is STARTING, wait until the cache starts.
- if (state == CacheStatus.STARTING)
- {
- log.trace("Cache is starting; block.");
- try
- {
- blockUntilCacheStarts();
- return true;
- }
- catch (InterruptedException e)
- {
- Thread.currentThread().interrupt();
- }
- }
- else
- {
- log.warn("Received a remote call but the cache is not in STARTED state - ignoring call.");
- }
- return false;
- }
-
- /**
- * Blocks until the current cache instance is in it's {@link org.jboss.cache.CacheStatus#STARTED started} phase. Blocks
- * for up to {@link org.jboss.cache.config.Configuration#getStateRetrievalTimeout()} milliseconds, throwing an IllegalStateException
- * if the cache doesn't reach this state even after this maximum wait time.
- *
- * @throws InterruptedException if interrupted while waiting
- * @throws IllegalStateException if even after waiting the cache has not started.
- */
- private void blockUntilCacheStarts() throws InterruptedException, IllegalStateException
- {
- int pollFrequencyMS = 100;
- long startupWaitTime = getConfiguration().getStateRetrievalTimeout();
- long giveUpTime = System.currentTimeMillis() + startupWaitTime;
-
- while (System.currentTimeMillis() < giveUpTime)
- {
- if (state.allowInvocations()) break;
- Thread.sleep(pollFrequencyMS);
- }
-
- // check if we have started.
- if (!state.allowInvocations())
- throw new IllegalStateException("Cache not in STARTED state, even after waiting " + getConfiguration().getStateRetrievalTimeout() + " millis.");
- }
-
- /**
- * A wrapper representing a component in the registry
- */
- public class Component
- {
- /**
- * A reference to the object instance for this component.
- */
- Object instance;
- /**
- * The name of the component
- */
- String name;
- /**
- * List of injection methods used to inject dependencies into the component
- */
- List<CachedMethod> injectionMethods = new LinkedList<CachedMethod>();
- /**
- * If true, then this component is not flushed before starting the ComponentRegistry.
- */
- boolean nonVolatile;
-
- @Override
- public String toString()
- {
- return "Component{" +
- "instance=" + instance +
- ", name=" + name +
- ", nonVolatile=" + nonVolatile +
- '}';
- }
-
- /**
- * Injects dependencies into this component.
- */
- public void injectDependencies()
- {
- for (CachedMethod m : injectionMethods) invokeInjectionMethod(instance, m);
- }
- }
-
-
- /**
- * Wrapper to encapsulate a method along with a priority
- */
- class PrioritizedMethod implements Comparable<PrioritizedMethod>
- {
- Method method;
- Component component;
- int priority;
-
- public int compareTo(PrioritizedMethod o)
- {
- return (priority < o.priority ? -1 : (priority == o.priority ? 0 : 1));
- }
-
- void invoke()
- {
- ReflectionUtil.invokeAccessibly(component.instance, method, null);
- }
- }
-}
Copied: core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java (from rev 5804, core/trunk/src/main/java/org/jboss/cache/factories/ComponentKernel.java)
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java (rev 0)
+++ core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java 2008-05-08 09:06:54 UTC (rev 5805)
@@ -0,0 +1,931 @@
+package org.jboss.cache.factories;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.cache.CacheException;
+import org.jboss.cache.CacheStatus;
+import org.jboss.cache.Version;
+import org.jboss.cache.config.Configuration;
+import org.jboss.cache.config.ConfigurationException;
+import org.jboss.cache.config.RuntimeConfig;
+import org.jboss.cache.factories.annotations.DefaultFactoryFor;
+import org.jboss.cache.factories.annotations.Destroy;
+import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.factories.annotations.NonVolatile;
+import org.jboss.cache.factories.annotations.Start;
+import org.jboss.cache.factories.annotations.Stop;
+import org.jboss.cache.util.BeanUtils;
+import org.jboss.cache.util.reflect.CachedMethod;
+import org.jboss.cache.util.reflect.ReflectionUtil;
+
+import javax.management.MBeanServerFactory;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A registry where components which have been created are stored. Components are stored as singletons, registered under
+ * a specific name.
+ * <p/>
+ * Components can be retrieved from the registry using {@link #getComponent(Class)}.
+ * <p/>
+ * Components can be registered using {@link #registerComponent(Object, Class)}, which will cause any dependencies to be
+ * wired in as well. Components that need to be created as a result of wiring will be done using {@link #getOrCreateComponent(Class)},
+ * which will look up the default factory for the component type (factories annotated with the appropriate {@link DefaultFactoryFor} annotation.
+ * <p/>
+ * Default factories are treated as components too and will need to be wired before being used.
+ * <p/>
+ * The registry can exist in one of several states, as defined by the {@link CacheStatus} enumeration. In terms of the cache,
+ * state changes in the following manner:
+ * <ul>
+ * <li>INSTANTIATED - when first constructed</li>
+ * <li>CONSTRUCTED - when created using the DefaultCacheFactory</li>
+ * <li>When {@link org.jboss.cache.Cache#create()} is called, the components are rewired.</li>
+ * <li>STARTED - when {@link org.jboss.cache.Cache#start()} is called</li>
+ * <li>STOPPED - when {@link org.jboss.cache.Cache#stop()} is called</li>
+ * <li>DESTROYED - when {@link org.jboss.cache.Cache#destroy()} is called.</li>
+ * </ul>
+ * <p/>
+ * Cache configuration can only be changed and will only be reinjected if the cache is not in the {@link org.jboss.cache.CacheStatus#STARTED} state.
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @since 2.1.0
+ */
+@NonVolatile
+public class ComponentRegistry
+{
+ /**
+ * Contains class definitions of component factories that can be used to construct certain components
+ */
+ Map<Class, Class<? extends ComponentFactory>> defaultFactories = null;
+
+ private static final Log log = LogFactory.getLog(ComponentRegistry.class);
+ private static final boolean trace = log.isTraceEnabled();
+ protected static final Object NULL_COMPONENT = new Object();
+
+ // component and method containers
+ final Map<String, Component> componentLookup = new HashMap<String, Component>();
+ final List<PrioritizedMethod> startMethods = new ArrayList<PrioritizedMethod>();
+ final List<PrioritizedMethod> stopMethods = new ArrayList<PrioritizedMethod>();
+ final List<PrioritizedMethod> destroyMethods = new ArrayList<PrioritizedMethod>();
+
+ CacheStatus state = CacheStatus.INSTANTIATED;
+
+ /**
+ * Hook to shut down the cache when the JVM exits.
+ */
+ private Thread shutdownHook;
+ /**
+ * A flag that the shutdown hook sets before calling cache.stop(). Allows stop() to identify if it has been called
+ * from a shutdown hook.
+ */
+ private boolean invokedFromShutdownHook;
+
+
+ /**
+ * Creates an instance of the component registry. The configuration passed in is automatically registered.
+ *
+ * @param configuration configuration with which this is created
+ */
+ public ComponentRegistry(Configuration configuration)
+ {
+ try
+ {
+ // bootstrap.
+ registerDefaultClassLoader(null);
+ registerComponent(this, ComponentRegistry.class);
+ registerComponent(configuration, Configuration.class);
+ }
+ catch (Exception e)
+ {
+ throw new CacheException("Unable to construct ComponentRegistry", e);
+ }
+ }
+
+ /**
+ * Retrieves the state of the registry
+ *
+ * @return state of the registry
+ */
+ public CacheStatus getState()
+ {
+ return state;
+ }
+
+ /**
+ * Wires an object instance with dependencies annotated with the {@link org.jboss.cache.factories.annotations.Inject} annotation, creating more components
+ * as needed based on the Configuration passed in if these additional components don't exist in the
+ * {@link ComponentRegistry}. Strictly for components that don't otherwise live in the registry and have a lifecycle, such as Nodes.
+ *
+ * @param target object to wire
+ * @throws ConfigurationException if there is a problem wiring the instance
+ */
+ public void wireDependencies(Object target) throws ConfigurationException
+ {
+ try
+ {
+ List<CachedMethod> methods = ReflectionUtil.getAllCachedMethods(target.getClass(), Inject.class);
+
+ // search for anything we need to inject
+ for (CachedMethod method : methods) invokeInjectionMethod(target, method);
+ }
+ catch (Exception e)
+ {
+ throw new ConfigurationException("Unable to configure component (type: " + target.getClass() + ", instance " + target + ")", e);
+ }
+ }
+
+ /**
+ * Registers the default class loader. This method *must* be called before any other components are registered,
+ * typically called by bootstrap code. Defensively, it is called in the constructor of ComponentRegistry with a null
+ * parameter.
+ *
+ * @param loader a class loader to use by default. If this is null, the class loader used to load this instance of ComponentRegistry is used.
+ */
+ public void registerDefaultClassLoader(ClassLoader loader)
+ {
+ registerComponent(loader == null ? getClass().getClassLoader() : loader, ClassLoader.class);
+ // make sure the class loader is non-volatile, so it survives restarts.
+ componentLookup.get(ClassLoader.class.getName()).nonVolatile = true;
+ }
+
+ /**
+ * This is hard coded for now, since scanning the classpath for factories annotated with {@link org.jboss.cache.factories.annotations.DefaultFactoryFor}
+ * does not work with all class loaders. This is a temporary solution until a more elegant one can be designed.
+ * <p/>
+ * BE SURE TO ADD ANY NEW FACTORY TYPES ANNOTATED WITH DefaultFactoryFor TO THIS SET!!
+ * <p/>
+ *
+ * @return set of known factory types.
+ */
+ private Set<Class<? extends ComponentFactory>> getHardcodedFactories()
+ {
+ Set<Class<? extends ComponentFactory>> s = new HashSet<Class<? extends ComponentFactory>>();
+ s.add(BootstrapFactory.class);
+ s.add(BuddyManagerFactory.class);
+ s.add(EmptyConstructorFactory.class);
+ s.add(InterceptorChainFactory.class);
+ s.add(RuntimeConfigAwareFactory.class);
+ s.add(TransactionManagerFactory.class);
+ s.add(ReplicationQueueFactory.class);
+ return s;
+ }
+
+ /**
+ * Registers a component in the registry under the given type, and injects any dependencies needed. If a component
+ * of this type already exists, it is overwritten.
+ *
+ * @param component component to register
+ * @param type type of component
+ */
+ public void registerComponent(Object component, Class type)
+ {
+ Component c = new Component();
+ String name = type.getName();
+ c.name = name;
+ c.nonVolatile = component.getClass().isAnnotationPresent(NonVolatile.class);
+ c.instance = component;
+ Component old = componentLookup.get(name);
+
+ if (old != null)
+ {
+ // if they are equal don't bother
+ if (old.instance.equals(component))
+ {
+ if (trace)
+ log.trace("Attempting to register a component equal to one that already exists under the same name (" + name + "). Not doing anything.");
+ return;
+ }
+ }
+
+ if (trace) log.trace("Registering component " + c + " under name " + name);
+
+ if (old != null)
+ {
+ if (trace) log.trace("Replacing old component " + old);
+ old.instance = component;
+ }
+ else
+ {
+ componentLookup.put(name, c);
+ }
+ addComponentDependencies(c);
+ // inject dependencies for this component
+ c.injectDependencies();
+ }
+
+ /**
+ * Adds component dependencies for a given component, by populating {@link Component#injectionMethods}.
+ *
+ * @param c component to add dependencies to
+ */
+ protected void addComponentDependencies(Component c)
+ {
+ Class type = c.instance.getClass();
+ List<CachedMethod> methods = ReflectionUtil.getAllCachedMethods(type, Inject.class);
+
+ for (CachedMethod m : methods) c.injectionMethods.add(m);
+ }
+
+ @SuppressWarnings("unchecked")
+ protected void invokeInjectionMethod(Object o, CachedMethod m)
+ {
+ Class[] dependencies = m.getParameterTypes();
+ Object[] params = new Object[dependencies.length];
+
+ for (int i = 0; i < dependencies.length; i++)
+ {
+ params[i] = getOrCreateComponent(dependencies[i]);
+ }
+
+ ReflectionUtil.invokeAccessibly(o, m.getMethod(), params);
+ }
+
+ /**
+ * Retrieves a component if one exists, and if not, attempts to find a factory capable of constructing the component
+ * (factories annotated with the {@link DefaultFactoryFor} annotation that is capable of creating the component class).
+ * <p/>
+ * If an instance needs to be constructed, dependencies are then automatically wired into the instance, based on methods
+ * on the component type annotated with {@link Inject}.
+ * <p/>
+ * Summing it up, component retrieval happens in the following order:<br />
+ * 1. Look for a component that has already been created and registered.
+ * 2. Look for an appropriate component that exists in the {@link Configuration} that may be injected from an external system.
+ * 3. Look for a class definition passed in to the {@link org.jboss.cache.config.Configuration} - such as an EvictionPolicy implementation
+ * 4. Attempt to create it by looking for an appropriate factory (annotated with {@link DefaultFactoryFor})
+ * <p/>
+ *
+ * @param componentClass type of component to be retrieved. Should not be null.
+ * @return a fully wired component instance, or null if one cannot be found or constructed.
+ * @throws ConfigurationException if there is a problem with consructing or wiring the instance.
+ */
+ protected <T> T getOrCreateComponent(Class<T> componentClass)
+ {
+
+ T component = getComponent(componentClass);
+
+ if (component == null)
+ {
+ // first see if this has been injected externally.
+ component = getFromConfiguration(componentClass);
+ boolean attemptedFactoryConstruction = false;
+
+ if (component == null)
+ {
+ // create this component and add it to the registry
+ ComponentFactory factory = getFactory(componentClass);
+ component = factory.construct(componentClass);
+ attemptedFactoryConstruction = true;
+
+ }
+
+ if (component != null)
+ {
+ registerComponent(component, componentClass);
+ }
+ else if (attemptedFactoryConstruction)
+ {
+ if (trace) log.trace("Registering a null for component " + componentClass.getSimpleName());
+ registerNullComponent(componentClass);
+ }
+ }
+
+ return component;
+ }
+
+ /**
+ * Retrieves a component factory instance capable of constructing components of a specified type. If the factory doesn't
+ * exist in the registry, one is created.
+ *
+ * @param componentClass type of component to construct
+ * @return component factory capable of constructing such components
+ */
+ protected ComponentFactory getFactory(Class componentClass)
+ {
+ if (defaultFactories == null) scanDefaultFactories();
+ Class<? extends ComponentFactory> cfClass = defaultFactories.get(componentClass);
+ if (cfClass == null)
+ throw new ConfigurationException("No registered default factory for component " + componentClass + " found!");
+ // a component factory is a component too! See if one has been created and exists in the registry
+ ComponentFactory cf = getComponent(cfClass);
+ if (cf == null)
+ {
+ // hasn't yet been created. Create and put in registry
+ cf = instantiateFactory(cfClass);
+ if (cf != null)
+ {
+ // we simply register this factory. Registration will take care of constructing any dependencies.
+ registerComponent(cf, cfClass);
+ }
+ }
+
+ if (cf == null)
+ throw new ConfigurationException("Unable to locate component factory for component " + componentClass);
+
+ // ensure the component factory is in the STARTED state!
+ Component c = componentLookup.get(cfClass.getName());
+ if (c.instance != cf)
+ throw new ConfigurationException("Component factory " + cfClass + " incorrectly registered!");
+ return cf;
+ }
+
+ /**
+ * Scans the class path for classes annotated with {@link org.jboss.cache.factories.annotations.DefaultFactoryFor}, and
+ * analyses which components can be created by such factories.
+ */
+ void scanDefaultFactories()
+ {
+ defaultFactories = new HashMap<Class, Class<? extends ComponentFactory>>();
+
+ Set<Class<? extends ComponentFactory>> factories = getHardcodedFactories();
+
+ for (Class<? extends ComponentFactory> factory : factories)
+ {
+ DefaultFactoryFor dFFAnnotation = factory.getAnnotation(DefaultFactoryFor.class);
+ for (Class targetClass : dFFAnnotation.classes()) defaultFactories.put(targetClass, factory);
+ }
+ }
+
+ /**
+ * No such thing as a meta factory yet. Factories are created using this method which attempts to use an empty public
+ * constructor.
+ *
+ * @param factory class of factory to be created
+ * @return factory instance
+ */
+ ComponentFactory instantiateFactory(Class<? extends ComponentFactory> factory)
+ {
+ try
+ {
+ return factory.newInstance();
+ }
+ catch (Exception e)
+ {
+ // unable to get a hold of an instance!!
+ throw new ConfigurationException("Unable to instantiate factory " + factory, e);
+ }
+ }
+
+ /**
+ * registers a special "null" component that has no dependencies.
+ *
+ * @param type type of component to register as a null
+ */
+ void registerNullComponent(Class type)
+ {
+ registerComponent(NULL_COMPONENT, type);
+ }
+
+ /**
+ * Retrieves a component from the {@link Configuration} or {@link RuntimeConfig}.
+ *
+ * @param componentClass component type
+ * @return component, or null if it cannot be found
+ */
+ @SuppressWarnings("unchecked")
+ protected <T> T getFromConfiguration(Class<T> componentClass)
+ {
+ if (log.isDebugEnabled())
+ log.debug("Looking in configuration for an instance of " + componentClass + " that may have been injected from an external source.");
+ Method getter = BeanUtils.getterMethod(Configuration.class, componentClass);
+ T returnValue = null;
+
+ if (getter != null)
+ {
+ try
+ {
+ returnValue = (T) getter.invoke(getConfiguration());
+ }
+ catch (Exception e)
+ {
+ log.warn("Unable to invoke getter " + getter + " on Configuration.class!", e);
+ }
+ }
+
+ // now try the RuntimeConfig - a legacy "registry" of sorts.
+ if (returnValue == null)
+ {
+ getter = BeanUtils.getterMethod(RuntimeConfig.class, componentClass);
+ if (getter != null)
+ {
+ try
+ {
+ returnValue = (T) getter.invoke(getConfiguration().getRuntimeConfig());
+ }
+ catch (Exception e)
+ {
+ log.warn("Unable to invoke getter " + getter + " on RuntimeConfig.class!", e);
+ }
+ }
+ }
+ return returnValue;
+ }
+
+ /**
+ * Retrieves the configuration component.
+ *
+ * @return a Configuration object
+ */
+ protected Configuration getConfiguration()
+ {
+ // this is assumed to always be present as a part of the bootstrap/construction of a ComponentRegistry.
+ return getComponent(Configuration.class);
+ }
+
+ /**
+ * Retrieves a component of a specified type from the registry, or null if it cannot be found.
+ *
+ * @param type type to find
+ * @return component, or null
+ */
+ @SuppressWarnings("unchecked")
+ public <T> T getComponent(Class<T> type)
+ {
+ Component wrapper = componentLookup.get(type.getName());
+ if (wrapper == null) return null;
+
+ return (T) (wrapper.instance == NULL_COMPONENT ? null : wrapper.instance);
+ }
+
+ /**
+ * Marks state as wired. Used by the DefaultCacheFactory after it has added the BootstrapFactory and CacheSPI components.
+ */
+ public void wire()
+ {
+ state = CacheStatus.CREATED;
+ }
+
+ /**
+ * Rewires components. Can only be called if the current state is WIRED or STARTED.
+ */
+ public void rewire()
+ {
+ // need to re-inject everything again.
+ for (Component c : new HashSet<Component>(componentLookup.values()))
+ {
+ // inject dependencies for this component
+ c.injectDependencies();
+ }
+ }
+
+ /**
+ * Scans each registered component for lifecycle methods, and adds them to the appropriate lists, and then sorts them
+ * by priority.
+ */
+ private void populateLifecycleMethods()
+ {
+ // cache a list of the start annotated methods
+ startMethods.clear();
+ for (Component c : componentLookup.values())
+ {
+ List<Method> methods = ReflectionUtil.getAllMethods(c.instance.getClass(), Start.class);
+ for (Method m : methods)
+ {
+ PrioritizedMethod em = new PrioritizedMethod();
+ em.component = c;
+ em.method = m;
+ em.priority = m.getAnnotation(Start.class).priority();
+ startMethods.add(em);
+ }
+ }
+
+ // cache a list of the stop annotated methods
+ stopMethods.clear();
+ for (Component c : componentLookup.values())
+ {
+ List<Method> methods = ReflectionUtil.getAllMethods(c.instance.getClass(), Stop.class);
+ for (Method m : methods)
+ {
+ PrioritizedMethod em = new PrioritizedMethod();
+ em.component = c;
+ em.method = m;
+ em.priority = m.getAnnotation(Stop.class).priority();
+ stopMethods.add(em);
+ }
+ }
+
+ // cache a list of the destroy annotated methods
+ destroyMethods.clear();
+ for (Component c : componentLookup.values())
+ {
+ List<Method> methods = ReflectionUtil.getAllMethods(c.instance.getClass(), Destroy.class);
+ for (Method m : methods)
+ {
+ PrioritizedMethod em = new PrioritizedMethod();
+ em.component = c;
+ em.method = m;
+ em.priority = m.getAnnotation(Destroy.class).priority();
+ destroyMethods.add(em);
+ }
+ }
+
+ Collections.sort(startMethods);
+ Collections.sort(stopMethods);
+ Collections.sort(destroyMethods);
+ }
+
+ /**
+ * Removes any components not annotated as @NonVolatile.
+ */
+ public void resetNonVolatile()
+ {
+ // destroy all components to clean up resources
+ for (Component c : new HashSet<Component>(componentLookup.values()))
+ {
+ // the component is volatile!!
+ if (!c.nonVolatile)
+ {
+ componentLookup.remove(c.name);
+ }
+ }
+
+ if (trace) log.trace("Reset volatile components");
+ }
+
+ // ------------------------------ START: Publicly available lifecycle methods -----------------------------
+ // These methods perform a check for appropriate transition and then delegate to similarly named internal methods.
+
+ /**
+ * Creates the components needed by a cache instance and sets the cache status to {@link org.jboss.cache.CacheStatus#CREATED}
+ * when it is done.
+ */
+ public void create()
+ {
+ if (!state.createAllowed())
+ {
+ if (state.needToDestroyFailedCache())
+ destroy();
+ else
+ return;
+ }
+
+ try
+ {
+ internalCreate();
+ }
+ catch (Throwable t)
+ {
+ handleLifecycleTransitionFailure(t);
+ }
+ }
+
+ /**
+ * This starts the components in the cache, connecting to channels, starting service threads, etc. If the cache is
+ * not in the {@link org.jboss.cache.CacheStatus#CREATED} state, {@link #create()} will be invoked first.
+ */
+ public void start()
+ {
+ boolean createdInStart = false;
+ if (!state.startAllowed())
+ {
+ if (state.needToDestroyFailedCache())
+ destroy(); // this will take us back to DESTROYED
+
+ if (state.needCreateBeforeStart())
+ {
+ create();
+ createdInStart = true;
+ }
+ else
+ return;
+ }
+
+ try
+ {
+ internalStart(createdInStart);
+ }
+ catch (Throwable t)
+ {
+ handleLifecycleTransitionFailure(t);
+ }
+ }
+
+ /**
+ * Stops the cache and sets the cache status to {@link org.jboss.cache.CacheStatus#STOPPED} once it is done. If the cache is not in
+ * the {@link org.jboss.cache.CacheStatus#STARTED} state, this is a no-op.
+ */
+ public void stop()
+ {
+ if (!state.stopAllowed())
+ {
+ return;
+ }
+
+ // Trying to stop() from FAILED is valid, but may not work
+ boolean failed = state == CacheStatus.FAILED;
+
+ try
+ {
+ internalStop();
+ }
+ catch (Throwable t)
+ {
+ if (failed)
+ {
+ log.warn("Attempted to stop() from FAILED state, but caught exception; try calling destroy()", t);
+ }
+ handleLifecycleTransitionFailure(t);
+ }
+ finally
+ {
+ if (!failed) state = CacheStatus.STOPPED;
+ }
+ }
+
+ /**
+ * Destroys the cache and frees up any resources. Sets the cache status to {@link CacheStatus#DESTROYED} when it is done.
+ * <p/>
+ * If the cache is in {@link org.jboss.cache.CacheStatus#STARTED} when this method is called, it will first call {@link #stop()}
+ * to stop the cache.
+ */
+ public void destroy()
+ {
+ if (!state.destroyAllowed())
+ {
+ if (state.needStopBeforeDestroy())
+ {
+ try
+ {
+ stop();
+ }
+ catch (CacheException e)
+ {
+ log.warn("Needed to call stop() before destroying but stop() threw exception. Proceeding to destroy", e);
+ }
+ }
+ else
+ return;
+ }
+
+ try
+ {
+ internalDestroy();
+ }
+ finally
+ {
+ // We always progress to destroyed
+ state = CacheStatus.DESTROYED;
+ }
+ }
+ // ------------------------------ END: Publicly available lifecycle methods -----------------------------
+
+ // ------------------------------ START: Actual internal lifecycle methods --------------------------------
+
+ /**
+ * Sets the cacheStatus to FAILED and rethrows the problem as one
+ * of the declared types. Converts any non-RuntimeException Exception
+ * to CacheException.
+ *
+ * @param t throwable thrown during failure
+ */
+ private void handleLifecycleTransitionFailure(Throwable t)
+ {
+ state = CacheStatus.FAILED;
+ if (t instanceof CacheException)
+ throw (CacheException) t;
+ else if (t instanceof RuntimeException)
+ throw (RuntimeException) t;
+ else if (t instanceof Error)
+ throw (Error) t;
+ else
+ throw new CacheException(t);
+ }
+
+ /**
+ * The actual create implementation.
+ */
+ private void internalCreate()
+ {
+ state = CacheStatus.CREATING;
+ resetNonVolatile();
+ rewire();
+ state = CacheStatus.CREATED;
+ }
+
+ private void internalStart(boolean createdInStart) throws CacheException, IllegalArgumentException
+ {
+ if (!createdInStart)
+ {
+ // re-wire all dependencies in case stuff has changed since the cache was created
+ // remove any components whose construction may have depended upon a configuration that may have changed.
+ resetNonVolatile();
+ rewire();
+ }
+
+ state = CacheStatus.STARTING;
+
+ // start all internal components
+ // first cache all start, stop and destroy methods.
+ populateLifecycleMethods();
+
+ // fire all START methods according to priority
+ for (PrioritizedMethod em : startMethods) em.invoke();
+
+ addShutdownHook();
+
+ log.info("JBoss Cache version: " + Version.printVersion());
+ state = CacheStatus.STARTED;
+ }
+
+ private void addShutdownHook()
+ {
+ ArrayList al = MBeanServerFactory.findMBeanServer(null);
+ boolean registerShutdownHook = (getConfiguration().getShutdownHookBehavior() == Configuration.ShutdownHookBehavior.DEFAULT && al.size() == 0)
+ || getConfiguration().getShutdownHookBehavior() == Configuration.ShutdownHookBehavior.REGISTER;
+
+ if (registerShutdownHook)
+ {
+ if (log.isTraceEnabled())
+ log.trace("Registering a shutdown hook. Configured behavior = " + getConfiguration().getShutdownHookBehavior());
+ shutdownHook = new Thread()
+ {
+ @Override
+ public void run()
+ {
+ try
+ {
+ invokedFromShutdownHook = true;
+ ComponentRegistry.this.stop();
+ }
+ finally
+ {
+ invokedFromShutdownHook = false;
+ }
+ }
+ };
+
+ Runtime.getRuntime().addShutdownHook(shutdownHook);
+ }
+ else
+ {
+ if (log.isTraceEnabled())
+ log.trace("Not registering a shutdown hook. Configured behavior = " + getConfiguration().getShutdownHookBehavior());
+ }
+ }
+
+ /**
+ * Actual stop
+ */
+ private void internalStop()
+ {
+ state = CacheStatus.STOPPING;
+ // if this is called from a source other than the shutdown hook, deregister the shutdown hook.
+ if (!invokedFromShutdownHook && shutdownHook != null) Runtime.getRuntime().removeShutdownHook(shutdownHook);
+
+ // fire all STOP methods according to priority
+ for (PrioritizedMethod em : stopMethods) em.invoke();
+
+ state = CacheStatus.STOPPED;
+ }
+
+ /**
+ * Actual destroy
+ */
+ private void internalDestroy()
+ {
+
+ state = CacheStatus.DESTROYING;
+
+ resetNonVolatile();
+
+ // fire all DESTROY methods according to priority
+ for (PrioritizedMethod em : destroyMethods) em.invoke();
+
+ state = CacheStatus.DESTROYED;
+ }
+
+ // ------------------------------ END: Actual internal lifecycle methods --------------------------------
+
+ /**
+ * Asserts whether invocations are allowed on the cache or not. Returns <tt>true</tt> if invocations are to be allowed,
+ * <tt>false</tt> otherwise. If the origin of the call is remote and the cache status is {@link org.jboss.cache.CacheStatus#STARTING},
+ * this method will block for up to {@link org.jboss.cache.config.Configuration#getStateRetrievalTimeout()} millis, checking
+ * for a valid state.
+ *
+ * @param originLocal true if the call originates locally (i.e., from the {@link org.jboss.cache.invocation.CacheInvocationDelegate} or false if it originates remotely, i.e., from the {@link org.jboss.cache.marshall.CommandAwareRpcDispatcher}.
+ * @return true if invocations are allowed, false otherwise.
+ */
+ public boolean invocationsAllowed(boolean originLocal)
+ {
+ log.trace("Testing if invocations are allowed.");
+ if (state.allowInvocations()) return true;
+
+ // if this is a locally originating call and the cache is not in a valid state, return false.
+ if (originLocal) return false;
+
+ log.trace("Is remotely originating.");
+
+ // else if this is a remote call and the status is STARTING, wait until the cache starts.
+ if (state == CacheStatus.STARTING)
+ {
+ log.trace("Cache is starting; block.");
+ try
+ {
+ blockUntilCacheStarts();
+ return true;
+ }
+ catch (InterruptedException e)
+ {
+ Thread.currentThread().interrupt();
+ }
+ }
+ else
+ {
+ log.warn("Received a remote call but the cache is not in STARTED state - ignoring call.");
+ }
+ return false;
+ }
+
+ /**
+ * Blocks until the current cache instance is in it's {@link org.jboss.cache.CacheStatus#STARTED started} phase. Blocks
+ * for up to {@link org.jboss.cache.config.Configuration#getStateRetrievalTimeout()} milliseconds, throwing an IllegalStateException
+ * if the cache doesn't reach this state even after this maximum wait time.
+ *
+ * @throws InterruptedException if interrupted while waiting
+ * @throws IllegalStateException if even after waiting the cache has not started.
+ */
+ private void blockUntilCacheStarts() throws InterruptedException, IllegalStateException
+ {
+ int pollFrequencyMS = 100;
+ long startupWaitTime = getConfiguration().getStateRetrievalTimeout();
+ long giveUpTime = System.currentTimeMillis() + startupWaitTime;
+
+ while (System.currentTimeMillis() < giveUpTime)
+ {
+ if (state.allowInvocations()) break;
+ Thread.sleep(pollFrequencyMS);
+ }
+
+ // check if we have started.
+ if (!state.allowInvocations())
+ throw new IllegalStateException("Cache not in STARTED state, even after waiting " + getConfiguration().getStateRetrievalTimeout() + " millis.");
+ }
+
+ /**
+ * A wrapper representing a component in the registry
+ */
+ public class Component
+ {
+ /**
+ * A reference to the object instance for this component.
+ */
+ Object instance;
+ /**
+ * The name of the component
+ */
+ String name;
+ /**
+ * List of injection methods used to inject dependencies into the component
+ */
+ List<CachedMethod> injectionMethods = new LinkedList<CachedMethod>();
+ /**
+ * If true, then this component is not flushed before starting the ComponentRegistry.
+ */
+ boolean nonVolatile;
+
+ @Override
+ public String toString()
+ {
+ return "Component{" +
+ "instance=" + instance +
+ ", name=" + name +
+ ", nonVolatile=" + nonVolatile +
+ '}';
+ }
+
+ /**
+ * Injects dependencies into this component.
+ */
+ public void injectDependencies()
+ {
+ for (CachedMethod m : injectionMethods) invokeInjectionMethod(instance, m);
+ }
+ }
+
+
+ /**
+ * Wrapper to encapsulate a method along with a priority
+ */
+ class PrioritizedMethod implements Comparable<PrioritizedMethod>
+ {
+ Method method;
+ Component component;
+ int priority;
+
+ public int compareTo(PrioritizedMethod o)
+ {
+ return (priority < o.priority ? -1 : (priority == o.priority ? 0 : 1));
+ }
+
+ void invoke()
+ {
+ ReflectionUtil.invokeAccessibly(component.instance, method, null);
+ }
+ }
+}
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java 2008-05-08 09:04:25 UTC (rev 5804)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java 2008-05-08 09:06:54 UTC (rev 5805)
@@ -29,7 +29,7 @@
import org.jboss.cache.config.Configuration;
import org.jboss.cache.config.Option;
import org.jboss.cache.factories.CommandsFactory;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.invocation.InvocationContextContainer;
import org.jboss.cache.notifications.Notifier;
@@ -67,7 +67,7 @@
private RPCManager rpcManager;
private Notifier notifier;
private InvocationContextContainer invocationContextContainer;
- private ComponentKernel componentRegistry;
+ private ComponentRegistry componentRegistry;
private final ModificationsReplayVisitor replayVisitorNoInject = new ModificationsReplayVisitor(false);
private final ModificationsReplayVisitor replayVisitorWithInject = new ModificationsReplayVisitor(true);
@@ -84,7 +84,7 @@
@Inject
public void intialize(RPCManager rpcManager,
Notifier notifier, InvocationContextContainer icc,
- CommandsFactory factory, ComponentKernel componentRegistry)
+ CommandsFactory factory, ComponentRegistry componentRegistry)
{
this.commandsFactory = factory;
this.rpcManager = rpcManager;
Modified: core/trunk/src/main/java/org/jboss/cache/invocation/AbstractInvocationDelegate.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/invocation/AbstractInvocationDelegate.java 2008-05-08 09:04:25 UTC (rev 5804)
+++ core/trunk/src/main/java/org/jboss/cache/invocation/AbstractInvocationDelegate.java 2008-05-08 09:06:54 UTC (rev 5805)
@@ -3,7 +3,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.interceptors.InterceptorChain;
@@ -26,7 +26,7 @@
protected Configuration configuration;
protected InvocationContextContainer invocationContextContainer;
- protected ComponentKernel componentRegistry;
+ protected ComponentRegistry componentRegistry;
protected InterceptorChain invoker;
protected boolean originLocal = true;
@@ -36,7 +36,7 @@
*/
@Inject
public void initialize(Configuration configuration, InvocationContextContainer invocationContextContainer,
- ComponentKernel componentRegistry, InterceptorChain interceptorChain)
+ ComponentRegistry componentRegistry, InterceptorChain interceptorChain)
{
this.configuration = configuration;
this.invocationContextContainer = invocationContextContainer;
Modified: core/trunk/src/main/java/org/jboss/cache/marshall/CommandAwareRpcDispatcher.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/marshall/CommandAwareRpcDispatcher.java 2008-05-08 09:04:25 UTC (rev 5804)
+++ core/trunk/src/main/java/org/jboss/cache/marshall/CommandAwareRpcDispatcher.java 2008-05-08 09:06:54 UTC (rev 5805)
@@ -6,7 +6,7 @@
import org.jboss.cache.commands.remote.AnnounceBuddyPoolNameCommand;
import org.jboss.cache.commands.remote.AssignToBuddyGroupCommand;
import org.jboss.cache.commands.remote.RemoveFromBuddyGroupCommand;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.interceptors.InterceptorChain;
import org.jboss.cache.invocation.InvocationContextContainer;
import org.jgroups.Address;
@@ -32,12 +32,12 @@
{
protected InvocationContextContainer invocationContextContainer;
protected InterceptorChain interceptorChain;
- protected ComponentKernel componentRegistry;
+ protected ComponentRegistry componentRegistry;
protected boolean trace;
public CommandAwareRpcDispatcher(Channel channel, MessageListener l, MembershipListener l2, Object server_obj,
InvocationContextContainer container, InterceptorChain interceptorChain,
- ComponentKernel componentRegistry)
+ ComponentRegistry componentRegistry)
{
super(channel, l, l2, server_obj);
this.invocationContextContainer = container;
Modified: core/trunk/src/main/java/org/jboss/cache/marshall/InactiveRegionAwareRpcDispatcher.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/marshall/InactiveRegionAwareRpcDispatcher.java 2008-05-08 09:04:25 UTC (rev 5804)
+++ core/trunk/src/main/java/org/jboss/cache/marshall/InactiveRegionAwareRpcDispatcher.java 2008-05-08 09:06:54 UTC (rev 5805)
@@ -1,7 +1,7 @@
package org.jboss.cache.marshall;
import org.jboss.cache.commands.ReplicableCommand;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.interceptors.InterceptorChain;
import org.jboss.cache.invocation.InvocationContextContainer;
import org.jgroups.Channel;
@@ -25,7 +25,7 @@
*/
public InactiveRegionAwareRpcDispatcher(Channel channel, MessageListener l, MembershipListener l2, Object serverObj,
InvocationContextContainer container, InterceptorChain interceptorChain,
- ComponentKernel componentRegistry)
+ ComponentRegistry componentRegistry)
{
super(channel, l, l2, serverObj, container, interceptorChain, componentRegistry);
}
Modified: core/trunk/src/main/java/org/jboss/cache/marshall/VersionAwareMarshaller.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/marshall/VersionAwareMarshaller.java 2008-05-08 09:04:25 UTC (rev 5804)
+++ core/trunk/src/main/java/org/jboss/cache/marshall/VersionAwareMarshaller.java 2008-05-08 09:06:54 UTC (rev 5805)
@@ -9,7 +9,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.Fqn;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.factories.annotations.Start;
import org.jboss.cache.util.Util;
@@ -41,14 +41,14 @@
private static final int VERSION_220 = 22;
private static final int CUSTOM_MARSHALLER = 999;
- private ComponentKernel componentRegistry;
+ private ComponentRegistry componentRegistry;
Marshaller defaultMarshaller;
final Map<Integer, Marshaller> marshallers = new HashMap<Integer, Marshaller>();
private int versionInt;
@Inject
- void injectComponents(ComponentKernel componentRegistry)
+ void injectComponents(ComponentRegistry componentRegistry)
{
this.componentRegistry = componentRegistry;
}
Modified: core/trunk/src/test/java/org/jboss/cache/factories/LifeCycleTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/factories/LifeCycleTest.java 2008-05-08 09:04:25 UTC (rev 5804)
+++ core/trunk/src/test/java/org/jboss/cache/factories/LifeCycleTest.java 2008-05-08 09:06:54 UTC (rev 5805)
@@ -261,7 +261,7 @@
{
// now DIRECTLY change the status of c2.
// emulate the race condition where the remote cache is stopping but hasn't disconnected from the channel.
- ComponentKernel cr1 = TestingUtil.extractComponentRegistry(c[1]);
+ ComponentRegistry cr1 = TestingUtil.extractComponentRegistry(c[1]);
cr1.state = CacheStatus.STOPPING;
// Thanks to JBCACHE-1179, this should only log a warning and not throw an exception
@@ -270,7 +270,7 @@
finally
{
// reset c[1] to running so the tearDown method can clean it up
- ComponentKernel cr1 = TestingUtil.extractComponentRegistry(c[1]);
+ ComponentRegistry cr1 = TestingUtil.extractComponentRegistry(c[1]);
cr1.state = CacheStatus.STARTED;
}
}
@@ -288,7 +288,7 @@
// there is a lousy race condition here - we need to make sure cache[1]'s start() method doesn't set status to STARTED
// after we attempt to change this.
TestingUtil.blockUntilCacheStatusAchieved(c[1], CacheStatus.STARTED, 1000);
- ComponentKernel cr1 = TestingUtil.extractComponentRegistry(c[1]);
+ ComponentRegistry cr1 = TestingUtil.extractComponentRegistry(c[1]);
cr1.state = CacheStatus.STARTING;
try
{
@@ -308,7 +308,7 @@
public void run()
{
TestingUtil.sleepThread(sleepTime);
- ComponentKernel cr1 = TestingUtil.extractComponentRegistry(c[1]);
+ ComponentRegistry cr1 = TestingUtil.extractComponentRegistry(c[1]);
cr1.state = CacheStatus.STARTED;
}
}.start();
@@ -322,7 +322,7 @@
finally
{
// reset c[1] to running so the tearDown method can clean it up
- ComponentKernel cr1 = TestingUtil.extractComponentRegistry(c[1]);
+ ComponentRegistry cr1 = TestingUtil.extractComponentRegistry(c[1]);
cr1.state = CacheStatus.STARTED;
}
}
@@ -335,7 +335,7 @@
c[0].put(Fqn.ROOT, "k2", "v2");
// now DIRECTLY change the status of c.
- ComponentKernel cr0 = TestingUtil.extractComponentRegistry(c[0]);
+ ComponentRegistry cr0 = TestingUtil.extractComponentRegistry(c[0]);
cr0.state = CacheStatus.STOPPING;
try
@@ -414,7 +414,7 @@
c[0].put(Fqn.ROOT, "k2", "v2");
// now DIRECTLY change the status of c.
- ComponentKernel cr0 = TestingUtil.extractComponentRegistry(c[0]);
+ ComponentRegistry cr0 = TestingUtil.extractComponentRegistry(c[0]);
cr0.state = CacheStatus.STOPPING;
// rollbacks should just log a message
Modified: core/trunk/src/test/java/org/jboss/cache/marshall/AbstractVersionAwareMarshallerTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/marshall/AbstractVersionAwareMarshallerTest.java 2008-05-08 09:04:25 UTC (rev 5804)
+++ core/trunk/src/test/java/org/jboss/cache/marshall/AbstractVersionAwareMarshallerTest.java 2008-05-08 09:06:54 UTC (rev 5805)
@@ -4,7 +4,7 @@
import org.jboss.cache.RegionManager;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.factories.CommandsFactory;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
/**
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
@@ -12,7 +12,7 @@
*/
public abstract class AbstractVersionAwareMarshallerTest
{
- protected ComponentKernel cr;
+ protected ComponentRegistry cr;
protected VersionAwareMarshaller createVAMandRestartCache(String replVersion)
{
Modified: core/trunk/src/test/java/org/jboss/cache/misc/TestingUtil.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/misc/TestingUtil.java 2008-05-08 09:04:25 UTC (rev 5804)
+++ core/trunk/src/test/java/org/jboss/cache/misc/TestingUtil.java 2008-05-08 09:06:54 UTC (rev 5805)
@@ -13,7 +13,7 @@
import org.jboss.cache.Fqn;
import org.jboss.cache.commands.VisitableCommand;
import org.jboss.cache.factories.CommandsFactory;
-import org.jboss.cache.factories.ComponentKernel;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.interceptors.InterceptorChain;
import org.jboss.cache.interceptors.base.CommandInterceptor;
import org.jboss.cache.invocation.CacheInvocationDelegate;
@@ -471,9 +471,9 @@
* @param cache cache to introspect
* @return component registry
*/
- public static ComponentKernel extractComponentRegistry(Cache cache)
+ public static ComponentRegistry extractComponentRegistry(Cache cache)
{
- return (ComponentKernel) extractField(cache, "componentRegistry");
+ return (ComponentRegistry) extractField(cache, "componentRegistry");
}
/**
@@ -482,9 +482,9 @@
* @param ci interceptor chain to introspect
* @return component registry
*/
- public static ComponentKernel extractComponentRegistry(InterceptorChain ci)
+ public static ComponentRegistry extractComponentRegistry(InterceptorChain ci)
{
- return (ComponentKernel) extractField(ci, "componentRegistry");
+ return (ComponentRegistry) extractField(ci, "componentRegistry");
}
@@ -497,7 +497,7 @@
*/
public static void replaceInterceptorChain(CacheSPI<?, ?> cache, CommandInterceptor interceptor)
{
- ComponentKernel cr = extractComponentRegistry(cache);
+ ComponentRegistry cr = extractComponentRegistry(cache);
// make sure all interceptors here are wired.
CommandInterceptor i = interceptor;
do
@@ -519,7 +519,7 @@
*/
public static CacheInvocationDelegate getInvocationDelegate(CacheSPI cache)
{
- ComponentKernel cr = extractComponentRegistry(cache);
+ ComponentRegistry cr = extractComponentRegistry(cache);
return cr.getComponent(CacheInvocationDelegate.class);
}
@@ -544,7 +544,7 @@
public static void replicateCommand(CacheSPI cache, VisitableCommand command) throws Throwable
{
- ComponentKernel cr = extractComponentRegistry(cache);
+ ComponentRegistry cr = extractComponentRegistry(cache);
InterceptorChain ic = cr.getComponent(InterceptorChain.class);
ic.invoke(command);
}
16 years, 7 months
JBoss Cache SVN: r5804 - core/trunk/src/main/java/org/jboss/cache/factories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-05-08 05:04:25 -0400 (Thu, 08 May 2008)
New Revision: 5804
Removed:
core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java
Log:
Deleted: core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java 2008-05-08 08:50:28 UTC (rev 5803)
+++ core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java 2008-05-08 09:04:25 UTC (rev 5804)
@@ -1,1016 +0,0 @@
-package org.jboss.cache.factories;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.cache.Cache;
-import org.jboss.cache.CacheSPI;
-import org.jboss.cache.DataContainer;
-import org.jboss.cache.LifecycleManager;
-import org.jboss.cache.config.Configuration;
-import org.jboss.cache.config.ConfigurationException;
-import org.jboss.cache.config.RuntimeConfig;
-import static org.jboss.cache.factories.ComponentRegistry.State.*;
-import org.jboss.cache.factories.annotations.CacheInjectionMethods;
-import org.jboss.cache.factories.annotations.ComponentName;
-import org.jboss.cache.factories.annotations.DefaultFactoryFor;
-import org.jboss.cache.factories.annotations.Destroy;
-import org.jboss.cache.factories.annotations.Inject;
-import org.jboss.cache.factories.annotations.Start;
-import org.jboss.cache.factories.annotations.Stop;
-import org.jboss.cache.interceptors.InterceptorChain;
-import org.jboss.cache.util.BeanUtils;
-import org.jboss.cache.util.reflect.CachedMethod;
-import org.jboss.cache.util.reflect.ReflectionUtil;
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * A registry where components which have been created are stored. Components are stored as singletons, registered under
- * a specific name. When retrieving components from the registry, callers may specify a component name or just the type
- * of component needed (in which case the fully qualified class name is used as the component name).
- * <p/>
- * Components can be retrieved from the registry using {@link #getComponent(Class)}, or they can be constructed using
- * {@link #getOrCreateComponent(String, Class)} which will scan for default factories and attempt to use such
- * factpries to create the component if needed.
- * <p/>
- * Default factories are treated as components too and will need to be wired and started before being used.
- * <p/>
- * Components can exist in one of 4 states, as defined by the {@link State} enumeration. The component registry also
- * has a state for the overall component set. While some components may move to the {@link org.jboss.cache.factories.ComponentRegistry.State#STARTED}
- * state before others (such as factories to create other components) the ComponentRegistry's overall state depicts the lowest
- * possible form for all components.
- * <p/>
- * In terms of the cache, overall state changes in the following manner:
- * <ul>
- * <li>CONSTRUCTED - when created using the DefaultCacheFactory</li>
- * <li>WIRED - when {@link org.jboss.cache.Cache#create()} is called</li>
- * <li>STARTED - when {@link org.jboss.cache.Cache#start()} is called</li>
- * <li>STOPPED - when {@link org.jboss.cache.Cache#stop()} is called</li>
- * </ul>
- * <p/>
- * Cache configuration can only be changed and will only be reinjected if the cache is not in the {@link org.jboss.cache.CacheStatus#STARTED} state.
- *
- * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
- * @since 2.1.0
- */
-public class ComponentRegistry
-{
- // TODO: 2.2.0: Needs refactoring
- //TODO: 2.2.x+ @Start annotation bug: BaseClass.start() and ChildrenClass.start() are annotated with @Start then only base class method is being called
- static final Object NULL_COMPONENT = new Object();
-
- State overallState = CONSTRUCTED;
-
- /**
- * The registry of components. Components are stored under their name.
- */
- final Map<String, Component> componentLookup = new HashMap<String, Component>();
-
- /**
- * Contains class definitions of component factories that can be used to construct certain components
- */
- Map<Class, Class<? extends ComponentFactory>> defaultFactories = null;
-
- private static final Log log = LogFactory.getLog(ComponentRegistry.class);
- private static final boolean trace = log.isTraceEnabled();
- private Bootstrap bootstrap;
-
- // cache of reflection methods to call during injections. These will be emptied when start() is called.
- Map<Class, List<CachedMethod>> shortTermMethodCache = null;
- // these will hang around longer - for components that are frequently created during normal operation.
- Map<Class, List<CachedMethod>> longTermMethodCache = null;
-
- /**
- * Creates an instance of the component registry. The configuration passed in is automatically registered.
- *
- * @param configuration
- */
- public ComponentRegistry(Configuration configuration)
- {
- // bootstrap.
- registerDefaultClassLoader(null);
- registerComponent(this, ComponentRegistry.class);
- registerComponent(configuration, Configuration.class);
- }
-
- /**
- * Registers the default class loader. This method *must* be called before any other components are registered,
- * typically called by bootstrap code. Defensively, it is called in the constructor of ComponentRegistry with a null
- * parameter.
- *
- * @param loader a class loader to use by default. If this is null, the class loader used to load this instance of ComponentRegistry is used.
- */
- public void registerDefaultClassLoader(ClassLoader loader)
- {
- registerComponent("deployerClassLoader", loader == null ? getClass().getClassLoader() : loader, ClassLoader.class);
- }
-
-
- public State getOverallState()
- {
- return overallState;
- }
-
- /**
- * This is hard coded for now, since scanning the classpath for factories annotated with {@link org.jboss.cache.factories.annotations.DefaultFactoryFor}
- * does not work with all class loaders. This is a temporary solution until a more elegant one can be designed.
- * <p/>
- * BE SURE TO ADD ANY NEW FACTORY TYPES ANNOTATED WITH DefaultFactoryFor TO THIS SET!!
- * <p/>
- *
- * @return set of known factory types.
- */
- private Set<Class<? extends ComponentFactory>> getHardcodedFactories()
- {
- Set<Class<? extends ComponentFactory>> s = new HashSet<Class<? extends ComponentFactory>>();
- s.add(BuddyManagerFactory.class);
- s.add(EmptyConstructorFactory.class);
- s.add(InterceptorChainFactory.class);
- s.add(RuntimeConfigAwareFactory.class);
- s.add(TransactionManagerFactory.class);
- s.add(ReplicationQueueFactory.class);
- return s;
- }
-
-
- /**
- * Adds a singleton instance to the registry. Note that if an instance of this component already exists in the
- * registry it is overwritten. The instance is registered under type <tt>component.getClass()</tt>. If the component
- * implements an interface or extends an abstract class, it may make more sense to use {@link #registerComponent(String, Object, Class)}
- * <p/>
- * The status of the component is updated th the overall state of the registry, which may involve calling of methods annotated
- * with {@link org.jboss.cache.factories.annotations.Inject}, {@link org.jboss.cache.factories.annotations.Start} or
- * {@link org.jboss.cache.factories.annotations.Stop}.
- * <p/>
- *
- * @param component component to add to the registry.
- */
- public void registerComponent(Object component, Class type)
- {
- registerComponent(type.getName(), component, type);
- }
-
- /**
- * Adds an instance component to the registry, registering the component under the given name. If an instance already
- * exists in the registry under the given name, it will be overwritten.
- * <p/>
- * The status of the component is updated th the overall state of the registry, which may involve calling of methods annotated
- * with {@link org.jboss.cache.factories.annotations.Inject}, {@link org.jboss.cache.factories.annotations.Start} or
- * {@link org.jboss.cache.factories.annotations.Stop}.
- * <p/>
- *
- * @param name name of the instance
- * @param component component to add
- */
- public void registerComponent(String name, Object component, Class type)
- {
- // this will make sure all dependent components are stopped or set to CONSTRUCTED so they can be re-wired later.
- Component c = new Component(name, component, type);
- Component old = componentLookup.get(name);
- if (trace)
- log.trace("Registering component " + c + " under name " + name + " replacing old component " + old);
- if (old != null)
- {
- // if they are equal don't bother
- if (old.instance.equals(component))
- {
- if (trace)
- log.trace("Attempting to register a component equal to one that already exists under the same name (" + name + "). Not doing anything.");
- return;
- }
- // unregister the old component so that components that depend on it can be stopped if necessary
- unregisterComponent(name);
- // components that depended on the old component should now depend on the new one.
- c.dependencyFor.addAll(old.dependencyFor);
- }
- componentLookup.put(name, c);
-
- addComponentDependencies(c, old == null);
-
- State stateToMoveTo = overallState == null ? CONSTRUCTED : overallState;
- c.changeState(stateToMoveTo);
-
- // make sure any other omponents that have inadvertently been stopped are now restarted.
- if (old != null)
- {
- for (Component comp : old.dependencyFor)
- {
- if (comp.state != stateToMoveTo) comp.changeState(stateToMoveTo);
- }
- }
- }
-
- protected void addComponentDependencies(Component c, boolean firstTimeAdded)
- {
- // build any dependent components if necessary
- for (Component d : c.dependencies)
- {
- getOrCreateComponent(d.name, d.type);
- Component dependencyComponent = componentLookup.get(d.name);
- if (dependencyComponent != null) dependencyComponent.dependencyFor.add(c);
- }
-
- if (firstTimeAdded)
- {
- // loop through all other components already registered and make sure the current component's dependencyFor map is accurate
- for (Component other : componentLookup.values())
- {
- if (other.dependencies.contains(c)) c.dependencyFor.add(other);
- }
- }
-
- }
-
- public <T> T getComponent(Class<T> c)
- {
- return getComponent(c.getName(), c);
- }
-
- /**
- * Retrieves a named component which can be assigned to the type passed in. Will return a null if no such component
- * is registered
- *
- * @param c type to be able to assign component to.
- * @return component, if found, or a null otherwise.
- */
- @SuppressWarnings("unchecked")
- public <T> T getComponent(String name, Class<T> c)
- {
- Component wrapper = componentLookup.get(name);
- if (wrapper == null) return null;
-
- T component = (T) (wrapper.instance == NULL_COMPONENT ? null : wrapper.instance);
-
- if (component == null || c.isAssignableFrom(component.getClass())) return component;
- else
- throw new ConfigurationException("Component registered under " + name + " is of type " + component.getClass() + " and cannot be assigned to " + c);
- }
-
- /**
- * Retrieves a named component if one exists, and if not, attempts to find a factory capable of constructing the component
- * (factories annotated with the {@link org.jboss.cache.factories.annotations.DefaultFactoryFor} annotation that is capable
- * of creating the component class).
- * <p/>
- * If an instance needs to be constructed, dependencies are then automatically wired into the instance, based on methods
- * on the component type annotated with {@link org.jboss.cache.factories.annotations.Inject}.
- * <p/>
- * Summing it up, component retrieval happens in the following order:<br />
- * 1. Look for an appropriate component that exists in the {@link Configuration} that may be injected from an external system.
- * 2. Look for a class definition passed in to the {@link org.jboss.cache.config.Configuration} - such as an EvictionPolicy implementation
- * 3. Attempt to create it by looking for an appropriate factory (annotated with {@link org.jboss.cache.factories.annotations.DefaultFactoryFor})
- * <p/>
- *
- * @param componentClass type of component to be retrieved. Should not be null.
- * @return a fully wired component instance, or null if one cannot be found or constructed.
- * @throws ConfigurationException if there is a problem with consructing or wiring the instance.
- */
- public <T> T getOrCreateComponent(Class<T> componentClass)
- {
- return getOrCreateComponent(null, componentClass);
- }
-
- /**
- * Retrieves a named component if one exists, and if not, attempts to find a factory capable of constructing the component
- * (factories annotated with the {@link org.jboss.cache.factories.annotations.DefaultFactoryFor} annotation that is capable
- * of creating the component class).
- * <p/>
- * If an instance needs to be constructed, dependencies are then automatically wired into the instance, based on methods
- * on the component type annotated with {@link org.jboss.cache.factories.annotations.Inject}.
- * <p/>
- * Summing it up, component retrieval happens in the following order:<br />
- * 1. Look for an appropriate component that exists in the {@link Configuration} that may be injected from an external system.
- * 2. Look for a class definition passed in to the {@link org.jboss.cache.config.Configuration} - such as an EvictionPolicy implementation
- * 3. Attempt to create it by looking for an appropriate factory (annotated with {@link org.jboss.cache.factories.annotations.DefaultFactoryFor})
- * <p/>
- *
- * @param componentName name of component to be created. If null, uses the fully qualified class name as component name.
- * @param componentClass type of component to be retrieved. Should not be null.
- * @return a fully wired component instance, or null if one cannot be found or constructed.
- * @throws ConfigurationException if there is a problem with consructing or wiring the instance.
- */
- public <T> T getOrCreateComponent(String componentName, Class<T> componentClass)
- {
- T component = getComponent(componentName == null ? componentClass.getName() : componentName, componentClass);
-
- if (component == null)
- {
- // first see if this has been injected externally.
- component = getFromConfiguration(componentClass);
- boolean attemptedFactoryConstruction = false;
-
- if (component == null && isNonBootstrapClass(componentClass))
- {
- // create this component and add it to the registry
- ComponentFactory factory = getFactory(componentClass);
- component = factory.construct(componentName, componentClass);
- attemptedFactoryConstruction = true;
-
- }
-
- String componentNameToUse = componentName == null ? componentClass.getName() : componentName;
-
- if (component != null)
- {
- registerComponent(componentNameToUse, component, componentClass);
- }
- else if (attemptedFactoryConstruction)
- {
- if (trace) log.trace("Registering a null for component " + componentNameToUse);
- registerNullComponent(componentNameToUse, componentClass);
- }
- }
-
- return component;
- }
-
- // registers a special "null" component that has no dependencies.
- void registerNullComponent(String componentName, Class type)
- {
- registerComponent(componentName, NULL_COMPONENT, type);
- }
-
- private boolean isNonBootstrapClass(Class<?> componentClass)
- {
- return !(componentClass.equals(CacheSPI.class) || componentClass.equals(LifecycleManager.class) ||
- componentClass.equals(Cache.class) || componentClass.equals(ComponentRegistry.class) ||
- componentClass.equals(Configuration.class));
- }
-
- @SuppressWarnings("unchecked")
- <T> T getFromConfiguration(Class<T> componentClass)
- {
- if (log.isDebugEnabled())
- log.debug("Looking in configuration for an instance of " + componentClass + " that may have been injected from an external source.");
- Method getter = BeanUtils.getterMethod(Configuration.class, componentClass);
- T returnValue = null;
-
- if (getter != null)
- {
- try
- {
- returnValue = (T) getter.invoke(getConfiguration());
- }
- catch (Exception e)
- {
- log.warn("Unable to invoke getter " + getter + " on Configuration.class!", e);
- }
- }
-
- // now try the RuntimeConfig - a legacy "registry" of sorts.
- if (returnValue == null)
- {
- getter = BeanUtils.getterMethod(RuntimeConfig.class, componentClass);
- if (getter != null)
- {
- try
- {
- returnValue = (T) getter.invoke(getConfiguration().getRuntimeConfig());
- }
- catch (Exception e)
- {
- log.warn("Unable to invoke getter " + getter + " on RuntimeConfig.class!", e);
- }
- }
- }
- return returnValue;
- }
-
- Configuration getConfiguration()
- {
- // this is assumed to always be present as a part of the bootstrap/construction of a ComponentRegistry.
- return getComponent(Configuration.class);
- }
-
- /**
- * Updates (re-injects) any dependencies needed by all components already in the registry.
- */
- public void updateDependencies()
- {
- State originalState = overallState;
- moveComponentsToState(overallState == STARTED ? STOPPED : CONSTRUCTED);
- moveComponentsToState(originalState);
- // re- add a few key components - this is a hack for now
- LifecycleManager clm = getComponent(LifecycleManager.class);
- CacheSPI spi = getComponent(CacheSPI.class.getName(), CacheSPI.class);
- CommandsFactory commandsFactory = getComponent(CommandsFactory.class.getName(), CommandsFactory.class);
-
- unregisterComponent(LifecycleManager.class);
- unregisterComponent(CacheSPI.class);
- unregisterComponent(CommandsFactory.class);
-
- overallState = CONSTRUCTED;
-
- registerComponent(LifecycleManager.class.getName(), clm, LifecycleManager.class);
- registerComponent(CacheSPI.class.getName(), spi, CacheSPI.class);
- registerComponent(CommandsFactory.class.getName(), commandsFactory, CommandsFactory.class);
-
- overallState = originalState;
- moveComponentsToState(overallState);
- }
-
- /**
- * Removes a component from the registry. If the component has already been injected into other components, you should
- * call {@link #updateDependencies()} to ensure dependencies are updated.
- *
- * @param clazz class of component to remove.
- */
- public void unregisterComponent(Class<?> clazz)
- {
- unregisterComponent(clazz.getName());
- }
-
- /**
- * Removes a component from the registry. If the component has already been injected into other components, you should
- * call {@link #updateDependencies()} to ensure dependencies are updated.
- *
- * @param name name of the component to remove.
- */
- public void unregisterComponent(String name)
- {
- Component c = componentLookup.remove(name);
- if (c != null) c.changeState(c.state == STARTED ? STOPPED : CONSTRUCTED);
- }
-
- /**
- * Wires an object instance with dependencies annotated with the {@link org.jboss.cache.factories.annotations.Inject} annotation, creating more components
- * as needed based on the Configuration passed in if these additional components don't exist in the
- * {@link ComponentRegistry}. Strictly for components that don't otherwise live in the registry and have a lifecycle, such as Nodes.
- *
- * @param target object to wire
- * @throws ConfigurationException if there is a problem wiring the instance
- */
- public void wireDependencies(Object target) throws ConfigurationException
- {
- //if (trace) log.trace("Inspecting class " + target.getClass());
- try
- {
- // look in caches first
- List<CachedMethod> methods = lookupInjectionMethods(target.getClass());
- //if (trace) log.trace("Found method set containing " + methods.size() + " methods that need injection: " + methods);
-
- // search for anything we need to inject
- for (CachedMethod method : methods)
- {
- //if (trace) log.trace("Method " + method + " needs some other components injected!");
- performInjection(method, target);
- }
- }
- catch (Exception e)
- {
- throw new ConfigurationException("Unable to configure component (type: " + target.getClass() + ", instance " + target + ")", e);
- }
- }
-
- private List<CachedMethod> lookupInjectionMethods(Class type)
- {
- if (longTermMethodCache != null && longTermMethodCache.containsKey(type)) return longTermMethodCache.get(type);
- if (shortTermMethodCache != null && shortTermMethodCache.containsKey(type)) return shortTermMethodCache.get(type);
-
- List<CachedMethod> methods = ReflectionUtil.getAllCachedMethods(type, Inject.class);
- if (type.isAnnotationPresent(CacheInjectionMethods.class))
- {
- if (longTermMethodCache == null) longTermMethodCache = new HashMap<Class, List<CachedMethod>>();
- longTermMethodCache.put(type, methods);
- }
- else
- {
- if (shortTermMethodCache == null) shortTermMethodCache = new HashMap<Class, List<CachedMethod>>();
- shortTermMethodCache.put(type, methods);
- }
-
- return methods;
- }
-
- /**
- * Looks through the parameter list of the given method, attempts to locate parameters that fit the types that may
- * exist in the {@link ComponentRegistry}, and then calls the method on the target object with the necessary parameters.
- *
- * @param method Method to call
- * @param target Instance on which to call the method
- * @throws IllegalAccessException if the method cannot be called
- * @throws java.lang.reflect.InvocationTargetException
- * if the method cannot be called
- */
- @SuppressWarnings("unchecked")
- private <T> void performInjection(CachedMethod method, T target) throws IllegalAccessException, InvocationTargetException
- {
- Class[] parameterTypes = method.getParameterTypes();
- List<Component> componentsToInject = getDeclaredDependencies(method);
-
- Object[] parameters = new Object[parameterTypes.length];
-
- for (int i = 0; i < parameterTypes.length; i++)
- {
- parameters[i] = getOrCreateComponent(componentsToInject.get(i).name, parameterTypes[i]);
- }
-
- Method reflectMethod = method.getMethod();
- // make sure we set this method to be accessible, so we can call private, package and protected
- // methods rather than just public ones.
- reflectMethod.setAccessible(true);
-
- // invoke the method with the parameters we've worked out.
- reflectMethod.invoke(target, parameters);
- }
-
- private String extractComponentName(Annotation[] annotationsOnParameter)
- {
- for (Annotation a : annotationsOnParameter)
- {
- if (a instanceof ComponentName)
- {
- ComponentName cn = (ComponentName) a;
- return cn.value();
- }
- }
- return null;
- }
-
- private List<Component> getDeclaredDependencies(CachedMethod method)
- {
- List<Component> dependencies = new LinkedList<Component>();
- Class[] parameterTypes = method.getParameterTypes();
- Annotation[][] annotationsOnParams = method.getParameterAnnotations();
- for (int i = 0; i < parameterTypes.length; i++)
- {
- String componentName = extractComponentName(annotationsOnParams[i]);
- String componentNameToUse = componentName == null ? parameterTypes[i].getName() : componentName;
- // if the component exists in the lookup, use it. Otherwise use a placeholder which will be constructed later, on demand.
- Component d = componentLookup.containsKey(componentNameToUse) ? componentLookup.get(componentNameToUse) : new Component(componentNameToUse, parameterTypes[i]);
- dependencies.add(d);
- }
- return dependencies;
- }
-
- /**
- * Retrieves a component factory instance capable of constructing components of a specified type. If the factory doesn't
- * exist in the registry, one is created. Always changes the state of any factory to {@link State#STARTED} before returning.
- *
- * @param componentClass type of component to construct
- * @return component factory capable of constructing such components
- */
- protected ComponentFactory getFactory(Class componentClass)
- {
- if (defaultFactories == null) scanDefaultFactories();
- Class<? extends ComponentFactory> cfClass = defaultFactories.get(componentClass);
- if (cfClass == null)
- throw new ConfigurationException("No registered default factory for component " + componentClass + " found!");
- // a component factory is a component too! See if one has been created and exists in the registry
- ComponentFactory cf = getComponent(cfClass);
- if (cf == null)
- {
- // hasn't yet been created. Create and put in registry
- cf = instantiateFactory(cfClass);
- if (cf != null)
- {
- // we simply register this factory. Registration will take care of constructing any dependencies.
- registerComponent(cf, cfClass);
- }
- }
-
- if (cf == null)
- throw new ConfigurationException("Unable to locate component factory for component " + componentClass);
-
- // ensure the component factory is in the STARTED state!
- Component c = componentLookup.get(cfClass.getName());
- if (c.instance != cf)
- throw new ConfigurationException("Component factory " + cfClass + " incorrectly registered!");
- c.changeState(STARTED);
- return cf;
- }
-
- /**
- * Scans the class path for classes annotated with {@link org.jboss.cache.factories.annotations.DefaultFactoryFor}, and
- * analyses which components can be created by such factories.
- */
- void scanDefaultFactories()
- {
- defaultFactories = new HashMap<Class, Class<? extends ComponentFactory>>();
-
- Set<Class<? extends ComponentFactory>> factories = getHardcodedFactories();
-
- for (Class<? extends ComponentFactory> factory : factories)
- {
- DefaultFactoryFor dFFAnnotation = factory.getAnnotation(DefaultFactoryFor.class);
- for (Class targetClass : dFFAnnotation.classes()) defaultFactories.put(targetClass, factory);
- }
- }
-
- /**
- * No such thing as a meta factory yet. Factories are created using this method which attempts to use an empty public
- * constructor.
- *
- * @param factory class of factory to be created
- * @return factory instance
- */
- ComponentFactory instantiateFactory(Class<? extends ComponentFactory> factory)
- {
- try
- {
- return factory.newInstance();
- }
- catch (Exception e)
- {
- // unable to get a hold of an instance!!
- throw new ConfigurationException("Unable to instantiate factory " + factory, e);
- }
- }
-
- /**
- * Wipes everything in the registry. Use with care.
- */
- public void reset()
- {
- // the bootstrap classes
- Component deployerClassLoader = componentLookup.get("deployerClassLoader");
- Component spi = componentLookup.get(CacheSPI.class.getName());
- Component interceptorChain = componentLookup.get(InterceptorChain.class.getName());
- Component lifeCycleManager = componentLookup.get(LifecycleManager.class.getName());
- Component dataContainer = componentLookup.get(DataContainer.class.getName());
- Component conf = componentLookup.get(Configuration.class.getName());
- Component cr = componentLookup.get(ComponentRegistry.class.getName());
-
- // destroy all components to clean up resources
- for (Component c : componentLookup.values()) c.changeState(DESTROYED);
-
- // remove from componentLookup
- componentLookup.clear();
-
- // bootstrap components
- deployerClassLoader.changeState(CONSTRUCTED);
- spi.changeState(CONSTRUCTED);
- interceptorChain.changeState(CONSTRUCTED);
- lifeCycleManager.changeState(CONSTRUCTED);
- dataContainer.changeState(CONSTRUCTED);
- conf.changeState(CONSTRUCTED);
- cr.changeState(CONSTRUCTED);
-
- bootstrap = new Bootstrap((ClassLoader) deployerClassLoader.instance, (InterceptorChain) interceptorChain.instance,
- (LifecycleManager) lifeCycleManager.instance, (DataContainer) dataContainer.instance, (CacheSPI) spi.instance,
- (ComponentRegistry) cr.instance, (Configuration) conf.instance);
-
- overallState = null;
- }
-
- /**
- * Starts all components that contain the {@link Start} annotation.
- */
- public void start()
- {
- moveComponentsToState(STARTED);
- shortTermMethodCache = null;
- }
-
- /**
- * Stops all components that contain the {@link Stop} annotation.
- */
- public void stop()
- {
- moveComponentsToState(STOPPED);
- }
-
- /**
- * Injects dependencies to all components that require injection.
- */
- public void wire()
- {
- moveComponentsToState(WIRED);
- }
-
- void moveComponentsToState(State state)
- {
- if (overallState == null && bootstrap != null && !bootstrap.isBootstrapped())
- {
- // we have been destroyed! Need to bootstrap again.
- bootstrap.bootstrap();
- }
-
- // copy the component lookup CHM to prevent concurrent modification exceptions later on, if components need to be
- // constructed and added to the system on the fly.
- Set<Component> components = new HashSet<Component>(componentLookup.values());
- for (Component c : components) c.changeState(state);
-
- overallState = state;
- }
-
- /**
- * Represents the state of a component
- */
- public enum State
- {
- DESTROYED, STOPPED, CONSTRUCTED, WIRED, STARTED;
-
- /**
- * Tests whether the current state is "greater" than the state passed in
- *
- * @param other state to compare with
- * @return true if the current state is "greater" than the state passed in
- */
- boolean isGreaterThan(State other)
- {
- return this.ordinal() > other.ordinal();
- }
-
- /**
- * Tests whether the current state is "less" than the state passed in
- *
- * @param other state to compare with
- * @return true if the current state is "less" than the state passed in
- */
- boolean isLessThan(State other)
- {
- return this.ordinal() < other.ordinal();
- }
-
- /**
- * @param other state to compare with
- * @return the absolute difference in ordinal places between 2 states
- */
- int absoluteDifference(State other)
- {
- return Math.abs(this.ordinal() - other.ordinal());
- }
- }
-
- /**
- * Represents a component in the registry, along with state and dependencies.
- */
- class Component
- {
- Object instance;
- final String name;
- final Class type;
- State state = CONSTRUCTED;
- final Set<Component> dependencies = new HashSet<Component>(3);
- final Set<Component> dependencyFor = new HashSet<Component>(3);
- boolean deepRecursionDetector = false;
-
- public Component(String name, Class type)
- {
- this.name = name;
- this.type = type;
- }
-
- /**
- * Constructs a Component out of an instance and a name. Scans instance for dependencies and populates
- * the "dependencies" and "dependencyFor" collections.
- *
- * @param name name of component
- * @param instance component instance
- */
- public Component(String name, Object instance, Class type)
- {
- this(name, type);
- this.instance = instance;
-
- // now scan the instance for all dependencies.
- List<CachedMethod> injectionMethods = lookupInjectionMethods(instance.getClass());
-
- // now for each injection method, get dependencies
- for (CachedMethod m : injectionMethods) dependencies.addAll(getDeclaredDependencies(m));
- }
-
- /**
- * Changes the state of a component - along with all dependent components - to a new state. This method is recursion
- * and cyclic dependency safe.
- *
- * @param newState new state to move component to
- */
- void changeState(State newState)
- {
- // Deep recursion is when this component depends on another component which in turn may depend on this component again.
- // if this is encountered then break out of the recursive loop.
- if (state != newState && !deepRecursionDetector)
- {
- // Step by step. If the new state is > 1 step away from the current state, change state gradually.
- boolean increase = newState.isGreaterThan(state);
- int numSteps = newState.absoluteDifference(state);
-
- while (numSteps > 1)
- {
- changeState(State.values()[state.ordinal() + (increase ? 1 : -1)]);
- numSteps = newState.absoluteDifference(state);
- }
-
- // now we update the state of dependent components accordingly.
- Set<Component> dependentComponents = new HashSet<Component>();
- Set<Component> shallowCyclic = new HashSet<Component>();
-
- if (increase)
- {
- // if I am moving to a "higher" state make sure all components that I depend on have moved to that state as well.
- dependentComponents.addAll(dependencies);
- }
- else
- {
- // if I am moving to a "lower" state make sure all components depend on me have moved to that state as well.
- dependentComponents.addAll(dependencyFor);
- }
-
- // switch on the deep recursion detector
- deepRecursionDetector = true;
- for (Component d : dependentComponents)
- {
- if (d != null)
- {
- // always look up again in the component lookup. The dependencies and dependenciesFor sets are just
- // used as references. The actual component instances may be out of date.
- d = componentLookup.get(d.name);
-
- if (d != null)
- {
- if (isShallowCyclic(d))
- {
- // don't invoke shallow cyclic deps here - shoud do that after we set our state.
- shallowCyclic.add(d);
- }
- else
- {
- // of we are "moving up" - only do this if the component is lower than what is needed.
- if ((increase && newState.isGreaterThan(d.state)) || (!increase && newState.isLessThan(d.state)))
- {
- d.changeState(newState);
- }
- }
- }
- }
- }
-
- // NOW we update our state.
- switch (newState)
- {
- case STOPPED:
- stop();
- break;
- case WIRED:
- if (increase) wire();
- break;
- case STARTED:
- start();
- break;
- case DESTROYED:
- destroy();
- break;
- case CONSTRUCTED:
- // do nothing
- }
-
- state = newState;
-
- // now process the shallow cyclic deps
- for (Component c : shallowCyclic)
- {
- // of we are "moving up" - only do this if the component is lower than what is needed.
- if ((increase && newState.isGreaterThan(c.state)) || (!increase && newState.isLessThan(c.state)))
- c.changeState(newState);
- }
-
- // make sure we switch off the deep recursion detector now.
- deepRecursionDetector = false;
- }
- }
-
- /**
- * Tests whether there is an immediate cyclic dependency (i.e., both components depend on each other) between the current component and another one.
- *
- * @param c other component to test with
- * @return true if there is an immediate cyclic dependency between the 2 components
- */
- private boolean isShallowCyclic(Component c)
- {
- return dependencies.contains(c) && c.dependencies.contains(this);
- }
-
- /**
- * Used to wire dependencies into this component instance.
- */
- void wire()
- {
- try
- {
- List<CachedMethod> methods = lookupInjectionMethods(instance.getClass());
-
- // search for anything we need to inject
- for (CachedMethod method : methods) performInjection(method, instance);
- }
- catch (Exception e)
- {
- throw new ConfigurationException("Unable to configure component (type: " + instance.getClass() + ", instance " + instance + ")", e);
- }
- }
-
- /**
- * Used to call all methods annotated with {@link Start} on component instance
- */
- void start()
- {
- invokeMethods(Start.class);
- }
-
- /**
- * Used to call all methods annotated with {@link Stop} on component instance
- */
- void stop()
- {
- invokeMethods(Stop.class);
- }
-
- /**
- * Used to call all methods annotated with {@link org.jboss.cache.factories.annotations.Destroy} on component instance
- */
- void destroy()
- {
- invokeMethods(Destroy.class);
- }
-
- private void invokeMethods(Class<? extends Annotation> annotation)
- {
- List<Method> methods = ReflectionUtil.getAllMethods(instance.getClass(), annotation);
- for (Method m : methods)
- {
- try
- {
- m.setAccessible(true);
- m.invoke(instance);
- }
- catch (Exception e)
- {
- log.warn("Unable to invoke annotated method " + m, e);
- }
- }
- }
-
- @Override
- public String toString()
- {
- return "Component (name = " + name + ", state = " + state + ")";
- }
-
- @Override
- public int hashCode()
- {
- return 31 * name.hashCode();
- }
-
- @Override
- public boolean equals(Object other)
- {
- return other instanceof Component && name.equals(((Component) other).name);
- }
-
- }
-
- class Bootstrap
- {
- final InterceptorChain interceptorChain;
- final LifecycleManager lifecycleManager;
- final DataContainer dataContainer;
- final CacheSPI cacheSPI;
- final ComponentRegistry componentRegistry;
- final Configuration configuration;
- private final ClassLoader deployerClassLoader;
-
- Bootstrap(ClassLoader deployerClassLoader, InterceptorChain interceptorChain, LifecycleManager lifecycleManager,
- DataContainer dataContainer, CacheSPI cacheSPI, ComponentRegistry componentRegistry, Configuration configuration)
- {
- this.deployerClassLoader = deployerClassLoader;
- this.lifecycleManager = lifecycleManager;
- this.dataContainer = dataContainer;
- this.interceptorChain = interceptorChain;
- this.cacheSPI = cacheSPI;
- this.componentRegistry = componentRegistry;
- this.configuration = configuration;
- }
-
- boolean isBootstrapped()
- {
- return componentLookup.containsKey(Configuration.class.getName()) &&
- componentLookup.containsKey(LifecycleManager.class.getName()) &&
- componentLookup.containsKey(InterceptorChain.class.getName()) &&
- componentLookup.containsKey(DataContainer.class.getName()) &&
- componentLookup.containsKey(CacheSPI.class.getName()) &&
- componentLookup.containsKey(ComponentRegistry.class.getName()) &&
- componentLookup.containsKey("deployerClassLoader");
- }
-
- void bootstrap()
- {
- overallState = CONSTRUCTED;
- registerComponent("deployerClassLoader", deployerClassLoader, ClassLoader.class);
- registerComponent(Configuration.class.getName(), configuration, Configuration.class);
- registerComponent(ComponentRegistry.class.getName(), componentRegistry, ComponentRegistry.class);
- registerComponent(InterceptorChain.class.getName(), interceptorChain, InterceptorChain.class);
- registerComponent(LifecycleManager.class.getName(), lifecycleManager, LifecycleManager.class);
- registerComponent(DataContainer.class.getName(), dataContainer, DataContainer.class);
- registerComponent(CacheSPI.class.getName(), cacheSPI, CacheSPI.class);
- }
- }
-}
\ No newline at end of file
16 years, 7 months
JBoss Cache SVN: r5803 - in core/trunk/src: main/java/org/jboss/cache/buddyreplication and 28 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-05-08 04:50:28 -0400 (Thu, 08 May 2008)
New Revision: 5803
Added:
core/trunk/src/main/java/org/jboss/cache/factories/BootstrapFactory.java
core/trunk/src/main/java/org/jboss/cache/factories/ComponentKernel.java
core/trunk/src/main/java/org/jboss/cache/factories/annotations/NonVolatile.java
core/trunk/src/test/java/org/jboss/cache/factories/LifeCycleTest.java
Removed:
core/trunk/src/main/java/org/jboss/cache/LifecycleManager.java
core/trunk/src/main/java/org/jboss/cache/factories/annotations/CacheInjectionMethods.java
core/trunk/src/main/java/org/jboss/cache/factories/annotations/ComponentName.java
Modified:
core/trunk/src/main/java/org/jboss/cache/DataContainer.java
core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java
core/trunk/src/main/java/org/jboss/cache/NodeFactory.java
core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java
core/trunk/src/main/java/org/jboss/cache/RegionManager.java
core/trunk/src/main/java/org/jboss/cache/UnversionedNode.java
core/trunk/src/main/java/org/jboss/cache/VersionedNode.java
core/trunk/src/main/java/org/jboss/cache/buddyreplication/BuddyManager.java
core/trunk/src/main/java/org/jboss/cache/cluster/ReplicationQueue.java
core/trunk/src/main/java/org/jboss/cache/commands/write/EvictCommand.java
core/trunk/src/main/java/org/jboss/cache/config/Configuration.java
core/trunk/src/main/java/org/jboss/cache/config/ConfigurationComponent.java
core/trunk/src/main/java/org/jboss/cache/factories/BuddyManagerFactory.java
core/trunk/src/main/java/org/jboss/cache/factories/CommandsFactory.java
core/trunk/src/main/java/org/jboss/cache/factories/ComponentFactory.java
core/trunk/src/main/java/org/jboss/cache/factories/EmptyConstructorFactory.java
core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java
core/trunk/src/main/java/org/jboss/cache/factories/ReplicationQueueFactory.java
core/trunk/src/main/java/org/jboss/cache/factories/RuntimeConfigAwareFactory.java
core/trunk/src/main/java/org/jboss/cache/factories/TransactionManagerFactory.java
core/trunk/src/main/java/org/jboss/cache/factories/annotations/DefaultFactoryFor.java
core/trunk/src/main/java/org/jboss/cache/factories/annotations/Destroy.java
core/trunk/src/main/java/org/jboss/cache/factories/annotations/Start.java
core/trunk/src/main/java/org/jboss/cache/factories/annotations/Stop.java
core/trunk/src/main/java/org/jboss/cache/interceptors/InterceptorChain.java
core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java
core/trunk/src/main/java/org/jboss/cache/invocation/AbstractInvocationDelegate.java
core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java
core/trunk/src/main/java/org/jboss/cache/invocation/InvocationContextContainer.java
core/trunk/src/main/java/org/jboss/cache/loader/CacheLoaderManager.java
core/trunk/src/main/java/org/jboss/cache/loader/ChainingCacheLoader.java
core/trunk/src/main/java/org/jboss/cache/lock/IdentityLock.java
core/trunk/src/main/java/org/jboss/cache/lock/LockManager.java
core/trunk/src/main/java/org/jboss/cache/lock/LockStrategyFactory.java
core/trunk/src/main/java/org/jboss/cache/marshall/AbstractMarshaller.java
core/trunk/src/main/java/org/jboss/cache/marshall/CommandAwareRpcDispatcher.java
core/trunk/src/main/java/org/jboss/cache/marshall/InactiveRegionAwareRpcDispatcher.java
core/trunk/src/main/java/org/jboss/cache/marshall/VersionAwareMarshaller.java
core/trunk/src/main/java/org/jboss/cache/notifications/Notifier.java
core/trunk/src/main/java/org/jboss/cache/remoting/jgroups/ChannelMessageListener.java
core/trunk/src/main/java/org/jboss/cache/statetransfer/StateTransferManager.java
core/trunk/src/main/java/org/jboss/cache/transaction/TransactionTable.java
core/trunk/src/main/java/org/jboss/cache/util/reflect/ReflectionUtil.java
core/trunk/src/test/java/org/jboss/cache/TreeCacheFunctionalTest.java
core/trunk/src/test/java/org/jboss/cache/api/NodeReplicatedMoveOptimisticTest.java
core/trunk/src/test/java/org/jboss/cache/api/pfer/PutForExternalReadTestBase.java
core/trunk/src/test/java/org/jboss/cache/buddyreplication/BuddyManagerTest.java
core/trunk/src/test/java/org/jboss/cache/cluster/ReplicationQueueTest.java
core/trunk/src/test/java/org/jboss/cache/factories/ComponentRegistryFunctionalTest.java
core/trunk/src/test/java/org/jboss/cache/factories/ComponentRegistryUnitTest.java
core/trunk/src/test/java/org/jboss/cache/lock/IdentityLockTest.java
core/trunk/src/test/java/org/jboss/cache/marshall/AbstractVersionAwareMarshallerTest.java
core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshaller200Test.java
core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshallerTestBase.java
core/trunk/src/test/java/org/jboss/cache/marshall/MarshalledValueTest.java
core/trunk/src/test/java/org/jboss/cache/marshall/MethodIdPreservationTest.java
core/trunk/src/test/java/org/jboss/cache/marshall/VersionAwareMarshallerTest.java
core/trunk/src/test/java/org/jboss/cache/misc/TestingUtil.java
core/trunk/src/test/java/org/jboss/cache/notifications/RemoteCacheListenerTest.java
core/trunk/src/test/java/org/jboss/cache/optimistic/NodeInterceptorGetChildrenNamesTest.java
core/trunk/src/test/java/org/jboss/cache/statetransfer/FailedStateTransferTest.java
core/trunk/src/test/java/org/jboss/cache/transaction/PrepareCommitContentionTest.java
Log:
ComponentRegistry refactoring
Modified: core/trunk/src/main/java/org/jboss/cache/DataContainer.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/DataContainer.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/DataContainer.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -6,6 +6,10 @@
import org.jboss.cache.buddyreplication.BuddyManager;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.factories.annotations.NonVolatile;
+import org.jboss.cache.factories.annotations.Start;
+import org.jboss.cache.factories.annotations.Stop;
+import org.jboss.cache.invocation.NodeInvocationDelegate;
import org.jboss.cache.marshall.NodeData;
import org.jboss.cache.optimistic.DataVersion;
import org.jboss.cache.transaction.GlobalTransaction;
@@ -23,6 +27,7 @@
* @author Mircea.Markus(a)jboss.com
* @since 2.2
*/
+@NonVolatile
public class DataContainer
{
private static final Log log = LogFactory.getLog(DataContainer.class);
@@ -40,13 +45,38 @@
* not included in standard state transfers.
*/
private final Set<Fqn> internalFqns = new HashSet<Fqn>();
+ private NodeFactory nodeFactory;
@Inject
- public void injectDependencies(Configuration configuration)
+ public void injectDependencies(Configuration configuration, NodeFactory nodeFactory)
{
this.configuration = configuration;
+ this.nodeFactory = nodeFactory;
+ createRootNode();
}
+ @Start(priority = 25)
+ private void createRootNode()
+ {
+ // create a new root temporarily.
+ NodeSPI tempRoot = nodeFactory.createRootDataNode();
+ // if we don't already have a root or the new (temp) root is of a different class (optimistic vs pessimistic) to
+ // the current root, then we use the new one.
+
+ Class currentRootType = root == null ? null : ((NodeInvocationDelegate) root).getDelegationTarget().getClass();
+ Class tempRootType = ((NodeInvocationDelegate) tempRoot).getDelegationTarget().getClass();
+
+ if (!tempRootType.equals(currentRootType)) setRoot(tempRoot);
+ }
+
+ @Stop(priority = 100)
+ public void stop()
+ {
+ // empty in-memory state
+ root.clearDataDirect();
+ root.removeChildrenDirect();
+ }
+
/**
* Retrieves the root node.
*
Modified: core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -8,8 +8,9 @@
import org.jboss.cache.config.Configuration;
import org.jboss.cache.config.ConfigurationException;
+import org.jboss.cache.factories.BootstrapFactory;
import org.jboss.cache.factories.ComponentFactory;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.factories.XmlConfigurationParser;
import org.jboss.cache.invocation.CacheInvocationDelegate;
@@ -19,10 +20,10 @@
* Default implementation of the {@link org.jboss.cache.CacheFactory} interface.
* <p/>
* This is a special instance of a {@link ComponentFactory} which contains bootstrap information for the
- * {@link ComponentRegistry}.
+ * {@link org.jboss.cache.factories.ComponentKernel}.
* <p/>
* E.g., {@link #bootstrap(LifecycleManager , CacheSPI, org.jboss.cache.config.Configuration)} is used to create a cache, a
- * {@link ComponentRegistry}, and then wire dependencies as needed.
+ * {@link org.jboss.cache.factories.ComponentKernel}, and then wire dependencies as needed.
* <p/>
* In JBoss Cache 2.0.x, this was a singleton and you had to use {@link #getInstance()} to obtain an instance. From
* JBoss Cache 2.1.x onwards, this is no longer a singleton and you can use the default no-arg constructor to obtain
@@ -114,26 +115,27 @@
protected CacheSPI<K, V> createAndWire(Configuration configuration) throws Exception
{
- LifecycleManager lifecycleManager = new LifecycleManager(configuration);
CacheSPI<K, V> spi = new CacheInvocationDelegate<K, V>();
- bootstrap(lifecycleManager, spi, configuration);
- componentRegistry.wire();
+ bootstrap(spi, configuration);
return spi;
}
/**
* Bootstraps this factory with a Configuration and a ComponentRegistry.
*/
- protected void bootstrap(LifecycleManager lifecycleManager, CacheSPI spi, Configuration configuration)
+ private void bootstrap(CacheSPI spi, Configuration configuration)
{
// injection bootstrap stuff
- componentRegistry = lifecycleManager.getComponentRegistry();
+ componentRegistry = new ComponentKernel(configuration);
componentRegistry.registerDefaultClassLoader(defaultClassLoader);
this.configuration = configuration;
+ BootstrapFactory bf = new BootstrapFactory(spi, configuration, componentRegistry);
+ componentRegistry.registerComponent(bf, BootstrapFactory.class);
// make sure we set the CacheLifecycleManager and CacheSPI instance in the component registry.
- componentRegistry.registerComponent(LifecycleManager.class.getName(), lifecycleManager, LifecycleManager.class);
- componentRegistry.registerComponent(CacheSPI.class.getName(), spi, CacheSPI.class);
+ //componentRegistry.registerComponent(lifecycleManager, LifecycleManager.class);
+ componentRegistry.registerComponent(spi, CacheSPI.class);
+ componentRegistry.wire();
}
/**
@@ -161,7 +163,7 @@
}
@Override
- protected <T> T construct(String componentName, Class<T> componentType)
+ protected <T> T construct(Class<T> componentType)
{
throw new UnsupportedOperationException("Should never be invoked - this is a bootstrap factory.");
}
Deleted: core/trunk/src/main/java/org/jboss/cache/LifecycleManager.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/LifecycleManager.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/LifecycleManager.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -1,484 +0,0 @@
-package org.jboss.cache;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.cache.buddyreplication.BuddyManager;
-import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.ComponentRegistry;
-import org.jboss.cache.factories.annotations.Inject;
-import org.jboss.cache.interceptors.InterceptorChain;
-import org.jboss.cache.invocation.NodeInvocationDelegate;
-import org.jboss.cache.loader.CacheLoaderManager;
-import org.jboss.cache.lock.LockStrategyFactory;
-import org.jboss.cache.marshall.Marshaller;
-import org.jboss.cache.notifications.Notifier;
-
-import javax.management.MBeanServerFactory;
-import javax.transaction.TransactionManager;
-import java.util.ArrayList;
-
-/**
- * Added in 2.2.0 to handle the lifecycle of the cache. I.e., to control the starting and stopping process, as defined
- * by the {@link org.jboss.cache.Cache#start()} and {@link org.jboss.cache.Cache#stop()} API methods.
- * <p/>
- * This class also acts as a container for the {@link ComponentRegistry}, which it constructs in its constructor
- * as a place to hold all components of a given cache instance.
- * <p/>
- * It also holds the status of the cache, which can be queried.
- * <p/>
- *
- * @author Mircea.Markus(a)jboss.com
- * @since 2.2
- */
-public class LifecycleManager
-{
- private static final Log log = LogFactory.getLog(LifecycleManager.class);
- private CacheStatus cacheStatus;
-
- /* dependencies*/
- private Configuration configuration;
- private Notifier notifier;
- private RegionManager regionManager;
- private NodeFactory nodeFactory;
- private DataContainer dataContainer;
- private BuddyManager buddyManager;
- private RPCManager rpcManager;
- private ComponentRegistry componentRegistry;
-
-
- @Inject
- public void initialize(Configuration configuration, Notifier notifier, RegionManager regionManager, NodeFactory nodeFactory,
- DataContainer cacheData, BuddyManager buddyManager, RPCManager rpcManager,
- ComponentRegistry componentRegistry)
- {
- this.configuration = configuration;
- this.notifier = notifier;
- this.regionManager = regionManager;
- this.nodeFactory = nodeFactory;
- this.buddyManager = buddyManager;
- this.rpcManager = rpcManager;
- this.dataContainer = cacheData;
- this.componentRegistry = componentRegistry;
- }
-
- /**
- * Hook to shut down the cache when the JVM exits.
- */
- private Thread shutdownHook;
- /**
- * A flag that the shutdown hook sets before calling cache.stop(). Allows stop() to identify if it has been called
- * from a shutdown hook.
- */
- private boolean invokedFromShutdownHook;
-
- /**
- * Constructs a new instance, also constructs a {@link org.jboss.cache.factories.ComponentRegistry} instance which can
- * then be retrieved using {@link #getComponentRegistry()}. When constructed, the cache status is set to {@link org.jboss.cache.CacheStatus#INSTANTIATED}.
- *
- * @param configuration with which to create this class.
- */
- public LifecycleManager(Configuration configuration)
- {
- this.configuration = configuration;
- this.componentRegistry = new ComponentRegistry(configuration);
- this.cacheStatus = CacheStatus.INSTANTIATED;
- }
-
- /**
- * Creates the components needed by a cache instance and sets the cache status to {@link org.jboss.cache.CacheStatus#CREATED}
- * when it is done.
- *
- * @throws CacheException if there is a problem with construction.
- */
- public void create() throws CacheException
- {
- if (!cacheStatus.createAllowed())
- {
- if (cacheStatus.needToDestroyFailedCache())
- destroy();
- else
- return;
- }
- try
- {
- internalCreate();
- }
- catch (Throwable t)
- {
- handleLifecycleTransitionFailure(t);
- }
- }
-
- /**
- * Starts the components needed by a cache instance, and then starts the cache instance itself. Sets the cache status to
- * {@link org.jboss.cache.CacheStatus#STARTED} once it is done.
- * <p/>
- * If the cache status is not {@link org.jboss.cache.CacheStatus#CREATED} when this is called, it will first call {@link #create()}
- * to create the cache.
- * <p/>
- *
- * @throws CacheException if there is a problem with starting the cache.
- */
- public void start() throws CacheException
- {
- if (!cacheStatus.startAllowed())
- {
- if (cacheStatus.needToDestroyFailedCache())
- destroy(); // this will take us back to DESTROYED
-
- if (cacheStatus.needCreateBeforeStart())
- create();
- else
- return;
- }
-
- try
- {
- internalStart();
- }
- catch (Throwable t)
- {
-// if (log.isTraceEnabled()) log.trace("InternalStart had problems: ", t);
- handleLifecycleTransitionFailure(t);
- }
- }
-
- /**
- * Destroys the cache and frees up any resources. Sets the cache status to {@link CacheStatus#DESTROYED} when it is done.
- * <p/>
- * If the cache is in {@link org.jboss.cache.CacheStatus#STARTED} when this method is called, it will first call {@link #stop()}
- * to stop the cache.
- */
- public void destroy()
- {
- if (!cacheStatus.destroyAllowed())
- {
- if (cacheStatus.needStopBeforeDestroy())
- {
- try
- {
- stop();
- }
- catch (CacheException e)
- {
- log.warn("Needed to call stop() before destroying but stop() " +
- "threw exception. Proceeding to destroy", e);
- }
- }
- else
- return;
- }
-
- try
- {
- internalDestroy();
- }
- finally
- {
- // We always progress to destroyed
- cacheStatus = CacheStatus.DESTROYED;
- }
- }
-
- /**
- * Stops the cache and sets the cache status to {@link org.jboss.cache.CacheStatus#STOPPED} once it is done. If the cache is not in
- * the {@link org.jboss.cache.CacheStatus#STARTED} state, this is a no-op.
- */
- public void stop()
- {
- if (!cacheStatus.stopAllowed())
- {
- return;
- }
-
- // Trying to stop() from FAILED is valid, but may not work
- boolean failed = cacheStatus == CacheStatus.FAILED;
-
- try
- {
- internalStop();
- }
- catch (Throwable t)
- {
- if (failed)
- {
- log.warn("Attempted to stop() from FAILED state, " +
- "but caught exception; try calling destroy()", t);
- }
- handleLifecycleTransitionFailure(t);
- }
- finally
- {
- if (!failed) cacheStatus = CacheStatus.STOPPED;
- }
- }
-
- /**
- * The actual start implementation.
- */
- private void internalStart() throws CacheException, IllegalArgumentException
- {
- // re-wire all dependencies in case stuff has changed since the cache was created
-
- // remove any components whose construction may have depended upon a configuration that may have changed.
- removeConfigurationDependentComponents();
-
- // this will recreate any missing components based on the current config
- componentRegistry.updateDependencies();
- componentRegistry.wireDependencies(dataContainer.getRoot());
-
- cacheStatus = CacheStatus.STARTING;
-
- // start all internal components
- componentRegistry.start();
-
- if (log.isDebugEnabled())
- log.debug("Interceptor chain is: " + componentRegistry.getComponent(InterceptorChain.class));
-
- correctRootNodeType();
-
- startManualComponents();
-
- // start any eviction threads.
- if (regionManager.isUsingEvictions())
- {
- regionManager.startEvictionThread();
- }
-
- notifier.notifyCacheStarted();
-
- addShutdownHook();
-
- log.info("JBoss Cache version: " + Version.printVersion());
-
- cacheStatus = CacheStatus.STARTED;
- }
-
- private void addShutdownHook()
- {
- ArrayList al = MBeanServerFactory.findMBeanServer(null);
- boolean registerShutdownHook = (configuration.getShutdownHookBehavior() == Configuration.ShutdownHookBehavior.DEFAULT && al.size() == 0)
- || configuration.getShutdownHookBehavior() == Configuration.ShutdownHookBehavior.REGISTER;
-
- if (registerShutdownHook)
- {
- if (log.isTraceEnabled())
- log.trace("Registering a shutdown hook. Configured behavior = " + configuration.getShutdownHookBehavior());
- shutdownHook = new Thread()
- {
- @Override
- public void run()
- {
- try
- {
- invokedFromShutdownHook = true;
- LifecycleManager.this.stop();
- }
- finally
- {
- invokedFromShutdownHook = false;
- }
- }
- };
-
- Runtime.getRuntime().addShutdownHook(shutdownHook);
- }
- else
- {
- if (log.isTraceEnabled())
- log.trace("Not registering a shutdown hook. Configured behavior = " + configuration.getShutdownHookBehavior());
- }
- }
-
- /**
- * The actual create implementation.
- *
- * @throws CacheException
- */
- private void internalCreate() throws CacheException
- {
- componentRegistry.wire();
- correctRootNodeType();
-
- LockStrategyFactory.setIsolationLevel(configuration.getIsolationLevel());
-
- cacheStatus = CacheStatus.CREATED;
- }
-
- /**
- * Sets the cacheStatus to FAILED and rethrows the problem as one
- * of the declared types. Converts any non-RuntimeException Exception
- * to CacheException.
- *
- * @param t
- * @throws CacheException
- * @throws RuntimeException
- * @throws Error
- */
- private void handleLifecycleTransitionFailure(Throwable t)
- throws RuntimeException, Error
- {
- cacheStatus = CacheStatus.FAILED;
- if (t instanceof CacheException)
- throw (CacheException) t;
- else if (t instanceof RuntimeException)
- throw (RuntimeException) t;
- else if (t instanceof Error)
- throw (Error) t;
- else
- throw new CacheException(t);
- }
-
- /**
- * The actual destroy implementation.
- */
- private void internalDestroy()
- {
- cacheStatus = CacheStatus.DESTROYING;
- // The rest of these should have already been taken care of in stop,
- // but we do it here as well in case stop failed.
- rpcManager.stop();
- componentRegistry.reset();
- }
-
- /**
- * The actual stop implementation.
- */
- private void internalStop()
- {
- cacheStatus = CacheStatus.STOPPING;
- // if this is called from a source other than the shutdown hook, deregister the shutdown hook.
- if (!invokedFromShutdownHook && shutdownHook != null) Runtime.getRuntime().removeShutdownHook(shutdownHook);
- componentRegistry.stop();
- if (notifier != null)
- {
- notifier.notifyCacheStopped();
- notifier.removeAllCacheListeners();
- }
- // unset transaction manager reference
- cacheStatus = CacheStatus.STOPPED;
- // empty in-memory state
- dataContainer.getRoot().clearDataDirect();
- dataContainer.getRoot().removeChildrenDirect();
- }
-
- private void removeConfigurationDependentComponents()
- {
- // remove the Interceptor.class component though, since it may pertain to an old config
-
- componentRegistry.unregisterComponent(InterceptorChain.class); // the interceptor chain will need reconstructing in case the cfg has changed before calling start()
- componentRegistry.unregisterComponent(Marshaller.class);
- componentRegistry.unregisterComponent(TransactionManager.class);
- componentRegistry.unregisterComponent(BuddyManager.class);
- componentRegistry.unregisterComponent(CacheLoaderManager.class);
- }
-
- /**
- * Creates a new root node if one does not exist, or if the existing one does not match the type according to the configuration.
- */
- private void correctRootNodeType()
- {
- // create a new root temporarily.
- NodeSPI tempRoot = nodeFactory.createRootDataNode();
- // if we don't already have a root or the new (temp) root is of a different class (optimistic vs pessimistic) to
- // the current root, then we use the new one.
-
- Class currentRootType = dataContainer.getRoot() == null ? null : ((NodeInvocationDelegate) dataContainer.getRoot()).getDelegationTarget().getClass();
- Class tempRootType = ((NodeInvocationDelegate) tempRoot).getDelegationTarget().getClass();
-
- if (!tempRootType.equals(currentRootType)) dataContainer.setRoot(tempRoot);
- }
-
- private void startManualComponents()
- {
- // these 2 components need to be started manually since they can only be started after ALL other components have started.
- // i.e., rpcManager's start() method may do state transfers. State transfers will rely on the interceptor chain being started.
- // the interceptor chain cannot start until the rpcManager is started. And similarly, the buddyManager relies on the
- // rpcManager being started.
- if (rpcManager != null) rpcManager.start();
- if (buddyManager != null)
- {
- buddyManager.init();
- if (buddyManager.isEnabled())
- {
- dataContainer.registerInternalFqn(BuddyManager.BUDDY_BACKUP_SUBTREE_FQN);
- }
- }
- }
-
- /**
- * Asserts whether invocations are allowed on the cache or not. Returns <tt>true</tt> if invocations are to be allowed,
- * <tt>false</tt> otherwise. If the origin of the call is remote and the cache status is {@link org.jboss.cache.CacheStatus#STARTING},
- * this method will block for up to {@link org.jboss.cache.config.Configuration#getStateRetrievalTimeout()} millis, checking
- * for a valid state.
- *
- * @param originLocal true if the call originates locally (i.e., from the {@link org.jboss.cache.invocation.CacheInvocationDelegate} or false if it originates remotely, i.e., from the {@link org.jboss.cache.marshall.CommandAwareRpcDispatcher}.
- * @return true if invocations are allowed, false otherwise.
- */
- public boolean invocationsAllowed(boolean originLocal)
- {
- if (getCacheStatus().allowInvocations()) return true;
-
- // if this is a locally originating call and the cache is not in a valid state, return false.
- if (originLocal) return false;
-
- // else if this is a remote call and the status is STARTING, wait until the cache starts.
- if (getCacheStatus() == CacheStatus.STARTING)
- {
- try
- {
- blockUntilCacheStarts();
- return true;
- }
- catch (InterruptedException e)
- {
- Thread.currentThread().interrupt();
- }
- }
- else
- {
- log.warn("Received a remote call but the cache is not in STARTED state - ignoring call.");
- }
- return false;
- }
-
- /**
- * Blocks until the current cache instance is in it's {@link org.jboss.cache.CacheStatus#STARTED started} phase. Blocks
- * for up to {@link org.jboss.cache.config.Configuration#getStateRetrievalTimeout()} milliseconds, throwing an IllegalStateException
- * if the cache doesn't reach this state even after this maximum wait time.
- *
- * @throws InterruptedException if interrupted while waiting
- * @throws IllegalStateException if even after waiting the cache has not started.
- */
- private void blockUntilCacheStarts() throws InterruptedException, IllegalStateException
- {
- int pollFrequencyMS = 100;
- long startupWaitTime = configuration.getStateRetrievalTimeout();
- long giveUpTime = System.currentTimeMillis() + startupWaitTime;
-
- while (System.currentTimeMillis() < giveUpTime)
- {
- if (getCacheStatus().allowInvocations()) break;
- Thread.sleep(pollFrequencyMS);
- }
-
- // check if we have started.
- if (!getCacheStatus().allowInvocations())
- throw new IllegalStateException("Cache not in STARTED state, even after waiting " + configuration.getStateRetrievalTimeout() + " millis.");
- }
-
- public CacheStatus getCacheStatus()
- {
- return cacheStatus;
- }
-
- public ComponentRegistry getComponentRegistry()
- {
- return componentRegistry;
- }
-
- public void setCacheStatus(CacheStatus cacheStatus)
- {
- this.cacheStatus = cacheStatus;
- }
-}
Modified: core/trunk/src/main/java/org/jboss/cache/NodeFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/NodeFactory.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/NodeFactory.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -14,6 +14,7 @@
import org.jboss.cache.interceptors.InterceptorChain;
import org.jboss.cache.invocation.InvocationContextContainer;
import org.jboss.cache.invocation.NodeInvocationDelegate;
+import org.jboss.cache.lock.LockStrategyFactory;
import org.jboss.cache.optimistic.TransactionWorkspace;
import org.jboss.cache.optimistic.WorkspaceNode;
import org.jboss.cache.optimistic.WorkspaceNodeImpl;
@@ -33,12 +34,12 @@
private Configuration configuration;
private TransactionTable transactionTable;
private InvocationContextContainer invocationContextContainer;
- private LifecycleManager lifecycleManager;
private InterceptorChain interceptorChain;
private CommandsFactory commandsFactory;
+ private LockStrategyFactory lockStrategyFactory;
@Override
- protected <T> T construct(String componentName, Class<T> componentType)
+ protected <T> T construct(Class<T> componentType)
{
throw new UnsupportedOperationException("Should never be called!");
}
@@ -63,16 +64,16 @@
@Inject
private void injectDependencies(CacheSPI<K, V> cache, Configuration configuration, TransactionTable transactionTable,
- InvocationContextContainer invocationContextContainer, LifecycleManager lifecycleManager,
- InterceptorChain interceptorChain, CommandsFactory commandsFactory)
+ InvocationContextContainer invocationContextContainer,
+ InterceptorChain interceptorChain, CommandsFactory commandsFactory, LockStrategyFactory lockStrategyFactory)
{
this.cache = cache;
this.configuration = configuration;
this.transactionTable = transactionTable;
this.invocationContextContainer = invocationContextContainer;
- this.lifecycleManager = lifecycleManager;
this.interceptorChain = interceptorChain;
this.commandsFactory = commandsFactory;
+ this.lockStrategyFactory = lockStrategyFactory;
}
/**
@@ -106,12 +107,12 @@
NodeInvocationDelegate<K, V> nid = new NodeInvocationDelegate(un);
// Too slow to have these autowired for now. Look at manually wiring them.
- nid.initialize(configuration, invocationContextContainer, lifecycleManager, interceptorChain);
+ nid.initialize(configuration, invocationContextContainer, componentRegistry, interceptorChain);
nid.injectDependencies(cache);
- un.injectDependencies(cache, transactionTable, commandsFactory);
+ un.injectDependencies(cache, transactionTable, commandsFactory, lockStrategyFactory);
- componentRegistry.wireDependencies(nid);
- componentRegistry.wireDependencies(un);
+// componentRegistry.wireDependencies(nid);
+// componentRegistry.wireDependencies(un);
// back ref
un.setDelegate(nid);
return nid;
Modified: core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -11,7 +11,9 @@
import org.jboss.cache.commands.ReplicableCommand;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.config.RuntimeConfig;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.factories.annotations.Start;
import org.jboss.cache.factories.annotations.Stop;
import org.jboss.cache.interceptors.InterceptorChain;
import org.jboss.cache.invocation.InvocationContextContainer;
@@ -88,16 +90,16 @@
private TransactionManager txManager;
private TransactionTable txTable;
private InterceptorChain interceptorChain;
- private LifecycleManager lifecycleManager;
private boolean isUsingBuddyReplication;
private boolean isInLocalMode;
+ private ComponentKernel componentRegistry;
@Inject
private void setupDependencies(ChannelMessageListener messageListener, Configuration configuration, Notifier notifier,
CacheSPI spi, Marshaller marshaller, TransactionTable txTable,
TransactionManager txManager, InvocationContextContainer container, InterceptorChain interceptorChain,
- LifecycleManager lifecycleManager)
+ ComponentKernel componentRegistry)
{
this.messageListener = messageListener;
this.configuration = configuration;
@@ -108,13 +110,12 @@
this.txTable = txTable;
this.invocationContextContainer = container;
this.interceptorChain = interceptorChain;
- this.lifecycleManager = lifecycleManager;
+ this.componentRegistry = componentRegistry;
}
// ------------ START: Lifecycle methods ------------
- // TODO: 2.2.0: This needs to be started manually for now, rather than by @Start. See CacheImpl.internalStart()
-
+ @Start(priority = 15)
public void start()
{
switch (configuration.getCacheMode())
@@ -190,7 +191,7 @@
}
}
- @Stop
+ @Stop(priority = 8)
public void stop()
{
try
@@ -281,12 +282,12 @@
if (configuration.isUseRegionBasedMarshalling())
{
disp = new InactiveRegionAwareRpcDispatcher(channel, messageListener, new MembershipListenerAdaptor(),
- spi, invocationContextContainer, interceptorChain, lifecycleManager);
+ spi, invocationContextContainer, interceptorChain, componentRegistry);
}
else
{
disp = new CommandAwareRpcDispatcher(channel, messageListener, new MembershipListenerAdaptor(),
- invocationContextContainer, invocationContextContainer, interceptorChain, lifecycleManager);
+ invocationContextContainer, invocationContextContainer, interceptorChain, componentRegistry);
}
disp.setRequestMarshaller(marshaller);
Modified: core/trunk/src/main/java/org/jboss/cache/RegionManager.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/RegionManager.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/RegionManager.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -15,6 +15,7 @@
import org.jboss.cache.eviction.RegionNameConflictException;
import org.jboss.cache.factories.annotations.Destroy;
import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.factories.annotations.NonVolatile;
import org.jboss.cache.factories.annotations.Start;
import org.jboss.cache.factories.annotations.Stop;
import org.jboss.cache.lock.NodeLock;
@@ -35,6 +36,7 @@
* @since 2.0.0
*/
@ThreadSafe
+@NonVolatile
public class RegionManager
{
/**
@@ -91,6 +93,8 @@
}
setDefaultInactive(configuration.isInactiveOnStartup());
+
+ if (isUsingEvictions()) startEvictionThread();
}
@Stop
Modified: core/trunk/src/main/java/org/jboss/cache/UnversionedNode.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/UnversionedNode.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/UnversionedNode.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -12,6 +12,7 @@
import org.jboss.cache.commands.write.CreateNodeCommand;
import org.jboss.cache.factories.CommandsFactory;
import org.jboss.cache.lock.IdentityLock;
+import org.jboss.cache.lock.LockStrategyFactory;
import org.jboss.cache.marshall.MarshalledValue;
import org.jboss.cache.optimistic.DataVersion;
import org.jboss.cache.transaction.GlobalTransaction;
@@ -44,7 +45,7 @@
* Lock manager that manages locks to be acquired when accessing the node inside a transaction. Lazy set just in case
* locking is not needed.
*/
- protected transient IdentityLock lock_ = null;
+ protected transient IdentityLock lock = null;
/**
* A reference of the CacheImpl instance.
@@ -59,6 +60,7 @@
protected NodeSPI delegate;
private CommandsFactory commandsFactory;
+ protected LockStrategyFactory lockStrategyFactory;
/**
* Constructs a new node with an FQN of Root.
@@ -78,8 +80,20 @@
*/
protected UnversionedNode(Object child_name, Fqn fqn, Map data, boolean mapSafe, CacheSPI cache)
{
+ if (cache == null)
+ {
+ throw new IllegalArgumentException("no cache init for " + fqn);
+ }
+ if (!fqn.isRoot() && !child_name.equals(fqn.getLastElement()))
+ {
+ throw new IllegalArgumentException("Child " + child_name + " must be last part of " + fqn);
+ }
+
initFlags();
- init(child_name, fqn, cache);
+ this.cache = cache;
+ this.fqn = fqn;
+
+ init();
setInternalState(data);
}
@@ -103,30 +117,22 @@
this.delegate = delegate;
}
- public void injectDependencies(CacheSPI spi, TransactionTable transactionTable, CommandsFactory commandsFactory)
+ public void injectDependencies(CacheSPI spi, TransactionTable transactionTable, CommandsFactory commandsFactory, LockStrategyFactory lockStrategyFactory)
{
this.cache = spi;
this.transactionTable = transactionTable;
this.commandsFactory = commandsFactory;
+ this.lockStrategyFactory = lockStrategyFactory;
+ init();
}
/**
* Initializes with a name and FQN and cache.
*/
- private void init(Object child_name, Fqn fqn, CacheSPI cache)
+ private void init()
{
- if (cache == null)
- {
- throw new IllegalArgumentException("no cache init for " + fqn);
- }
- this.cache = cache;
- this.fqn = fqn;
- if (!fqn.isRoot() && !child_name.equals(fqn.getLastElement()))
- {
- throw new IllegalArgumentException("Child " + child_name + " must be last part of " + fqn);
- }
-
- setLockForChildInsertRemove(cache.getConfiguration().isLockParentForChildInsertRemove());
+ if (cache != null && cache.getConfiguration() != null)
+ setLockForChildInsertRemove(cache.getConfiguration().isLockParentForChildInsertRemove());
}
/**
@@ -143,9 +149,9 @@
protected synchronized void initLock()
{
- if (lock_ == null)
+ if (lock == null)
{
- lock_ = new IdentityLock(cache.getConfiguration().getIsolationLevel(), delegate);
+ lock = new IdentityLock(lockStrategyFactory, delegate);
}
}
@@ -201,18 +207,18 @@
private boolean isReadLocked()
{
- return lock_ != null && lock_.isReadLocked();
+ return lock != null && lock.isReadLocked();
}
private boolean isWriteLocked()
{
- return lock_ != null && lock_.isWriteLocked();
+ return lock != null && lock.isWriteLocked();
}
public IdentityLock getLock()
{
initLock();
- return lock_;
+ return lock;
}
public Map getDataDirect()
@@ -400,7 +406,7 @@
sb.append("]");
}
}
- if (lock_ != null)
+ if (lock != null)
{
if (isReadLocked())
{
Modified: core/trunk/src/main/java/org/jboss/cache/VersionedNode.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/VersionedNode.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/VersionedNode.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -8,7 +8,6 @@
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.lock.IdentityLock;
-import org.jboss.cache.lock.IsolationLevel;
import org.jboss.cache.optimistic.DataVersion;
import org.jboss.cache.optimistic.DefaultDataVersion;
@@ -84,7 +83,7 @@
@Override
protected synchronized void initLock()
{
- if (lock_ == null) lock_ = new IdentityLock(IsolationLevel.REPEATABLE_READ, delegate);
+ if (lock == null) lock = new IdentityLock(lockStrategyFactory, delegate);
}
@Override
Modified: core/trunk/src/main/java/org/jboss/cache/buddyreplication/BuddyManager.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/buddyreplication/BuddyManager.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/buddyreplication/BuddyManager.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -10,6 +10,7 @@
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.CacheException;
import org.jboss.cache.CacheSPI;
+import org.jboss.cache.DataContainer;
import org.jboss.cache.Fqn;
import org.jboss.cache.Node;
import org.jboss.cache.RPCManager;
@@ -27,6 +28,7 @@
import org.jboss.cache.config.Option;
import org.jboss.cache.factories.CommandsFactory;
import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.factories.annotations.Start;
import org.jboss.cache.factories.annotations.Stop;
import org.jboss.cache.lock.TimeoutException;
import org.jboss.cache.notifications.Notifier;
@@ -139,6 +141,7 @@
private ViewChangeListener viewChangeListener; // the view-change viewChangeListener
private boolean receivedBuddyInfo;
+ private DataContainer dataContainer;
public BuddyManager()
{
@@ -175,9 +178,9 @@
}
@Inject
- private void injectDependencies(CacheSPI cache, Configuration configuration, RegionManager regionManager,
- StateTransferManager stateTransferManager, RPCManager rpcManager, Notifier notifier,
- CommandsFactory factory)
+ public void injectDependencies(CacheSPI cache, Configuration configuration, RegionManager regionManager,
+ StateTransferManager stateTransferManager, RPCManager rpcManager, Notifier notifier,
+ CommandsFactory factory, DataContainer dataContainer)
{
this.cache = cache;
this.configuration = configuration;
@@ -186,7 +189,7 @@
this.rpcManager = rpcManager;
this.notifier = notifier;
this.commandsFactory = factory;
- setupInternals(configuration.getBuddyReplicationConfig());
+ this.dataContainer = dataContainer;
}
public BuddyReplicationConfig getConfig()
@@ -221,10 +224,10 @@
/**
* Stops the buddy manager and the related async thread.
*/
- @Stop
+ @Stop(priority = 5)
public void stop()
{
- if (config.isEnabled())
+ if (isEnabled())
{
log.debug("Stopping BuddyManager");
// unregister the viewChangeListener
@@ -241,52 +244,57 @@
}
}
- // TODO: 2.2.0: This needs to be started manually for now, rather than by @Start. See CacheImpl.internalStart()
+ @Start(priority = 20)
public void init() throws CacheException
{
- log.debug("Starting BuddyManager");
- buddyGroup = new BuddyGroup();
- buddyGroup.setDataOwner(cache.getLocalAddress());
- Address localAddress = rpcManager.getLocalAddress();
- if (localAddress == null)
+ setupInternals(configuration.getBuddyReplicationConfig());
+ if (isEnabled())
{
- if (configuration.getCacheMode() == Configuration.CacheMode.LOCAL)
+ log.debug("Starting BuddyManager");
+ dataContainer.registerInternalFqn(BuddyManager.BUDDY_BACKUP_SUBTREE_FQN);
+ buddyGroup = new BuddyGroup();
+ buddyGroup.setDataOwner(cache.getLocalAddress());
+ Address localAddress = rpcManager.getLocalAddress();
+ if (localAddress == null)
{
- log.warn("Buddy replication is enabled but cache mode is LOCAL - not starting BuddyManager!");
- ReflectionUtil.setValue(config, "accessible", true);
- config.setEnabled(false);
- return;
+ if (configuration.getCacheMode() == Configuration.CacheMode.LOCAL)
+ {
+ log.warn("Buddy replication is enabled but cache mode is LOCAL - not starting BuddyManager!");
+ ReflectionUtil.setValue(config, "accessible", true);
+ config.setEnabled(false);
+ return;
+ }
+ else
+ {
+ throw new CacheException("Unable to initialize BuddyManager - the RPCManager has not connected to the cluster and local Address is null!");
+ }
}
- else
+ buddyGroup.setGroupName(BuddyFqnTransformer.getGroupNameFromAddress(localAddress));
+
+ if (config.getBuddyPoolName() != null)
{
- throw new CacheException("Unable to initialize BuddyManager - the RPCManager has not connected to the cluster and local Address is null!");
+ buddyPool.put(buddyGroup.getDataOwner(), config.getBuddyPoolName());
}
- }
- buddyGroup.setGroupName(BuddyFqnTransformer.getGroupNameFromAddress(localAddress));
- if (config.getBuddyPoolName() != null)
- {
- buddyPool.put(buddyGroup.getDataOwner(), config.getBuddyPoolName());
- }
+ broadcastBuddyPoolMembership();
- broadcastBuddyPoolMembership();
+ if (!cache.exists(BUDDY_BACKUP_SUBTREE_FQN)) cache.getRoot().addChildDirect(BUDDY_BACKUP_SUBTREE_FQN);
- if (!cache.exists(BUDDY_BACKUP_SUBTREE_FQN)) cache.getRoot().addChildDirect(BUDDY_BACKUP_SUBTREE_FQN);
+ // allow waiting threads to process.
+ initialisationLatch.countDown();
- // allow waiting threads to process.
- initialisationLatch.countDown();
+ // register a CacheImpl Listener to reassign buddies as and when view changes occur
+ viewChangeListener = new ViewChangeListener();
- // register a CacheImpl Listener to reassign buddies as and when view changes occur
- viewChangeListener = new ViewChangeListener();
+ cache.addCacheListener(viewChangeListener);
- cache.addCacheListener(viewChangeListener);
+ // assign buddies based on what we know now
+ reassignBuddies(cache.getMembers());
+ queue.clear();
+ asyncViewChangeHandler.start();
- // assign buddies based on what we know now
- reassignBuddies(cache.getMembers());
- queue.clear();
- asyncViewChangeHandler.start();
-
- initFqnTransformer(buddyGroup.getGroupName(), commandsFactory);
+ initFqnTransformer(buddyGroup.getGroupName(), commandsFactory);
+ }
}
void initFqnTransformer(String groupName, CommandsFactory commandsFactory)
@@ -1010,6 +1018,9 @@
{
Fqn defunctBackupRootFqn = getDefunctBackupRootFqn(dataOwner);
+ if (trace) log.trace("Migrating defunct data. Backup root is " + backupRoot);
+ if (trace) log.trace("Children of backup root are " + backupRoot.getChildren());
+
for (Object child : backupRoot.getChildren())
{
Fqn childFqn = ((Node) child).getFqn();
@@ -1151,8 +1162,15 @@
for (Address a : toRemove)
{
BuddyGroup bg = buddyGroupsIParticipateIn.remove(a);
- Node backupRoot = cache.getNode(BuddyFqnTransformer.getBackupRoot(bg.getDataOwner()));
- migrateDefunctData(backupRoot, bg.getDataOwner());
+ Fqn backupRootFqn = BuddyFqnTransformer.getBackupRoot(bg.getDataOwner());
+ Node backupRoot = cache.getNode(backupRootFqn);
+ if (backupRoot != null)
+ {
+ // could be a race condition where the backup region has been removed because we have been removed
+ // from the buddy group, but the buddyGroupsIParticipateIn map hasn't been updated.
+ migrateDefunctData(backupRoot, bg.getDataOwner());
+ }
+
}
}
}
Modified: core/trunk/src/main/java/org/jboss/cache/cluster/ReplicationQueue.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/cluster/ReplicationQueue.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/cluster/ReplicationQueue.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -69,6 +69,8 @@
this.rpcManager = rpcManager;
this.configuration = configuration;
this.commandsFactory = commandsFactory;
+
+ // this is checked again in Start
enabled = configuration.isUseReplQueue() && (configuration.getBuddyReplicationConfig() == null || !configuration.getBuddyReplicationConfig().isEnabled());
}
Modified: core/trunk/src/main/java/org/jboss/cache/commands/write/EvictCommand.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/commands/write/EvictCommand.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/commands/write/EvictCommand.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -117,7 +117,7 @@
@Override
public String toString()
{
- return "EvictNodeCommand{" +
+ return "EvictCommand{" +
"fqn=" + fqn +
", recursive=" + recursive +
", dataVersion=" + dataVersion +
Modified: core/trunk/src/main/java/org/jboss/cache/config/Configuration.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/config/Configuration.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/config/Configuration.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -8,6 +8,7 @@
import org.jboss.cache.Version;
import org.jboss.cache.factories.XmlConfigurationParser;
+import org.jboss.cache.factories.annotations.NonVolatile;
import org.jboss.cache.lock.IsolationLevel;
import org.jboss.cache.marshall.Marshaller;
import org.w3c.dom.Element;
@@ -20,6 +21,7 @@
*
* @author <a href="mailto:manik@jboss.org">Manik Surtani (manik(a)jboss.org)</a>
*/
+@NonVolatile
public class Configuration extends ConfigurationComponent
{
private static final long serialVersionUID = 5553791890144997466L;
Modified: core/trunk/src/main/java/org/jboss/cache/config/ConfigurationComponent.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/config/ConfigurationComponent.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/config/ConfigurationComponent.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -10,7 +10,7 @@
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.CacheSPI;
import org.jboss.cache.CacheStatus;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.factories.annotations.Start;
@@ -35,7 +35,7 @@
protected transient Log log = LogFactory.getLog(getClass());
private transient CacheSPI cache; // back-reference to test whether the cache is running.
private final Set<ConfigurationComponent> children = Collections.synchronizedSet(new HashSet<ConfigurationComponent>());
- private ComponentRegistry cr;
+ private ComponentKernel cr;
// a workaround to get over immutability checks
private boolean accessible;
@@ -138,7 +138,7 @@
}
@Inject
- private void injectDependencies(ComponentRegistry cr)
+ private void injectDependencies(ComponentKernel cr)
{
this.cr = cr;
}
Added: core/trunk/src/main/java/org/jboss/cache/factories/BootstrapFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/BootstrapFactory.java (rev 0)
+++ core/trunk/src/main/java/org/jboss/cache/factories/BootstrapFactory.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -0,0 +1,41 @@
+package org.jboss.cache.factories;
+
+import org.jboss.cache.CacheException;
+import org.jboss.cache.CacheSPI;
+import org.jboss.cache.config.Configuration;
+import org.jboss.cache.factories.annotations.DefaultFactoryFor;
+import org.jboss.cache.factories.annotations.NonVolatile;
+
+/**
+ * // TODO: MANIK: Document this
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @since 2.2.0
+ */
+@DefaultFactoryFor(classes = {CacheSPI.class, Configuration.class, ComponentKernel.class})
+@NonVolatile
+public class BootstrapFactory extends ComponentFactory
+{
+ CacheSPI cacheSPI;
+ Configuration configuration;
+ ComponentKernel componentRegistry;
+
+ public BootstrapFactory(CacheSPI cacheSPI, Configuration configuration, ComponentKernel componentRegistry)
+ {
+ this.cacheSPI = cacheSPI;
+ this.configuration = configuration;
+ this.componentRegistry = componentRegistry;
+ }
+
+ @SuppressWarnings("unchecked")
+ protected <T> T construct(Class<T> componentType)
+ {
+ if (componentType.equals(CacheSPI.class)) return (T) cacheSPI;
+
+ if (componentType.equals(Configuration.class)) return (T) configuration;
+
+ if (componentType.equals(ComponentKernel.class)) return (T) componentRegistry;
+
+ throw new CacheException("Don't know how to handle type " + componentType);
+ }
+}
Modified: core/trunk/src/main/java/org/jboss/cache/factories/BuddyManagerFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/BuddyManagerFactory.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/factories/BuddyManagerFactory.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -14,11 +14,11 @@
public class BuddyManagerFactory extends EmptyConstructorFactory
{
@Override
- public <T> T construct(String componentName, Class<T> componentType)
+ public <T> T construct(Class<T> componentType)
{
if (configuration.getBuddyReplicationConfig() != null && configuration.getBuddyReplicationConfig().isEnabled() && configuration.getCacheMode() != Configuration.CacheMode.LOCAL)
{
- return super.construct(componentName, componentType);
+ return super.construct(componentType);
}
else
{
Modified: core/trunk/src/main/java/org/jboss/cache/factories/CommandsFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/CommandsFactory.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/factories/CommandsFactory.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -38,6 +38,7 @@
import org.jboss.cache.commands.write.RemoveNodeCommand;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.factories.annotations.NonVolatile;
import org.jboss.cache.interceptors.InterceptorChain;
import org.jboss.cache.notifications.Notifier;
import org.jboss.cache.transaction.GlobalTransaction;
@@ -61,6 +62,7 @@
* @author Mircea.Markus(a)jboss.com
* @since 2.2
*/
+@NonVolatile
public class CommandsFactory
{
private RPCManager rpcManager;
Modified: core/trunk/src/main/java/org/jboss/cache/factories/ComponentFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/ComponentFactory.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/factories/ComponentFactory.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -16,17 +16,17 @@
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
* @see Inject
- * @see ComponentRegistry
+ * @see ComponentKernel
* @since 2.1.0
*/
public abstract class ComponentFactory
{
protected final Log log = LogFactory.getLog(getClass());
- protected ComponentRegistry componentRegistry;
+ protected ComponentKernel componentRegistry;
protected Configuration configuration;
@Inject
- private void injectDependencies(Configuration configuration, ComponentRegistry componentRegistry)
+ private void injectDependencies(Configuration configuration, ComponentKernel componentRegistry)
{
this.configuration = configuration;
this.componentRegistry = componentRegistry;
@@ -35,11 +35,10 @@
/**
* Constructs a component.
*
- * @param componentName optional, if the ComponentName annotation is used with the parameter, it's value is passed in here for the implementing factory to use.
* @param componentType type of component
* @return a component
*/
- protected abstract <T> T construct(String componentName, Class<T> componentType);
+ protected abstract <T> T construct(Class<T> componentType);
protected void assertTypeConstructable(Class requestedType, Class... ableToConstruct)
{
Copied: core/trunk/src/main/java/org/jboss/cache/factories/ComponentKernel.java (from rev 5795, core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java)
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/ComponentKernel.java (rev 0)
+++ core/trunk/src/main/java/org/jboss/cache/factories/ComponentKernel.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -0,0 +1,931 @@
+package org.jboss.cache.factories;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.cache.CacheException;
+import org.jboss.cache.CacheStatus;
+import org.jboss.cache.Version;
+import org.jboss.cache.config.Configuration;
+import org.jboss.cache.config.ConfigurationException;
+import org.jboss.cache.config.RuntimeConfig;
+import org.jboss.cache.factories.annotations.DefaultFactoryFor;
+import org.jboss.cache.factories.annotations.Destroy;
+import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.factories.annotations.NonVolatile;
+import org.jboss.cache.factories.annotations.Start;
+import org.jboss.cache.factories.annotations.Stop;
+import org.jboss.cache.util.BeanUtils;
+import org.jboss.cache.util.reflect.CachedMethod;
+import org.jboss.cache.util.reflect.ReflectionUtil;
+
+import javax.management.MBeanServerFactory;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A registry where components which have been created are stored. Components are stored as singletons, registered under
+ * a specific name.
+ * <p/>
+ * Components can be retrieved from the registry using {@link #getComponent(Class)}.
+ * <p/>
+ * Components can be registered using {@link #registerComponent(Object, Class)}, which will cause any dependencies to be
+ * wired in as well. Components that need to be created as a result of wiring will be done using {@link #getOrCreateComponent(Class)},
+ * which will look up the default factory for the component type (factories annotated with the appropriate {@link DefaultFactoryFor} annotation.
+ * <p/>
+ * Default factories are treated as components too and will need to be wired before being used.
+ * <p/>
+ * The registry can exist in one of 5 states, as defined by the {@link CacheStatus} enumeration. In terms of the cache,
+ * state changes in the following manner:
+ * <ul>
+ * <li>CONSTRUCTED - when first constructed</li>
+ * <li>WIRED - when created using the DefaultCacheFactory</li>
+ * <li>When {@link org.jboss.cache.Cache#create()} is called, the components are rewired.</li>
+ * <li>STARTED - when {@link org.jboss.cache.Cache#start()} is called</li>
+ * <li>STOPPED - when {@link org.jboss.cache.Cache#stop()} is called</li>
+ * <li>DESTROYED - when {@link org.jboss.cache.Cache#destroy()} is called.</li>
+ * </ul>
+ * <p/>
+ * Cache configuration can only be changed and will only be reinjected if the cache is not in the {@link org.jboss.cache.CacheStatus#STARTED} state.
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @since 2.1.0
+ */
+@NonVolatile
+public class ComponentKernel
+{
+ /**
+ * Contains class definitions of component factories that can be used to construct certain components
+ */
+ Map<Class, Class<? extends ComponentFactory>> defaultFactories = null;
+
+ private static final Log log = LogFactory.getLog(ComponentKernel.class);
+ private static final boolean trace = log.isTraceEnabled();
+ protected static final Object NULL_COMPONENT = new Object();
+
+ // component and method containers
+ final Map<String, Component> componentLookup = new HashMap<String, Component>();
+ final List<PrioritizedMethod> startMethods = new ArrayList<PrioritizedMethod>();
+ final List<PrioritizedMethod> stopMethods = new ArrayList<PrioritizedMethod>();
+ final List<PrioritizedMethod> destroyMethods = new ArrayList<PrioritizedMethod>();
+
+ CacheStatus state = CacheStatus.INSTANTIATED;
+
+ /**
+ * Hook to shut down the cache when the JVM exits.
+ */
+ private Thread shutdownHook;
+ /**
+ * A flag that the shutdown hook sets before calling cache.stop(). Allows stop() to identify if it has been called
+ * from a shutdown hook.
+ */
+ private boolean invokedFromShutdownHook;
+
+
+ /**
+ * Creates an instance of the component registry. The configuration passed in is automatically registered.
+ *
+ * @param configuration configuration with which this is created
+ */
+ public ComponentKernel(Configuration configuration)
+ {
+ try
+ {
+ // bootstrap.
+ registerDefaultClassLoader(null);
+ registerComponent(this, ComponentKernel.class);
+ registerComponent(configuration, Configuration.class);
+ }
+ catch (Exception e)
+ {
+ throw new CacheException("Unable to construct ComponentRegistry", e);
+ }
+ }
+
+ /**
+ * Retrieves the state of the registry
+ *
+ * @return state of the registry
+ */
+ public CacheStatus getState()
+ {
+ return state;
+ }
+
+ /**
+ * Wires an object instance with dependencies annotated with the {@link org.jboss.cache.factories.annotations.Inject} annotation, creating more components
+ * as needed based on the Configuration passed in if these additional components don't exist in the
+ * {@link org.jboss.cache.factories.ComponentKernel}. Strictly for components that don't otherwise live in the registry and have a lifecycle, such as Nodes.
+ *
+ * @param target object to wire
+ * @throws ConfigurationException if there is a problem wiring the instance
+ */
+ public void wireDependencies(Object target) throws ConfigurationException
+ {
+ try
+ {
+ List<CachedMethod> methods = ReflectionUtil.getAllCachedMethods(target.getClass(), Inject.class);
+
+ // search for anything we need to inject
+ for (CachedMethod method : methods) invokeInjectionMethod(target, method);
+ }
+ catch (Exception e)
+ {
+ throw new ConfigurationException("Unable to configure component (type: " + target.getClass() + ", instance " + target + ")", e);
+ }
+ }
+
+ /**
+ * Registers the default class loader. This method *must* be called before any other components are registered,
+ * typically called by bootstrap code. Defensively, it is called in the constructor of ComponentRegistry with a null
+ * parameter.
+ *
+ * @param loader a class loader to use by default. If this is null, the class loader used to load this instance of ComponentRegistry is used.
+ */
+ public void registerDefaultClassLoader(ClassLoader loader)
+ {
+ registerComponent(loader == null ? getClass().getClassLoader() : loader, ClassLoader.class);
+ // make sure the class loader is non-volatile, so it survives restarts.
+ componentLookup.get(ClassLoader.class.getName()).nonVolatile = true;
+ }
+
+ /**
+ * This is hard coded for now, since scanning the classpath for factories annotated with {@link org.jboss.cache.factories.annotations.DefaultFactoryFor}
+ * does not work with all class loaders. This is a temporary solution until a more elegant one can be designed.
+ * <p/>
+ * BE SURE TO ADD ANY NEW FACTORY TYPES ANNOTATED WITH DefaultFactoryFor TO THIS SET!!
+ * <p/>
+ *
+ * @return set of known factory types.
+ */
+ private Set<Class<? extends ComponentFactory>> getHardcodedFactories()
+ {
+ Set<Class<? extends ComponentFactory>> s = new HashSet<Class<? extends ComponentFactory>>();
+ s.add(BootstrapFactory.class);
+ s.add(BuddyManagerFactory.class);
+ s.add(EmptyConstructorFactory.class);
+ s.add(InterceptorChainFactory.class);
+ s.add(RuntimeConfigAwareFactory.class);
+ s.add(TransactionManagerFactory.class);
+ s.add(ReplicationQueueFactory.class);
+ return s;
+ }
+
+ /**
+ * Registers a component in the registry under the given type, and injects any dependencies needed. If a component
+ * of this type already exists, it is overwritten.
+ *
+ * @param component component to register
+ * @param type type of component
+ */
+ public void registerComponent(Object component, Class type)
+ {
+ Component c = new Component();
+ String name = type.getName();
+ c.name = name;
+ c.nonVolatile = component.getClass().isAnnotationPresent(NonVolatile.class);
+ c.instance = component;
+ Component old = componentLookup.get(name);
+
+ if (old != null)
+ {
+ // if they are equal don't bother
+ if (old.instance.equals(component))
+ {
+ if (trace)
+ log.trace("Attempting to register a component equal to one that already exists under the same name (" + name + "). Not doing anything.");
+ return;
+ }
+ }
+
+ if (trace) log.trace("Registering component " + c + " under name " + name);
+
+ if (old != null)
+ {
+ if (trace) log.trace("Replacing old component " + old);
+ old.instance = component;
+ }
+ else
+ {
+ componentLookup.put(name, c);
+ }
+ addComponentDependencies(c);
+ // inject dependencies for this component
+ c.injectDependencies();
+ }
+
+ /**
+ * Adds component dependencies for a given component, by populating {@link Component#injectionMethods}.
+ *
+ * @param c component to add dependencies to
+ */
+ protected void addComponentDependencies(Component c)
+ {
+ Class type = c.instance.getClass();
+ List<CachedMethod> methods = ReflectionUtil.getAllCachedMethods(type, Inject.class);
+
+ for (CachedMethod m : methods) c.injectionMethods.add(m);
+ }
+
+ @SuppressWarnings("unchecked")
+ protected void invokeInjectionMethod(Object o, CachedMethod m)
+ {
+ Class[] dependencies = m.getParameterTypes();
+ Object[] params = new Object[dependencies.length];
+
+ for (int i = 0; i < dependencies.length; i++)
+ {
+ params[i] = getOrCreateComponent(dependencies[i]);
+ }
+
+ ReflectionUtil.invokeAccessibly(o, m.getMethod(), params);
+ }
+
+ /**
+ * Retrieves a component if one exists, and if not, attempts to find a factory capable of constructing the component
+ * (factories annotated with the {@link DefaultFactoryFor} annotation that is capable of creating the component class).
+ * <p/>
+ * If an instance needs to be constructed, dependencies are then automatically wired into the instance, based on methods
+ * on the component type annotated with {@link Inject}.
+ * <p/>
+ * Summing it up, component retrieval happens in the following order:<br />
+ * 1. Look for a component that has already been created and registered.
+ * 2. Look for an appropriate component that exists in the {@link Configuration} that may be injected from an external system.
+ * 3. Look for a class definition passed in to the {@link org.jboss.cache.config.Configuration} - such as an EvictionPolicy implementation
+ * 4. Attempt to create it by looking for an appropriate factory (annotated with {@link DefaultFactoryFor})
+ * <p/>
+ *
+ * @param componentClass type of component to be retrieved. Should not be null.
+ * @return a fully wired component instance, or null if one cannot be found or constructed.
+ * @throws ConfigurationException if there is a problem with consructing or wiring the instance.
+ */
+ protected <T> T getOrCreateComponent(Class<T> componentClass)
+ {
+
+ T component = getComponent(componentClass);
+
+ if (component == null)
+ {
+ // first see if this has been injected externally.
+ component = getFromConfiguration(componentClass);
+ boolean attemptedFactoryConstruction = false;
+
+ if (component == null)
+ {
+ // create this component and add it to the registry
+ ComponentFactory factory = getFactory(componentClass);
+ component = factory.construct(componentClass);
+ attemptedFactoryConstruction = true;
+
+ }
+
+ if (component != null)
+ {
+ registerComponent(component, componentClass);
+ }
+ else if (attemptedFactoryConstruction)
+ {
+ if (trace) log.trace("Registering a null for component " + componentClass.getSimpleName());
+ registerNullComponent(componentClass);
+ }
+ }
+
+ return component;
+ }
+
+ /**
+ * Retrieves a component factory instance capable of constructing components of a specified type. If the factory doesn't
+ * exist in the registry, one is created.
+ *
+ * @param componentClass type of component to construct
+ * @return component factory capable of constructing such components
+ */
+ protected ComponentFactory getFactory(Class componentClass)
+ {
+ if (defaultFactories == null) scanDefaultFactories();
+ Class<? extends ComponentFactory> cfClass = defaultFactories.get(componentClass);
+ if (cfClass == null)
+ throw new ConfigurationException("No registered default factory for component " + componentClass + " found!");
+ // a component factory is a component too! See if one has been created and exists in the registry
+ ComponentFactory cf = getComponent(cfClass);
+ if (cf == null)
+ {
+ // hasn't yet been created. Create and put in registry
+ cf = instantiateFactory(cfClass);
+ if (cf != null)
+ {
+ // we simply register this factory. Registration will take care of constructing any dependencies.
+ registerComponent(cf, cfClass);
+ }
+ }
+
+ if (cf == null)
+ throw new ConfigurationException("Unable to locate component factory for component " + componentClass);
+
+ // ensure the component factory is in the STARTED state!
+ Component c = componentLookup.get(cfClass.getName());
+ if (c.instance != cf)
+ throw new ConfigurationException("Component factory " + cfClass + " incorrectly registered!");
+ return cf;
+ }
+
+ /**
+ * Scans the class path for classes annotated with {@link org.jboss.cache.factories.annotations.DefaultFactoryFor}, and
+ * analyses which components can be created by such factories.
+ */
+ void scanDefaultFactories()
+ {
+ defaultFactories = new HashMap<Class, Class<? extends ComponentFactory>>();
+
+ Set<Class<? extends ComponentFactory>> factories = getHardcodedFactories();
+
+ for (Class<? extends ComponentFactory> factory : factories)
+ {
+ DefaultFactoryFor dFFAnnotation = factory.getAnnotation(DefaultFactoryFor.class);
+ for (Class targetClass : dFFAnnotation.classes()) defaultFactories.put(targetClass, factory);
+ }
+ }
+
+ /**
+ * No such thing as a meta factory yet. Factories are created using this method which attempts to use an empty public
+ * constructor.
+ *
+ * @param factory class of factory to be created
+ * @return factory instance
+ */
+ ComponentFactory instantiateFactory(Class<? extends ComponentFactory> factory)
+ {
+ try
+ {
+ return factory.newInstance();
+ }
+ catch (Exception e)
+ {
+ // unable to get a hold of an instance!!
+ throw new ConfigurationException("Unable to instantiate factory " + factory, e);
+ }
+ }
+
+ /**
+ * registers a special "null" component that has no dependencies.
+ *
+ * @param type type of component to register as a null
+ */
+ void registerNullComponent(Class type)
+ {
+ registerComponent(NULL_COMPONENT, type);
+ }
+
+ /**
+ * Retrieves a component from the {@link Configuration} or {@link RuntimeConfig}.
+ *
+ * @param componentClass component type
+ * @return component, or null if it cannot be found
+ */
+ @SuppressWarnings("unchecked")
+ protected <T> T getFromConfiguration(Class<T> componentClass)
+ {
+ if (log.isDebugEnabled())
+ log.debug("Looking in configuration for an instance of " + componentClass + " that may have been injected from an external source.");
+ Method getter = BeanUtils.getterMethod(Configuration.class, componentClass);
+ T returnValue = null;
+
+ if (getter != null)
+ {
+ try
+ {
+ returnValue = (T) getter.invoke(getConfiguration());
+ }
+ catch (Exception e)
+ {
+ log.warn("Unable to invoke getter " + getter + " on Configuration.class!", e);
+ }
+ }
+
+ // now try the RuntimeConfig - a legacy "registry" of sorts.
+ if (returnValue == null)
+ {
+ getter = BeanUtils.getterMethod(RuntimeConfig.class, componentClass);
+ if (getter != null)
+ {
+ try
+ {
+ returnValue = (T) getter.invoke(getConfiguration().getRuntimeConfig());
+ }
+ catch (Exception e)
+ {
+ log.warn("Unable to invoke getter " + getter + " on RuntimeConfig.class!", e);
+ }
+ }
+ }
+ return returnValue;
+ }
+
+ /**
+ * Retrieves the configuration component.
+ *
+ * @return a Configuration object
+ */
+ protected Configuration getConfiguration()
+ {
+ // this is assumed to always be present as a part of the bootstrap/construction of a ComponentRegistry.
+ return getComponent(Configuration.class);
+ }
+
+ /**
+ * Retrieves a component of a specified type from the registry, or null if it cannot be found.
+ *
+ * @param type type to find
+ * @return component, or null
+ */
+ @SuppressWarnings("unchecked")
+ public <T> T getComponent(Class<T> type)
+ {
+ Component wrapper = componentLookup.get(type.getName());
+ if (wrapper == null) return null;
+
+ return (T) (wrapper.instance == NULL_COMPONENT ? null : wrapper.instance);
+ }
+
+ /**
+ * Marks state as wired. Used by the DefaultCacheFactory after it has added the BootstrapFactory and CacheSPI components.
+ */
+ public void wire()
+ {
+ state = CacheStatus.CREATED;
+ }
+
+ /**
+ * Rewires components. Can only be called if the current state is WIRED or STARTED.
+ */
+ public void rewire()
+ {
+ // need to re-inject everything again.
+ for (Component c : new HashSet<Component>(componentLookup.values()))
+ {
+ // inject dependencies for this component
+ c.injectDependencies();
+ }
+ }
+
+ /**
+ * Scans each registered component for lifecycle methods, and adds them to the appropriate lists, and then sorts them
+ * by priority.
+ */
+ private void populateLifecycleMethods()
+ {
+ // cache a list of the start annotated methods
+ startMethods.clear();
+ for (Component c : componentLookup.values())
+ {
+ List<Method> methods = ReflectionUtil.getAllMethods(c.instance.getClass(), Start.class);
+ for (Method m : methods)
+ {
+ PrioritizedMethod em = new PrioritizedMethod();
+ em.component = c;
+ em.method = m;
+ em.priority = m.getAnnotation(Start.class).priority();
+ startMethods.add(em);
+ }
+ }
+
+ // cache a list of the stop annotated methods
+ stopMethods.clear();
+ for (Component c : componentLookup.values())
+ {
+ List<Method> methods = ReflectionUtil.getAllMethods(c.instance.getClass(), Stop.class);
+ for (Method m : methods)
+ {
+ PrioritizedMethod em = new PrioritizedMethod();
+ em.component = c;
+ em.method = m;
+ em.priority = m.getAnnotation(Stop.class).priority();
+ stopMethods.add(em);
+ }
+ }
+
+ // cache a list of the destroy annotated methods
+ destroyMethods.clear();
+ for (Component c : componentLookup.values())
+ {
+ List<Method> methods = ReflectionUtil.getAllMethods(c.instance.getClass(), Destroy.class);
+ for (Method m : methods)
+ {
+ PrioritizedMethod em = new PrioritizedMethod();
+ em.component = c;
+ em.method = m;
+ em.priority = m.getAnnotation(Destroy.class).priority();
+ destroyMethods.add(em);
+ }
+ }
+
+ Collections.sort(startMethods);
+ Collections.sort(stopMethods);
+ Collections.sort(destroyMethods);
+ }
+
+ /**
+ * Removes any components not annotated as @NonVolatile.
+ */
+ public void resetNonVolatile()
+ {
+ // destroy all components to clean up resources
+ for (Component c : new HashSet<Component>(componentLookup.values()))
+ {
+ // the component is volatile!!
+ if (!c.nonVolatile)
+ {
+ componentLookup.remove(c.name);
+ }
+ }
+
+ if (trace) log.trace("Reset volatile components");
+ }
+
+ // ------------------------------ START: Publicly available lifecycle methods -----------------------------
+ // These methods perform a check for appropriate transition and then delegate to similarly named internal methods.
+
+ /**
+ * Creates the components needed by a cache instance and sets the cache status to {@link org.jboss.cache.CacheStatus#CREATED}
+ * when it is done.
+ */
+ public void create()
+ {
+ if (!state.createAllowed())
+ {
+ if (state.needToDestroyFailedCache())
+ destroy();
+ else
+ return;
+ }
+
+ try
+ {
+ internalCreate();
+ }
+ catch (Throwable t)
+ {
+ handleLifecycleTransitionFailure(t);
+ }
+ }
+
+ /**
+ * This starts the components in the cache, connecting to channels, starting service threads, etc. If the cache is
+ * not in the {@link org.jboss.cache.CacheStatus#CREATED} state, {@link #create()} will be invoked first.
+ */
+ public void start()
+ {
+ boolean createdInStart = false;
+ if (!state.startAllowed())
+ {
+ if (state.needToDestroyFailedCache())
+ destroy(); // this will take us back to DESTROYED
+
+ if (state.needCreateBeforeStart())
+ {
+ create();
+ createdInStart = true;
+ }
+ else
+ return;
+ }
+
+ try
+ {
+ internalStart(createdInStart);
+ }
+ catch (Throwable t)
+ {
+ handleLifecycleTransitionFailure(t);
+ }
+ }
+
+ /**
+ * Stops the cache and sets the cache status to {@link org.jboss.cache.CacheStatus#STOPPED} once it is done. If the cache is not in
+ * the {@link org.jboss.cache.CacheStatus#STARTED} state, this is a no-op.
+ */
+ public void stop()
+ {
+ if (!state.stopAllowed())
+ {
+ return;
+ }
+
+ // Trying to stop() from FAILED is valid, but may not work
+ boolean failed = state == CacheStatus.FAILED;
+
+ try
+ {
+ internalStop();
+ }
+ catch (Throwable t)
+ {
+ if (failed)
+ {
+ log.warn("Attempted to stop() from FAILED state, but caught exception; try calling destroy()", t);
+ }
+ handleLifecycleTransitionFailure(t);
+ }
+ finally
+ {
+ if (!failed) state = CacheStatus.STOPPED;
+ }
+ }
+
+ /**
+ * Destroys the cache and frees up any resources. Sets the cache status to {@link CacheStatus#DESTROYED} when it is done.
+ * <p/>
+ * If the cache is in {@link org.jboss.cache.CacheStatus#STARTED} when this method is called, it will first call {@link #stop()}
+ * to stop the cache.
+ */
+ public void destroy()
+ {
+ if (!state.destroyAllowed())
+ {
+ if (state.needStopBeforeDestroy())
+ {
+ try
+ {
+ stop();
+ }
+ catch (CacheException e)
+ {
+ log.warn("Needed to call stop() before destroying but stop() threw exception. Proceeding to destroy", e);
+ }
+ }
+ else
+ return;
+ }
+
+ try
+ {
+ internalDestroy();
+ }
+ finally
+ {
+ // We always progress to destroyed
+ state = CacheStatus.DESTROYED;
+ }
+ }
+ // ------------------------------ END: Publicly available lifecycle methods -----------------------------
+
+ // ------------------------------ START: Actual internal lifecycle methods --------------------------------
+
+ /**
+ * Sets the cacheStatus to FAILED and rethrows the problem as one
+ * of the declared types. Converts any non-RuntimeException Exception
+ * to CacheException.
+ *
+ * @param t throwable thrown during failure
+ */
+ private void handleLifecycleTransitionFailure(Throwable t)
+ {
+ state = CacheStatus.FAILED;
+ if (t instanceof CacheException)
+ throw (CacheException) t;
+ else if (t instanceof RuntimeException)
+ throw (RuntimeException) t;
+ else if (t instanceof Error)
+ throw (Error) t;
+ else
+ throw new CacheException(t);
+ }
+
+ /**
+ * The actual create implementation.
+ */
+ private void internalCreate()
+ {
+ state = CacheStatus.CREATING;
+ resetNonVolatile();
+ rewire();
+ state = CacheStatus.CREATED;
+ }
+
+ private void internalStart(boolean createdInStart) throws CacheException, IllegalArgumentException
+ {
+ if (!createdInStart)
+ {
+ // re-wire all dependencies in case stuff has changed since the cache was created
+ // remove any components whose construction may have depended upon a configuration that may have changed.
+ resetNonVolatile();
+ rewire();
+ }
+
+ state = CacheStatus.STARTING;
+
+ // start all internal components
+ // first cache all start, stop and destroy methods.
+ populateLifecycleMethods();
+
+ // fire all START methods according to priority
+ for (PrioritizedMethod em : startMethods) em.invoke();
+
+ addShutdownHook();
+
+ log.info("JBoss Cache version: " + Version.printVersion());
+ state = CacheStatus.STARTED;
+ }
+
+ private void addShutdownHook()
+ {
+ ArrayList al = MBeanServerFactory.findMBeanServer(null);
+ boolean registerShutdownHook = (getConfiguration().getShutdownHookBehavior() == Configuration.ShutdownHookBehavior.DEFAULT && al.size() == 0)
+ || getConfiguration().getShutdownHookBehavior() == Configuration.ShutdownHookBehavior.REGISTER;
+
+ if (registerShutdownHook)
+ {
+ if (log.isTraceEnabled())
+ log.trace("Registering a shutdown hook. Configured behavior = " + getConfiguration().getShutdownHookBehavior());
+ shutdownHook = new Thread()
+ {
+ @Override
+ public void run()
+ {
+ try
+ {
+ invokedFromShutdownHook = true;
+ ComponentKernel.this.stop();
+ }
+ finally
+ {
+ invokedFromShutdownHook = false;
+ }
+ }
+ };
+
+ Runtime.getRuntime().addShutdownHook(shutdownHook);
+ }
+ else
+ {
+ if (log.isTraceEnabled())
+ log.trace("Not registering a shutdown hook. Configured behavior = " + getConfiguration().getShutdownHookBehavior());
+ }
+ }
+
+ /**
+ * Actual stop
+ */
+ private void internalStop()
+ {
+ state = CacheStatus.STOPPING;
+ // if this is called from a source other than the shutdown hook, deregister the shutdown hook.
+ if (!invokedFromShutdownHook && shutdownHook != null) Runtime.getRuntime().removeShutdownHook(shutdownHook);
+
+ // fire all STOP methods according to priority
+ for (PrioritizedMethod em : stopMethods) em.invoke();
+
+ state = CacheStatus.STOPPED;
+ }
+
+ /**
+ * Actual destroy
+ */
+ private void internalDestroy()
+ {
+
+ state = CacheStatus.DESTROYING;
+
+ resetNonVolatile();
+
+ // fire all DESTROY methods according to priority
+ for (PrioritizedMethod em : destroyMethods) em.invoke();
+
+ state = CacheStatus.DESTROYED;
+ }
+
+ // ------------------------------ END: Actual internal lifecycle methods --------------------------------
+
+ /**
+ * Asserts whether invocations are allowed on the cache or not. Returns <tt>true</tt> if invocations are to be allowed,
+ * <tt>false</tt> otherwise. If the origin of the call is remote and the cache status is {@link org.jboss.cache.CacheStatus#STARTING},
+ * this method will block for up to {@link org.jboss.cache.config.Configuration#getStateRetrievalTimeout()} millis, checking
+ * for a valid state.
+ *
+ * @param originLocal true if the call originates locally (i.e., from the {@link org.jboss.cache.invocation.CacheInvocationDelegate} or false if it originates remotely, i.e., from the {@link org.jboss.cache.marshall.CommandAwareRpcDispatcher}.
+ * @return true if invocations are allowed, false otherwise.
+ */
+ public boolean invocationsAllowed(boolean originLocal)
+ {
+ log.trace("Testing if invocations are allowed.");
+ if (state.allowInvocations()) return true;
+
+ // if this is a locally originating call and the cache is not in a valid state, return false.
+ if (originLocal) return false;
+
+ log.trace("Is remotely originating.");
+
+ // else if this is a remote call and the status is STARTING, wait until the cache starts.
+ if (state == CacheStatus.STARTING)
+ {
+ log.trace("Cache is starting; block.");
+ try
+ {
+ blockUntilCacheStarts();
+ return true;
+ }
+ catch (InterruptedException e)
+ {
+ Thread.currentThread().interrupt();
+ }
+ }
+ else
+ {
+ log.warn("Received a remote call but the cache is not in STARTED state - ignoring call.");
+ }
+ return false;
+ }
+
+ /**
+ * Blocks until the current cache instance is in it's {@link org.jboss.cache.CacheStatus#STARTED started} phase. Blocks
+ * for up to {@link org.jboss.cache.config.Configuration#getStateRetrievalTimeout()} milliseconds, throwing an IllegalStateException
+ * if the cache doesn't reach this state even after this maximum wait time.
+ *
+ * @throws InterruptedException if interrupted while waiting
+ * @throws IllegalStateException if even after waiting the cache has not started.
+ */
+ private void blockUntilCacheStarts() throws InterruptedException, IllegalStateException
+ {
+ int pollFrequencyMS = 100;
+ long startupWaitTime = getConfiguration().getStateRetrievalTimeout();
+ long giveUpTime = System.currentTimeMillis() + startupWaitTime;
+
+ while (System.currentTimeMillis() < giveUpTime)
+ {
+ if (state.allowInvocations()) break;
+ Thread.sleep(pollFrequencyMS);
+ }
+
+ // check if we have started.
+ if (!state.allowInvocations())
+ throw new IllegalStateException("Cache not in STARTED state, even after waiting " + getConfiguration().getStateRetrievalTimeout() + " millis.");
+ }
+
+ /**
+ * A wrapper representing a component in the registry
+ */
+ public class Component
+ {
+ /**
+ * A reference to the object instance for this component.
+ */
+ Object instance;
+ /**
+ * The name of the component
+ */
+ String name;
+ /**
+ * List of injection methods used to inject dependencies into the component
+ */
+ List<CachedMethod> injectionMethods = new LinkedList<CachedMethod>();
+ /**
+ * If true, then this component is not flushed before starting the ComponentRegistry.
+ */
+ boolean nonVolatile;
+
+ @Override
+ public String toString()
+ {
+ return "Component{" +
+ "instance=" + instance +
+ ", name=" + name +
+ ", nonVolatile=" + nonVolatile +
+ '}';
+ }
+
+ /**
+ * Injects dependencies into this component.
+ */
+ public void injectDependencies()
+ {
+ for (CachedMethod m : injectionMethods) invokeInjectionMethod(instance, m);
+ }
+ }
+
+
+ /**
+ * Wrapper to encapsulate a method along with a priority
+ */
+ class PrioritizedMethod implements Comparable<PrioritizedMethod>
+ {
+ Method method;
+ Component component;
+ int priority;
+
+ public int compareTo(PrioritizedMethod o)
+ {
+ return (priority < o.priority ? -1 : (priority == o.priority ? 0 : 1));
+ }
+
+ void invoke()
+ {
+ ReflectionUtil.invokeAccessibly(component.instance, method, null);
+ }
+ }
+}
Modified: core/trunk/src/main/java/org/jboss/cache/factories/EmptyConstructorFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/EmptyConstructorFactory.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/factories/EmptyConstructorFactory.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -8,6 +8,7 @@
import org.jboss.cache.invocation.InvocationContextContainer;
import org.jboss.cache.loader.CacheLoaderManager;
import org.jboss.cache.lock.LockManager;
+import org.jboss.cache.lock.LockStrategyFactory;
import org.jboss.cache.marshall.Marshaller;
import org.jboss.cache.marshall.VersionAwareMarshaller;
import org.jboss.cache.notifications.Notifier;
@@ -24,12 +25,13 @@
@DefaultFactoryFor(classes = {StateTransferManager.class, RegionManager.class, Notifier.class,
ChannelMessageListener.class, CacheLoaderManager.class, Marshaller.class,
InvocationContextContainer.class, CacheInvocationDelegate.class,
- TransactionTable.class, DataContainer.class, CommandsFactory.class, LockManager.class})
+ TransactionTable.class, DataContainer.class, CommandsFactory.class, LockManager.class,
+ LockStrategyFactory.class})
public class EmptyConstructorFactory extends ComponentFactory
{
@Override
@SuppressWarnings("unchecked")
- protected <T> T construct(String componentName, Class<T> componentType)
+ protected <T> T construct(Class<T> componentType)
{
try
{
Modified: core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -34,12 +34,13 @@
private CommandInterceptor createInterceptor(Class<? extends CommandInterceptor> clazz) throws IllegalAccessException, InstantiationException
{
- //TODO: 2.2.0: no reason for the individual interceptors to be registered as components, all manipulation should be done through InterceptorChain
- CommandInterceptor chainedInterceptor = componentRegistry.getComponent(clazz.getName(), clazz);
+// CommandInterceptor chainedInterceptor = componentRegistry.getComponent(clazz.getName(), clazz);
+ CommandInterceptor chainedInterceptor = componentRegistry.getComponent(clazz);
if (chainedInterceptor == null)
{
chainedInterceptor = clazz.newInstance();
- componentRegistry.registerComponent(clazz.getName(), chainedInterceptor, clazz);
+// componentRegistry.registerComponent(clazz.getName(), chainedInterceptor, clazz);
+ componentRegistry.registerComponent(chainedInterceptor, clazz);
}
else
{
@@ -57,6 +58,9 @@
CommandInterceptor first = createInterceptor(InvocationContextInterceptor.class);
InterceptorChain interceptorChain = new InterceptorChain(first);
+ // add the interceptor chain to the registry first, since some interceptors may ask for it.
+ componentRegistry.registerComponent(interceptorChain, InterceptorChain.class);
+
// load the cache management interceptor next
if (configuration.getExposeManagementStatistics())
interceptorChain.appendIntereceptor(createInterceptor(CacheMgmtInterceptor.class));
@@ -122,7 +126,7 @@
@Override
@SuppressWarnings("unchecked")
- protected <T> T construct(String componentName, Class<T> componentType)
+ protected <T> T construct(Class<T> componentType)
{
try
{
@@ -134,7 +138,7 @@
}
}
- public static InterceptorChainFactory getInstance(ComponentRegistry componentRegistry, Configuration configuration)
+ public static InterceptorChainFactory getInstance(ComponentKernel componentRegistry, Configuration configuration)
{
InterceptorChainFactory icf = new InterceptorChainFactory();
icf.componentRegistry = componentRegistry;
Modified: core/trunk/src/main/java/org/jboss/cache/factories/ReplicationQueueFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/ReplicationQueueFactory.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/factories/ReplicationQueueFactory.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -14,12 +14,12 @@
public class ReplicationQueueFactory extends EmptyConstructorFactory
{
@Override
- public <T> T construct(String componentName, Class<T> componentType)
+ public <T> T construct(Class<T> componentType)
{
if ((configuration.getCacheMode() == Configuration.CacheMode.REPL_ASYNC || configuration.getCacheMode() == Configuration.CacheMode.INVALIDATION_ASYNC)
&& configuration.isUseReplQueue())
{
- return super.construct(componentName, componentType);
+ return super.construct(componentType);
}
else
{
Modified: core/trunk/src/main/java/org/jboss/cache/factories/RuntimeConfigAwareFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/RuntimeConfigAwareFactory.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/factories/RuntimeConfigAwareFactory.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -20,9 +20,9 @@
{
@Override
@SuppressWarnings("unchecked")
- protected <T> T construct(String componentName, Class<T> componentType)
+ protected <T> T construct(Class<T> componentType)
{
- T component = super.construct(componentName, componentType);
+ T component = super.construct(componentType);
Method setter = BeanUtils.setterMethod(RuntimeConfig.class, componentType);
if (setter != null)
Modified: core/trunk/src/main/java/org/jboss/cache/factories/TransactionManagerFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/TransactionManagerFactory.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/factories/TransactionManagerFactory.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -17,7 +17,7 @@
{
@Override
@SuppressWarnings("unchecked")
- protected <T> T construct(String componentName, Class<T> componentType)
+ protected <T> T construct(Class<T> componentType)
{
// See if we had a TransactionManager injected into our config
TransactionManager transactionManager = configuration.getRuntimeConfig().getTransactionManager();
Deleted: core/trunk/src/main/java/org/jboss/cache/factories/annotations/CacheInjectionMethods.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/annotations/CacheInjectionMethods.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/factories/annotations/CacheInjectionMethods.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -1,23 +0,0 @@
-package org.jboss.cache.factories.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * If this is set on a class, then all methods on that class (and superclasses) annotated with @Inject are cached in the component registry.
- * Useful for components that are frequently constructed using the component registry during the lifespan of the cache.
- *
- * @author Manik Surtani
- * @see org.jboss.cache.factories.annotations.ComponentName
- * @since 2.1.0
- */
-// ensure this annotation is available at runtime.
-(a)Retention(RetentionPolicy.RUNTIME)
-
-// only applies to fields.
-(a)Target(ElementType.TYPE)
-public @interface CacheInjectionMethods
-{
-}
\ No newline at end of file
Deleted: core/trunk/src/main/java/org/jboss/cache/factories/annotations/ComponentName.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/annotations/ComponentName.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/factories/annotations/ComponentName.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -1,52 +0,0 @@
-package org.jboss.cache.factories.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Used with the {@link org.jboss.cache.factories.annotations.Inject} annotation to specify the name of a component to inject.
- * Note that you still need to annotate your method with {@link org.jboss.cache.factories.annotations.Inject} for this
- * annotation to be of any use. You can also combine injections of named and singleton components, see example below.
- * <p/>
- * Usage example:
- * <p/>
- * <pre>
- * public class MyClass
- * {
- * private Map blahMap;
- * private Map anotherMap;
- * private List someList;
- * private TransactionManager tm;
- * <p/>
- * & Inject
- * public void setMyMap(&ComponentName("BlahMap") Map blahMap)
- * {
- * this.blahMap = blahMap;
- * }
- * & Inject
- * public void injectMoreStuff(&ComponentName("AnotherMap") Map anotherMap, &ComponentName("SomeList") List someList, TransactionManager singletonTM)
- * {
- * this.anotherMap = anotherMap;
- * this.someList = someList;
- * this.tm = singletonTM;
- * }
- * }
- * <p/>
- * </pre>
- *
- * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
- * @see org.jboss.cache.factories.annotations.Inject
- * @since 2.1.0
- */
-// ensure this annotation is available at runtime.
-(a)Retention(RetentionPolicy.RUNTIME)
-
-// only applies to fields.
-(a)Target(ElementType.PARAMETER)
-
-public @interface ComponentName
-{
- String value();
-}
Modified: core/trunk/src/main/java/org/jboss/cache/factories/annotations/DefaultFactoryFor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/annotations/DefaultFactoryFor.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/factories/annotations/DefaultFactoryFor.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -18,6 +18,8 @@
{
/**
* Components that may be constructed by a factory annotated with this annotation.
+ *
+ * @return classes that can be constructed by this factory
*/
Class[] classes();
}
Modified: core/trunk/src/main/java/org/jboss/cache/factories/annotations/Destroy.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/annotations/Destroy.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/factories/annotations/Destroy.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -17,4 +17,12 @@
@Retention(RetentionPolicy.RUNTIME)
public @interface Destroy
{
+ /**
+ * Optional parameter which defines the order in which this method will be called when the ComponentRegistry moves
+ * to the STARTED state. Defaults to 10.
+ *
+ * @return execution priority
+ * @since 2.2.0
+ */
+ int priority() default 10;
}
\ No newline at end of file
Added: core/trunk/src/main/java/org/jboss/cache/factories/annotations/NonVolatile.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/annotations/NonVolatile.java (rev 0)
+++ core/trunk/src/main/java/org/jboss/cache/factories/annotations/NonVolatile.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -0,0 +1,23 @@
+package org.jboss.cache.factories.annotations;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * This annotation is used for components that will be registered in the {@link org.jboss.cache.factories.ComponentKernel},
+ * that are resilient to changes in configuration. Examples are the {@link org.jboss.cache.CacheSPI} implementation used, which does
+ * not change regardless of the configuration.
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @since 2.2.0
+ */
+// ensure this annotation is available at runtime.
+(a)Retention(RetentionPolicy.RUNTIME)
+
+// only applies to classes.
+(a)Target(ElementType.TYPE)
+public @interface NonVolatile
+{
+}
Modified: core/trunk/src/main/java/org/jboss/cache/factories/annotations/Start.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/annotations/Start.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/factories/annotations/Start.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -17,4 +17,12 @@
@Retention(RetentionPolicy.RUNTIME)
public @interface Start
{
+ /**
+ * Optional parameter which defines the order in which this method will be called when the ComponentRegistry moves
+ * to the STARTED state. Defaults to 10.
+ *
+ * @return execution priority
+ * @since 2.2.0
+ */
+ int priority() default 10;
}
Modified: core/trunk/src/main/java/org/jboss/cache/factories/annotations/Stop.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/annotations/Stop.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/factories/annotations/Stop.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -17,4 +17,12 @@
@Retention(RetentionPolicy.RUNTIME)
public @interface Stop
{
+ /**
+ * Optional parameter which defines the order in which this method will be called when the ComponentRegistry moves
+ * to the STARTED state. Defaults to 10.
+ *
+ * @return execution priority
+ * @since 2.2.0
+ */
+ int priority() default 10;
}
\ No newline at end of file
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/InterceptorChain.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/InterceptorChain.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/InterceptorChain.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -6,6 +6,7 @@
import org.jboss.cache.InvocationContext;
import org.jboss.cache.commands.VisitableCommand;
import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.factories.annotations.Start;
import org.jboss.cache.interceptors.base.CommandInterceptor;
import org.jboss.cache.invocation.InvocationContextContainer;
import org.jboss.cache.util.CachePrinter;
@@ -32,9 +33,8 @@
* used for invoking commands on the chain
*/
private InvocationContextContainer invocationContextContainer;
+ private static final Log log = LogFactory.getLog(InterceptorChain.class);
- private Log log = LogFactory.getLog(InterceptorChain.class);
-
/**
* Constructs an interceptor chain having the supplied interceptor as first.
*/
@@ -49,6 +49,12 @@
this.invocationContextContainer = invocationContextContainer;
}
+ @Start
+ private void printChainInfo()
+ {
+ if (log.isDebugEnabled()) log.debug("Interceptor chain is: " + toString());
+ }
+
/**
* Inserts the given interceptor at the specified position in the chain (o based indexing).
*
@@ -256,7 +262,7 @@
}
/**
- * Similar to {@link #invoke(org.jboss.cache.InvocationContext, org.jboss.cache.commands.ReplicableCommand)}, but
+ * Similar to {@link #invoke(org.jboss.cache.InvocationContext, org.jboss.cache.commands.VisitableCommand)}, but
* constructs a invocation context on the fly, using {@link InvocationContextContainer#get()}
*/
public Object invokeRemote(VisitableCommand cacheCommand) throws Throwable
@@ -267,7 +273,7 @@
}
/**
- * Similar to {@link #invoke(org.jboss.cache.InvocationContext, org.jboss.cache.commands.ReplicableCommand)}, but
+ * Similar to {@link #invoke(org.jboss.cache.InvocationContext, org.jboss.cache.commands.VisitableCommand)}, but
* constructs a invocation context on the fly, using {@link InvocationContextContainer#get()} and setting the origin local flag to it's default value.
*/
public Object invoke(VisitableCommand cacheCommand) throws Throwable
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -8,7 +8,6 @@
import org.jboss.cache.CacheException;
import org.jboss.cache.InvocationContext;
-import org.jboss.cache.LifecycleManager;
import org.jboss.cache.RPCManager;
import org.jboss.cache.ReplicationException;
import org.jboss.cache.commands.AbstractVisitor;
@@ -30,6 +29,7 @@
import org.jboss.cache.config.Configuration;
import org.jboss.cache.config.Option;
import org.jboss.cache.factories.CommandsFactory;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.invocation.InvocationContextContainer;
import org.jboss.cache.notifications.Notifier;
@@ -67,7 +67,7 @@
private RPCManager rpcManager;
private Notifier notifier;
private InvocationContextContainer invocationContextContainer;
- private LifecycleManager lifecycleManager;
+ private ComponentKernel componentRegistry;
private final ModificationsReplayVisitor replayVisitorNoInject = new ModificationsReplayVisitor(false);
private final ModificationsReplayVisitor replayVisitorWithInject = new ModificationsReplayVisitor(true);
@@ -84,13 +84,13 @@
@Inject
public void intialize(RPCManager rpcManager,
Notifier notifier, InvocationContextContainer icc,
- LifecycleManager lifecycleManager, CommandsFactory factory)
+ CommandsFactory factory, ComponentKernel componentRegistry)
{
this.commandsFactory = factory;
this.rpcManager = rpcManager;
this.notifier = notifier;
this.invocationContextContainer = icc;
- this.lifecycleManager = lifecycleManager;
+ this.componentRegistry = componentRegistry;
}
@Override
@@ -1248,7 +1248,7 @@
private void assertCanContinue()
{
- if (!lifecycleManager.getCacheStatus().allowInvocations() && (ctx.getOptionOverrides() == null || !ctx.getOptionOverrides().isSkipCacheStatusCheck()))
+ if (!componentRegistry.invocationsAllowed(true) && (ctx.getOptionOverrides() == null || !ctx.getOptionOverrides().isSkipCacheStatusCheck()))
throw new IllegalStateException("Cache not in STARTED state!");
}
Modified: core/trunk/src/main/java/org/jboss/cache/invocation/AbstractInvocationDelegate.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/invocation/AbstractInvocationDelegate.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/invocation/AbstractInvocationDelegate.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -2,8 +2,8 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.jboss.cache.LifecycleManager;
import org.jboss.cache.config.Configuration;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.interceptors.InterceptorChain;
@@ -26,7 +26,7 @@
protected Configuration configuration;
protected InvocationContextContainer invocationContextContainer;
- protected LifecycleManager lifecycleManager;
+ protected ComponentKernel componentRegistry;
protected InterceptorChain invoker;
protected boolean originLocal = true;
@@ -36,12 +36,12 @@
*/
@Inject
public void initialize(Configuration configuration, InvocationContextContainer invocationContextContainer,
- LifecycleManager lifecycleManager, InterceptorChain interceptorChain)
+ ComponentKernel componentRegistry, InterceptorChain interceptorChain)
{
this.configuration = configuration;
this.invocationContextContainer = invocationContextContainer;
this.invoker = interceptorChain;
- this.lifecycleManager = lifecycleManager;
+ this.componentRegistry = componentRegistry;
}
Modified: core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -19,6 +19,7 @@
import org.jboss.cache.config.Option;
import org.jboss.cache.factories.CommandsFactory;
import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.factories.annotations.NonVolatile;
import org.jboss.cache.interceptors.base.CommandInterceptor;
import org.jboss.cache.loader.CacheLoaderManager;
import org.jboss.cache.marshall.Marshaller;
@@ -44,6 +45,7 @@
* @since 2.1.0
*/
@SuppressWarnings("unchecked")
+@NonVolatile
public class CacheInvocationDelegate<K, V> extends AbstractInvocationDelegate implements CacheSPI<K, V>
{
// this stuff is needed since the SPI has methods to retrieve these.
@@ -257,28 +259,28 @@
public void create() throws CacheException
{
- lifecycleManager.create();
+ componentRegistry.create();
}
public void start() throws CacheException
{
- lifecycleManager.start();
+ componentRegistry.start();
}
public void stop()
{
- lifecycleManager.stop();
+ componentRegistry.stop();
}
public void destroy()
{
reset();
- lifecycleManager.destroy();
+ componentRegistry.destroy();
}
public CacheStatus getCacheStatus()
{
- return lifecycleManager == null ? null : lifecycleManager.getCacheStatus();
+ return componentRegistry.getState();
}
public InvocationContext getInvocationContext()
@@ -582,7 +584,7 @@
assertIsConstructed();
if (!ctx.getOptionOverrides().isSkipCacheStatusCheck())
{
- if (!lifecycleManager.invocationsAllowed(true))
+ if (!componentRegistry.invocationsAllowed(true))
{
throw new IllegalStateException("Cache not in STARTED state!");
}
Modified: core/trunk/src/main/java/org/jboss/cache/invocation/InvocationContextContainer.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/invocation/InvocationContextContainer.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/invocation/InvocationContextContainer.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -1,6 +1,7 @@
package org.jboss.cache.invocation;
import org.jboss.cache.InvocationContext;
+import org.jboss.cache.factories.annotations.NonVolatile;
/**
* Container and factory for thread locals
@@ -8,6 +9,7 @@
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
* @since 2.1.0
*/
+@NonVolatile
public class InvocationContextContainer extends ThreadLocal<InvocationContext>
{
@Override
Modified: core/trunk/src/main/java/org/jboss/cache/loader/CacheLoaderManager.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/loader/CacheLoaderManager.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/loader/CacheLoaderManager.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -16,7 +16,7 @@
import org.jboss.cache.config.CacheLoaderConfig.IndividualCacheLoaderConfig;
import org.jboss.cache.config.CacheLoaderConfig.IndividualCacheLoaderConfig.SingletonStoreConfig;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.factories.annotations.Start;
import org.jboss.cache.factories.annotations.Stop;
@@ -72,10 +72,10 @@
private boolean fetchPersistentState;
private Configuration configuration;
private RegionManager regionManager;
- private ComponentRegistry registry;
+ private ComponentKernel registry;
@Inject
- public void injectDependencies(CacheSPI cache, Configuration configuration, RegionManager regionManager, ComponentRegistry registry)
+ public void injectDependencies(CacheSPI cache, Configuration configuration, RegionManager regionManager, ComponentKernel registry)
{
this.regionManager = regionManager;
this.config = configuration.getCacheLoaderConfig();
Modified: core/trunk/src/main/java/org/jboss/cache/loader/ChainingCacheLoader.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/loader/ChainingCacheLoader.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/loader/ChainingCacheLoader.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -11,7 +11,7 @@
import org.jboss.cache.RegionManager;
import org.jboss.cache.config.CacheLoaderConfig;
import org.jboss.cache.config.CacheLoaderConfig.IndividualCacheLoaderConfig;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.factories.annotations.Inject;
import java.io.ObjectInputStream;
@@ -37,7 +37,7 @@
private final List<CacheLoader> cacheLoaders = new ArrayList<CacheLoader>(2);
private final List<CacheLoader> writeCacheLoaders = new ArrayList<CacheLoader>(2);
private final List<CacheLoaderConfig.IndividualCacheLoaderConfig> cacheLoaderConfigs = new ArrayList<CacheLoaderConfig.IndividualCacheLoaderConfig>(2);
- private ComponentRegistry registry;
+ private ComponentKernel registry;
/**
* Sets the configuration. Will be called before {@link #create()} and {@link #start()}
@@ -55,7 +55,7 @@
}
@Inject
- public void injectDependencies(ComponentRegistry registry)
+ public void injectDependencies(ComponentKernel registry)
{
this.registry = registry;
}
Modified: core/trunk/src/main/java/org/jboss/cache/lock/IdentityLock.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/lock/IdentityLock.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/lock/IdentityLock.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -72,35 +72,22 @@
private static final Log log = LogFactory.getLog(IdentityLock.class);
private static final boolean trace = log.isTraceEnabled();
- private final LockStrategy lock_;
- private final LockMap map_;
- private final boolean mustReacquireRead_;
+ private final LockStrategy lock;
+ private final LockMap map;
+ private final boolean mustReacquireRead;
private NodeSPI<?, ?> node;
/**
- * Creates a new Identity lock based on the lock level set in the {@link LockStrategyFactory}
- */
- public IdentityLock(NodeSPI node)
- {
- this(LockStrategyFactory.getLockStrategy(), node);
- log.trace("Using default lock level");
- }
-
- /**
- * Creates a new IdentityLock based on the lock level in force.
+ * Creates a new IdentityLock using the LockFactory passed in.
*
- * @param level
+ * @param factory to create lock strategies
+ * @param node to lock
*/
- public IdentityLock(IsolationLevel level, NodeSPI node)
+ public IdentityLock(LockStrategyFactory factory, NodeSPI node)
{
- this(LockStrategyFactory.getLockStrategy(level), node);
- }
-
- private IdentityLock(LockStrategy strategy, NodeSPI node)
- {
- lock_ = strategy;
- mustReacquireRead_ = strategy instanceof LockStrategyReadCommitted;
- map_ = new LockMap();
+ lock = factory.getLockStrategy();
+ mustReacquireRead = lock instanceof LockStrategyReadCommitted;
+ map = new LockMap();
this.node = node;
}
@@ -132,7 +119,7 @@
*/
public Collection<Object> getReaderOwners()
{
- return map_.readerOwners();
+ return map.readerOwners();
}
/**
@@ -142,12 +129,12 @@
*/
public Object getWriterOwner()
{
- return map_.writerOwner();
+ return map.writerOwner();
}
public LockMap getLockMap()
{
- return map_;
+ return map;
}
/**
@@ -185,7 +172,7 @@
throw new IllegalArgumentException("acquireWriteLock(): null caller");
}
- if (map_.isOwner(caller, LockMap.OWNER_WRITE))
+ if (map.isOwner(caller, LockMap.OWNER_WRITE))
{
if (trace)
{
@@ -195,7 +182,7 @@
}
// Check first if we need to upgrade
- if (map_.isOwner(caller, LockMap.OWNER_READ))
+ if (map.isOwner(caller, LockMap.OWNER_READ))
{
// Currently is a reader owner. Obtain the writer ownership then.
Lock wLock;
@@ -203,9 +190,9 @@
{
if (trace)
{
- log.trace("upgrading RL to WL for " + caller + ", timeout=" + timeout + ", locks: " + map_.printInfo());
+ log.trace("upgrading RL to WL for " + caller + ", timeout=" + timeout + ", locks: " + map.printInfo());
}
- wLock = lock_.upgradeLockAttempt(timeout);
+ wLock = lock.upgradeLockAttempt(timeout);
}
catch (UpgradeException ue)
{
@@ -216,9 +203,9 @@
if (wLock == null)
{
release(caller);// bug fix: remember to release the read lock before throwing the exception
- map_.removeReader(caller);
+ map.removeReader(caller);
String errStr = "upgrade lock for " + getFqn() + " could not be acquired after " + timeout + " ms." +
- " Lock map ownership " + map_.printInfo() + " (caller=" + caller + ", lock info: " + toString(true) + ')';
+ " Lock map ownership " + map.printInfo() + " (caller=" + caller + ", lock info: " + toString(true) + ')';
log.trace(errStr);
throw new UpgradeException(errStr);
}
@@ -228,7 +215,7 @@
{
log.trace("upgrading lock for " + getFqn());
}
- map_.upgrade(caller);
+ map.upgrade(caller);
}
catch (OwnerNotExistedException ex)
{
@@ -238,17 +225,17 @@
else
{
// Not a current reader owner. Obtain the writer ownership then.
- boolean rc = lock_.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS);
+ boolean rc = lock.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS);
// we don't need to synchronize from here on because we own the semaphore
if (!rc)
{
String errStr = "write lock for " + getFqn() + " could not be acquired after " + timeout + " ms. " +
- "Locks: " + map_.printInfo() + " (caller=" + caller + ", lock info: " + toString(true) + ')';
+ "Locks: " + map.printInfo() + " (caller=" + caller + ", lock info: " + toString(true) + ')';
log.trace(errStr);
throw new TimeoutException(errStr);
}
- map_.setWriterIfNotNull(caller);
+ map.setWriterIfNotNull(caller);
}
return true;
}
@@ -290,15 +277,15 @@
boolean hasRead = false;
boolean hasRequired = false;
- if (mustReacquireRead_)
+ if (mustReacquireRead)
{
- hasRequired = map_.isOwner(caller, LockMap.OWNER_WRITE);
+ hasRequired = map.isOwner(caller, LockMap.OWNER_WRITE);
if (!hasRequired)
{
- hasRead = map_.isOwner(caller, LockMap.OWNER_READ);
+ hasRead = map.isOwner(caller, LockMap.OWNER_READ);
}
}
- else if (map_.isOwner(caller, LockMap.OWNER_ANY))
+ else if (map.isOwner(caller, LockMap.OWNER_ANY))
{
hasRequired = true;
}
@@ -314,14 +301,14 @@
return false;// owner already has the lock
}
- rc = lock_.readLock().tryLock(timeout, TimeUnit.MILLISECONDS);
+ rc = lock.readLock().tryLock(timeout, TimeUnit.MILLISECONDS);
// we don't need to synchronize from here on because we own the semaphore
if (!rc)
{
StringBuffer sb = new StringBuffer();
sb.append("read lock for ").append(getFqn()).append(" could not be acquired by ").append(caller);
- sb.append(" after ").append(timeout).append(" ms. " + "Locks: ").append(map_.printInfo());
+ sb.append(" after ").append(timeout).append(" ms. " + "Locks: ").append(map.printInfo());
sb.append(", lock info: ").append(toString(true));
String errMsg = sb.toString();
log.trace(errMsg);
@@ -331,7 +318,7 @@
// Only add to the map if we didn't already have the lock
if (!hasRead)
{
- map_.addReader(caller);// this is synchronized internally, we don't need to synchronize here
+ map.addReader(caller);// this is synchronized internally, we don't need to synchronize here
}
return true;
}
@@ -349,15 +336,15 @@
}
// Check whether to release reader or writer lock.
- if (map_.isOwner(caller, LockMap.OWNER_READ))
+ if (map.isOwner(caller, LockMap.OWNER_READ))
{
- map_.removeReader(caller);
- lock_.readLock().unlock();
+ map.removeReader(caller);
+ lock.readLock().unlock();
}
- else if (map_.isOwner(caller, LockMap.OWNER_WRITE))
+ else if (map.isOwner(caller, LockMap.OWNER_WRITE))
{
- map_.removeWriter();
- lock_.writeLock().unlock();
+ map.removeWriter();
+ lock.writeLock().unlock();
}
}
@@ -368,17 +355,17 @@
{
try
{
- if ((map_.writerOwner()) != null)
+ if ((map.writerOwner()) != null)
{
// lock_.readLock().release();
- lock_.writeLock().unlock();
+ lock.writeLock().unlock();
}
- map_.releaseReaderOwners(lock_);
+ map.releaseReaderOwners(lock);
}
finally
{
- map_.removeAll();
+ map.removeAll();
}
}
@@ -395,7 +382,7 @@
*/
public boolean isReadLocked()
{
- return map_.isReadLocked();
+ return map.isReadLocked();
}
/**
@@ -403,7 +390,7 @@
*/
public boolean isWriteLocked()
{
- return map_.writerOwner() != null;
+ return map.writerOwner() != null;
}
/**
@@ -421,7 +408,7 @@
*/
public boolean isOwner(Object o)
{
- return map_.isOwner(o, LockMap.OWNER_ANY);
+ return map.isOwner(o, LockMap.OWNER_ANY);
}
@Override
@@ -445,7 +432,7 @@
public void toString(StringBuffer sb, boolean print_lock_details)
{
boolean printed_read_owners = false;
- Collection<Object> read_owners = lock_ != null ? getReaderOwners() : null;
+ Collection<Object> read_owners = lock != null ? getReaderOwners() : null;
if (read_owners != null && read_owners.size() > 0)
{
// Fix for JBCACHE-310 -- can't just call new ArrayList(read_owners) :(
@@ -463,7 +450,7 @@
printed_read_owners = true;
}
- Object write_owner = lock_ != null ? getWriterOwner() : null;
+ Object write_owner = lock != null ? getWriterOwner() : null;
if (write_owner != null)
{
if (printed_read_owners)
@@ -478,7 +465,7 @@
}
if (print_lock_details)
{
- sb.append(" (").append(lock_.toString()).append(')');
+ sb.append(" (").append(lock.toString()).append(')');
}
}
Modified: core/trunk/src/main/java/org/jboss/cache/lock/LockManager.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/lock/LockManager.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/lock/LockManager.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -10,6 +10,7 @@
import org.jboss.cache.config.Configuration;
import org.jboss.cache.factories.CommandsFactory;
import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.factories.annotations.Start;
import org.jboss.cache.transaction.GlobalTransaction;
import org.jboss.cache.transaction.TransactionEntry;
import org.jboss.cache.transaction.TransactionTable;
@@ -40,14 +41,19 @@
CommandsFactory commandsFactory)
{
this.configuration = configuration;
- lockAcquisitionTimeout = configuration.getLockAcquisitionTimeout();
this.dataContainer = dataContainer;
- rootNode = dataContainer.getRoot();
this.txTable = txTable;
this.commandsFactory = commandsFactory;
}
+ @Start
+ public void setRootNode()
+ {
+ this.lockAcquisitionTimeout = configuration.getLockAcquisitionTimeout();
+ rootNode = dataContainer.getRoot();
+ }
+
public boolean acquireLocksWithTimeout(InvocationContext ctx, Fqn fqn, NodeLock.LockType lockType,
boolean createIfNotExists, boolean zeroLockTimeout,
boolean acquireLockOnParent, boolean reverseRemoveCheck, List<NodeSPI> createdNodes, boolean skipNotification)
Modified: core/trunk/src/main/java/org/jboss/cache/lock/LockStrategyFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/lock/LockStrategyFactory.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/lock/LockStrategyFactory.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -6,7 +6,11 @@
*/
package org.jboss.cache.lock;
+import org.jboss.cache.config.Configuration;
+import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.factories.annotations.Start;
+
/**
* Factory to create LockStragtegy instance.
*
@@ -18,22 +22,28 @@
/**
* Transaction locking isolation level. Default.
*/
- private static IsolationLevel lockingLevel_ = IsolationLevel.REPEATABLE_READ;
+ private IsolationLevel lockingLevel = IsolationLevel.REPEATABLE_READ;
+ private Configuration configuration;
- /**
- *
- */
- protected LockStrategyFactory()
+ @Inject
+ public void injectDependencies(Configuration configuration)
{
+ this.configuration = configuration;
}
- public static LockStrategy getLockStrategy()
+ @Start(priority = 1)
+ public void start()
{
- return getLockStrategy(lockingLevel_);
+ lockingLevel = configuration.isNodeLockingOptimistic() ? IsolationLevel.REPEATABLE_READ : configuration.getIsolationLevel();
}
- public static LockStrategy getLockStrategy(IsolationLevel lockingLevel)
+ public LockStrategy getLockStrategy()
{
+ return getLockStrategy(lockingLevel);
+ }
+
+ public LockStrategy getLockStrategy(IsolationLevel lockingLevel)
+ {
//if(log_.isTraceEnabled()) {
// log_.trace("LockStrategy is: " + lockingLevel);
//}
@@ -55,9 +65,8 @@
}
}
- public static void setIsolationLevel(IsolationLevel level)
+ public void setIsolationLevel(IsolationLevel level)
{
- lockingLevel_ = level;
+ lockingLevel = level;
}
-
}
Modified: core/trunk/src/main/java/org/jboss/cache/marshall/AbstractMarshaller.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/marshall/AbstractMarshaller.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/marshall/AbstractMarshaller.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -35,7 +35,6 @@
import org.jboss.cache.commands.write.EvictCommand;
import org.jboss.cache.commands.write.InvalidateCommand;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.annotations.ComponentName;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.factories.annotations.Start;
import org.jboss.cache.transaction.GlobalTransaction;
@@ -68,7 +67,7 @@
protected boolean useRefs = false;
@Inject
- void injectDependencies(RegionManager regionManager, Configuration configuration, @ComponentName("deployerClassLoader")ClassLoader defaultClassLoader)
+ void injectDependencies(RegionManager regionManager, Configuration configuration, ClassLoader defaultClassLoader)
{
this.defaultClassLoader = defaultClassLoader;
this.regionManager = regionManager;
@@ -88,7 +87,7 @@
trace = log.isTraceEnabled();
}
- // implement the basic contract set in RPcDispatcher.AbstractMarshaller
+ // implement the basic contract set in RPCDispatcher.AbstractMarshaller
public byte[] objectToByteBuffer(Object obj) throws Exception
{
throw new RuntimeException("Needs to be overridden!");
Modified: core/trunk/src/main/java/org/jboss/cache/marshall/CommandAwareRpcDispatcher.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/marshall/CommandAwareRpcDispatcher.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/marshall/CommandAwareRpcDispatcher.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -1,12 +1,12 @@
package org.jboss.cache.marshall;
import org.jboss.cache.InvocationContext;
-import org.jboss.cache.LifecycleManager;
import org.jboss.cache.commands.ReplicableCommand;
import org.jboss.cache.commands.VisitableCommand;
import org.jboss.cache.commands.remote.AnnounceBuddyPoolNameCommand;
import org.jboss.cache.commands.remote.AssignToBuddyGroupCommand;
import org.jboss.cache.commands.remote.RemoveFromBuddyGroupCommand;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.interceptors.InterceptorChain;
import org.jboss.cache.invocation.InvocationContextContainer;
import org.jgroups.Address;
@@ -32,16 +32,16 @@
{
protected InvocationContextContainer invocationContextContainer;
protected InterceptorChain interceptorChain;
- protected LifecycleManager lifecycleManager;
+ protected ComponentKernel componentRegistry;
protected boolean trace;
public CommandAwareRpcDispatcher(Channel channel, MessageListener l, MembershipListener l2, Object server_obj,
InvocationContextContainer container, InterceptorChain interceptorChain,
- LifecycleManager lifecycleManager)
+ ComponentKernel componentRegistry)
{
super(channel, l, l2, server_obj);
this.invocationContextContainer = container;
- this.lifecycleManager = lifecycleManager;
+ this.componentRegistry = componentRegistry;
this.interceptorChain = interceptorChain;
trace = log.isTraceEnabled();
}
@@ -134,7 +134,7 @@
}
catch (Throwable x)
{
- if (trace) log.trace("Problems invoking command", x);
+ if (trace) log.trace("Problems invoking command.", x);
return x;
}
}
@@ -152,7 +152,7 @@
{
InvocationContext ctx = invocationContextContainer.get();
ctx.setOriginLocal(false);
- if (!lifecycleManager.invocationsAllowed(false))
+ if (!componentRegistry.invocationsAllowed(false))
{
return null;
}
@@ -166,7 +166,7 @@
if (!(cmd instanceof AnnounceBuddyPoolNameCommand ||
cmd instanceof AssignToBuddyGroupCommand ||
cmd instanceof RemoveFromBuddyGroupCommand)
- && !lifecycleManager.invocationsAllowed(false))
+ && !componentRegistry.invocationsAllowed(false))
{
return null;
}
Modified: core/trunk/src/main/java/org/jboss/cache/marshall/InactiveRegionAwareRpcDispatcher.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/marshall/InactiveRegionAwareRpcDispatcher.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/marshall/InactiveRegionAwareRpcDispatcher.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -1,7 +1,7 @@
package org.jboss.cache.marshall;
-import org.jboss.cache.LifecycleManager;
import org.jboss.cache.commands.ReplicableCommand;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.interceptors.InterceptorChain;
import org.jboss.cache.invocation.InvocationContextContainer;
import org.jgroups.Channel;
@@ -25,9 +25,9 @@
*/
public InactiveRegionAwareRpcDispatcher(Channel channel, MessageListener l, MembershipListener l2, Object serverObj,
InvocationContextContainer container, InterceptorChain interceptorChain,
- LifecycleManager lifecycleManager)
+ ComponentKernel componentRegistry)
{
- super(channel, l, l2, serverObj, container, interceptorChain, lifecycleManager);
+ super(channel, l, l2, serverObj, container, interceptorChain, componentRegistry);
}
@Override
Modified: core/trunk/src/main/java/org/jboss/cache/marshall/VersionAwareMarshaller.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/marshall/VersionAwareMarshaller.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/marshall/VersionAwareMarshaller.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -9,7 +9,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.Fqn;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.factories.annotations.Start;
import org.jboss.cache.util.Util;
@@ -41,14 +41,14 @@
private static final int VERSION_220 = 22;
private static final int CUSTOM_MARSHALLER = 999;
- private ComponentRegistry componentRegistry;
+ private ComponentKernel componentRegistry;
Marshaller defaultMarshaller;
final Map<Integer, Marshaller> marshallers = new HashMap<Integer, Marshaller>();
private int versionInt;
@Inject
- void injectComponents(ComponentRegistry componentRegistry)
+ void injectComponents(ComponentKernel componentRegistry)
{
this.componentRegistry = componentRegistry;
}
Modified: core/trunk/src/main/java/org/jboss/cache/notifications/Notifier.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/notifications/Notifier.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/notifications/Notifier.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -17,7 +17,9 @@
import org.jboss.cache.config.Configuration;
import org.jboss.cache.factories.annotations.Destroy;
import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.factories.annotations.NonVolatile;
import org.jboss.cache.factories.annotations.Start;
+import org.jboss.cache.factories.annotations.Stop;
import org.jboss.cache.marshall.MarshalledValueMap;
import org.jboss.cache.notifications.annotation.*;
import org.jboss.cache.notifications.event.*;
@@ -42,6 +44,7 @@
*
* @author <a href="mailto:manik@jboss.org">Manik Surtani (manik(a)jboss.org)</a>
*/
+@NonVolatile
public class Notifier
{
private static final Log log = LogFactory.getLog(Notifier.class);
@@ -199,6 +202,7 @@
/**
* Removes all listeners from the notifier, including the evictionPolicyListener.
*/
+ @Stop(priority = 99)
public void removeAllCacheListeners()
{
synchronized (listenerInvocations)
@@ -490,6 +494,7 @@
/**
* Notifies all registered listeners of a cacheStarted event.
*/
+ @Start(priority = 99)
public void notifyCacheStarted()
{
List<ListenerInvocation> listeners = listenerInvocations.get(CacheStarted.class);
@@ -506,6 +511,7 @@
/**
* Notifies all registered listeners of a cacheStopped event.
*/
+ @Stop(priority = 98)
public void notifyCacheStopped()
{
List<ListenerInvocation> listeners = listenerInvocations.get(CacheStopped.class);
Modified: core/trunk/src/main/java/org/jboss/cache/remoting/jgroups/ChannelMessageListener.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/remoting/jgroups/ChannelMessageListener.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/remoting/jgroups/ChannelMessageListener.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -6,6 +6,7 @@
import org.jboss.cache.Fqn;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.factories.annotations.NonVolatile;
import org.jboss.cache.statetransfer.StateTransferManager;
import org.jboss.cache.util.ExposedByteArrayOutputStream;
import org.jboss.util.stream.MarshalledValueInputStream;
@@ -24,6 +25,7 @@
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
* @since 2.1.0
*/
+@NonVolatile
public class ChannelMessageListener implements ExtendedMessageListener
{
/**
Modified: core/trunk/src/main/java/org/jboss/cache/statetransfer/StateTransferManager.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/statetransfer/StateTransferManager.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/statetransfer/StateTransferManager.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -12,17 +12,21 @@
import org.jboss.cache.CacheSPI;
import org.jboss.cache.Fqn;
import org.jboss.cache.NodeSPI;
+import org.jboss.cache.RegionManager;
+import org.jboss.cache.config.Configuration;
import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.factories.annotations.NonVolatile;
import org.jboss.cache.loader.CacheLoaderManager;
import org.jboss.cache.lock.NodeLock;
import org.jboss.cache.lock.TimeoutException;
+import org.jboss.cache.marshall.Marshaller;
import org.jboss.cache.marshall.NodeData;
import org.jboss.cache.marshall.NodeDataMarker;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
-
+@NonVolatile
public class StateTransferManager
{
protected final static Log log = LogFactory.getLog(StateTransferManager.class);
@@ -32,15 +36,21 @@
public static final String PARTIAL_STATE_DELIMITER = "_PARTIAL_STATE_DELIMITER";
private CacheSPI cache;
+ private Marshaller marshaller;
+ private RegionManager regionManager;
+ private Configuration configuration;
public StateTransferManager()
{
}
@Inject
- private void injectDependencies(CacheSPI cache)
+ public void injectDependencies(CacheSPI cache, Marshaller marshaller, RegionManager regionManager, Configuration configuration)
{
this.cache = cache;
+ this.regionManager = regionManager;
+ this.marshaller = marshaller;
+ this.configuration = configuration;
}
public StateTransferManager(CacheSPI cache)
@@ -70,15 +80,15 @@
public void getState(ObjectOutputStream out, Fqn fqn, long timeout, boolean force, boolean suppressErrors) throws Throwable
{
// can't give state for regions currently being activated/inactivated
- boolean canProvideState = (!cache.getRegionManager().isInactive(fqn) && cache.peek(fqn, false, false) != null);
+ boolean canProvideState = (!regionManager.isInactive(fqn) && cache.peek(fqn, false, false) != null);
- boolean fetchTransientState = cache.getConfiguration().isFetchInMemoryState();
+ boolean fetchTransientState = configuration.isFetchInMemoryState();
CacheLoaderManager cacheLoaderManager = cache.getCacheLoaderManager();
boolean fetchPersistentState = cacheLoaderManager != null && cacheLoaderManager.isFetchPersistentState();
if (canProvideState && (fetchPersistentState || fetchTransientState))
{
- cache.getMarshaller().objectToObjectStream(true, out);
+ marshaller.objectToObjectStream(true, out);
StateTransferGenerator generator = getStateTransferGenerator();
Object owner = getOwnerForLock();
long startTime = System.currentTimeMillis();
@@ -104,13 +114,13 @@
}
else
{
- cache.getMarshaller().objectToObjectStream(false, out);
+ marshaller.objectToObjectStream(false, out);
Exception e = null;
if (!canProvideState)
{
String exceptionMessage = "Cache instance at " + cache.getLocalAddress() + " cannot provide state for fqn " + fqn + ".";
- if (cache.getRegionManager().isInactive(fqn))
+ if (regionManager.isInactive(fqn))
{
exceptionMessage += " Region for fqn " + fqn + " is inactive.";
}
@@ -124,7 +134,7 @@
{
e = new CacheException("Cache instance at " + cache.getLocalAddress() + " is not configured to provide state");
}
- cache.getMarshaller().objectToObjectStream(e, out);
+ marshaller.objectToObjectStream(e, out);
throw e;
}
}
@@ -158,7 +168,7 @@
cache.put(targetRoot, null);
target = cache.peek(targetRoot, false, false);
}
- Object o = cache.getMarshaller().objectFromObjectStream(in);
+ Object o = marshaller.objectFromObjectStream(in);
Boolean hasState = (Boolean) o;
if (hasState)
{
@@ -167,7 +177,7 @@
else
{
throw new CacheException("Cache instance at " + cache.getLocalAddress()
- + " cannot integrate state since state provider could not provide state due to " + cache.getMarshaller().objectFromObjectStream(in));
+ + " cannot integrate state since state provider could not provide state due to " + marshaller.objectFromObjectStream(in));
}
}
@@ -188,7 +198,7 @@
private void setState(ObjectInputStream state, NodeSPI targetRoot) throws Exception
{
Object owner = getOwnerForLock();
- long timeout = cache.getConfiguration().getStateRetrievalTimeout();
+ long timeout = configuration.getStateRetrievalTimeout();
long startTime = System.currentTimeMillis();
try
Modified: core/trunk/src/main/java/org/jboss/cache/transaction/TransactionTable.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/transaction/TransactionTable.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/transaction/TransactionTable.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -14,6 +14,8 @@
import org.jboss.cache.commands.ReversibleCommand;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.factories.annotations.NonVolatile;
+import org.jboss.cache.factories.annotations.Start;
import org.jboss.cache.lock.NodeLock;
import org.jgroups.Address;
@@ -32,6 +34,7 @@
* @author <a href="mailto:bela@jboss.org">Bela Ban</a> Apr 14, 2003
* @version $Revision$
*/
+@NonVolatile
public class TransactionTable
{
private static final Log log = LogFactory.getLog(TransactionTable.class);
@@ -54,12 +57,19 @@
private RPCManager rpcManager;
private boolean isOptimisticLocking;
+ private Configuration configuration;
@Inject
public void initialize(TransactionManager transactionManager, RPCManager rpcManager, Configuration configuration)
{
this.transactionManager = transactionManager;
this.rpcManager = rpcManager;
+ this.configuration = configuration;
+ }
+
+ @Start
+ public void start()
+ {
isOptimisticLocking = configuration.isNodeLockingOptimistic();
}
Modified: core/trunk/src/main/java/org/jboss/cache/util/reflect/ReflectionUtil.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/util/reflect/ReflectionUtil.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/main/java/org/jboss/cache/util/reflect/ReflectionUtil.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -2,6 +2,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.jboss.cache.CacheException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
@@ -162,4 +163,26 @@
}
return f;
}
+
+ /**
+ * Invokes a method using reflection, in an accessible manner (by using {@link Method#setAccessible(boolean)}
+ *
+ * @param instance instance on which to execute the method
+ * @param method method to execute
+ * @param parameters parameters
+ */
+ public static void invokeAccessibly(Object instance, Method method, Object[] parameters)
+ {
+ try
+ {
+ method.setAccessible(true);
+ method.invoke(instance, parameters);
+ }
+ catch (Exception e)
+ {
+ throw new CacheException("Unable to invoke method " + method + " on object instance " + instance +
+ (parameters != null ? " with parameters " + Arrays.asList(parameters) : ""));
+ }
+ }
+
}
Modified: core/trunk/src/test/java/org/jboss/cache/TreeCacheFunctionalTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/TreeCacheFunctionalTest.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/TreeCacheFunctionalTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -16,7 +16,7 @@
* @author Bela Ban
* @version $Id$
*/
-@Test(groups = {"functional"})
+@Test(groups = "functional")
public class TreeCacheFunctionalTest
{
CacheSPI<Object, Object> cache = null;
Modified: core/trunk/src/test/java/org/jboss/cache/api/NodeReplicatedMoveOptimisticTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/api/NodeReplicatedMoveOptimisticTest.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/api/NodeReplicatedMoveOptimisticTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -15,10 +15,4 @@
{
optimistic = true;
}
-
- @Override
- public void testReplicatability()
- {
- super.testReplicatability(); //To change body of overridden methods use File | Settings | File Templates.
- }
}
Modified: core/trunk/src/test/java/org/jboss/cache/api/pfer/PutForExternalReadTestBase.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/api/pfer/PutForExternalReadTestBase.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/api/pfer/PutForExternalReadTestBase.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -172,7 +172,7 @@
List<Address> memberList = originalRpcManager.getMembers();
expect(rpcManager.getMembers()).andReturn(memberList).anyTimes();
// inject a mock RPC manager so that we can test whether calls made are sync or async.
- TestingUtil.extractComponentRegistry(cache1).registerComponent(RPCManager.class.getName(), rpcManager, RPCManager.class);
+ TestingUtil.extractComponentRegistry(cache1).registerComponent(rpcManager, RPCManager.class);
// invalidations will not trigger any rpc call sfor PFER
if (!isUsingInvalidation())
@@ -189,7 +189,7 @@
verify(rpcManager);
// cleanup
- TestingUtil.extractComponentRegistry(cache1).registerComponent(RPCManager.class.getName(), originalRpcManager, RPCManager.class);
+ TestingUtil.extractComponentRegistry(cache1).registerComponent(originalRpcManager, RPCManager.class);
cache1.removeNode(fqn);
}
@@ -245,7 +245,7 @@
expect(barfingRpcManager.callRemoteMethods(anyAddresses(), (ReplicableCommand) anyObject(), anyBoolean(), anyLong(), anyBoolean())).andThrow(new RuntimeException("Barf!")).anyTimes();
replay(barfingRpcManager);
- TestingUtil.extractComponentRegistry(cache1).registerComponent(RPCManager.class.getName(), barfingRpcManager, RPCManager.class);
+ TestingUtil.extractComponentRegistry(cache1).registerComponent(barfingRpcManager, RPCManager.class);
cache1.getConfiguration().getRuntimeConfig().setRPCManager(barfingRpcManager);
try
@@ -283,7 +283,7 @@
}
finally
{
- TestingUtil.extractComponentRegistry(cache1).registerComponent(RPCManager.class.getName(), originalRpcManager, RPCManager.class);
+ TestingUtil.extractComponentRegistry(cache1).registerComponent(originalRpcManager, RPCManager.class);
}
}
Modified: core/trunk/src/test/java/org/jboss/cache/buddyreplication/BuddyManagerTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/buddyreplication/BuddyManagerTest.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/buddyreplication/BuddyManagerTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -13,7 +13,6 @@
import org.jboss.cache.config.BuddyReplicationConfig;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.factories.CommandsFactory;
-import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.factories.XmlConfigurationParser;
import org.jboss.cache.xml.XmlHelper;
import static org.testng.AssertJUnit.*;
Modified: core/trunk/src/test/java/org/jboss/cache/cluster/ReplicationQueueTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/cluster/ReplicationQueueTest.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/cluster/ReplicationQueueTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -7,7 +7,7 @@
import org.jboss.cache.RPCManager;
import org.jboss.cache.commands.ReplicableCommand;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.misc.TestingUtil;
import org.jgroups.Address;
import static org.testng.AssertJUnit.assertNotNull;
@@ -25,7 +25,7 @@
private static final int COUNT = 10;
Cache cache, cache2;
ReplicationQueue replQ;
- ComponentRegistry registry;
+ ComponentKernel registry;
RPCManager originalRpcManager;
@BeforeMethod
@@ -55,7 +55,7 @@
private void injectRpcManager(RPCManager manager)
{
- registry.registerComponent(RPCManager.class.getName(), manager, RPCManager.class);
+ registry.registerComponent(manager, RPCManager.class);
}
public void testQueueHoldAndFlush() throws Exception
Modified: core/trunk/src/test/java/org/jboss/cache/factories/ComponentRegistryFunctionalTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/factories/ComponentRegistryFunctionalTest.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/factories/ComponentRegistryFunctionalTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -1,23 +1,5 @@
package org.jboss.cache.factories;
-import org.jboss.cache.Cache;
-import org.jboss.cache.CacheFactory;
-import org.jboss.cache.DefaultCacheFactory;
-import org.jboss.cache.RPCManager;
-import org.jboss.cache.RegionManager;
-import org.jboss.cache.buddyreplication.BuddyManager;
-import org.jboss.cache.buddyreplication.NextMemberBuddyLocator;
-import org.jboss.cache.config.BuddyReplicationConfig;
-import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.annotations.Inject;
-import org.jboss.cache.marshall.CacheMarshaller200;
-import org.jboss.cache.marshall.CacheMarshaller210;
-import org.jboss.cache.marshall.Marshaller;
-import org.jboss.cache.marshall.VersionAwareMarshaller;
-import org.jboss.cache.misc.TestingUtil;
-import org.jboss.cache.notifications.Notifier;
-import org.jboss.cache.statetransfer.StateTransferManager;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
@@ -27,209 +9,209 @@
@Test(groups = {"functional"})
public class ComponentRegistryFunctionalTest
{
- private ComponentRegistry cr;
- private Configuration configuration;
-
- @BeforeMethod
- public void setUp() throws Exception
- {
- CacheFactory cf = new DefaultCacheFactory();
-
- Cache cache = cf.createCache(false);
- cr = TestingUtil.extractComponentRegistry(cache);
- configuration = cache.getConfiguration();
- }
-
- public void testDefaultFactoryScanning()
- {
- cr.scanDefaultFactories();
-
- assert cr.defaultFactories != null : "Should be populated";
-
- // at very least, expecting a Marshaller factory and a DefaultCacheFactory.
- assert cr.defaultFactories.containsKey(Marshaller.class);
- assert cr.defaultFactories.get(Marshaller.class).equals(EmptyConstructorFactory.class);
- assert cr.defaultFactories.containsKey(Notifier.class);
- assert cr.defaultFactories.get(Notifier.class).equals(EmptyConstructorFactory.class);
-
- }
-
- public void testDependencyConsistency()
- {
- for (ComponentRegistry.Component component : cr.componentLookup.values())
- {
- // test that this component appears in all dependencies' dependencyFor collection.
- for (ComponentRegistry.Component dep : component.dependencies)
- {
- assert cr.componentLookup.get(dep.name).dependencyFor.contains(component) : "Dependency " + dep.name + " does not have component " + component.name + " in it's dependencyFor collection.";
- }
- }
-
- for (ComponentRegistry.Component component : cr.componentLookup.values())
- {
- // test that this component appears in all dependencies' dependencyFor collection.
- for (ComponentRegistry.Component dep : component.dependencyFor)
- {
- assert cr.componentLookup.get(dep.name).dependencies.contains(component) : "Dependency " + dep.name + " does not have component " + component.name + " in it's dependencies collection.";
- }
- }
- }
-
-
- public void testNamedComponents()
- {
- cr.registerComponent("blah", new Object(), Object.class);
- Object namedComponent1 = cr.getOrCreateComponent("blah", Object.class);
- Object namedComponent2 = cr.getOrCreateComponent("blah", Object.class);
-
- assert namedComponent1 == namedComponent2;
- }
-
- /**
- * Case 1:
- * nothing injected, nothing specified in Configuration. Should use default factory.
- */
- public void testConstructionOrder1()
- {
- Class<Marshaller> componentToTest = Marshaller.class;
- Marshaller m = cr.getOrCreateComponent(null, componentToTest);
- assert m instanceof VersionAwareMarshaller;
- VersionAwareMarshaller vam = (VersionAwareMarshaller) m;
- vam.initReplicationVersions();
- m = (Marshaller) TestingUtil.extractField(vam, "defaultMarshaller");
- assert m instanceof CacheMarshaller210;
- }
-
- /**
- * Case 2:
- * instance injected, class specified in Configuration. Should use injected.
- */
- public void testConstructionOrder2()
- {
- Class<Marshaller> componentToTest = Marshaller.class;
- configuration.setMarshallerClass(CacheMarshaller200.class.getName());
- Marshaller instance = new CacheMarshaller210();
- configuration.setCacheMarshaller(instance);
-
- // the setup() would have wired the default marshaller. Need to update deps.
- cr.unregisterComponent(Marshaller.class);
- cr.updateDependencies();
-
- Marshaller m = cr.getOrCreateComponent(null, componentToTest);
- assert m == instance : "m is " + m + " but expected " + instance;
- }
-
- /**
- * Case 3:
- * instance injected, no class specified in Configuration. Should use injected.
- */
- public void testConstructionOrder3()
- {
- Class<Marshaller> componentToTest = Marshaller.class;
- Marshaller instance = new CacheMarshaller210();
- configuration.setCacheMarshaller(instance);
-
- // the setup() would have wired the default marshaller. Need to update deps.
- cr.unregisterComponent(Marshaller.class);
- cr.updateDependencies();
-
- Marshaller m = cr.getOrCreateComponent(null, componentToTest);
- assert m == instance : "m is " + m + " but expected " + instance;
- }
-
- /**
- * Case 4:
- * nothing injected, class specified in Configuration. Should use class specified.
- */
- public void testConstructionOrder4()
- {
- Class<Marshaller> componentToTest = Marshaller.class;
- configuration.setMarshallerClass(CacheMarshaller200.class.getName());
- Marshaller m = cr.getOrCreateComponent(null, componentToTest);
- assert m instanceof VersionAwareMarshaller;
- VersionAwareMarshaller vam = (VersionAwareMarshaller) m;
- vam.initReplicationVersions();
- m = (Marshaller) TestingUtil.extractField(vam, "defaultMarshaller");
- assert m instanceof CacheMarshaller200;
- }
-
- public void testTransitiveDependencies()
- {
- Class<BuddyManager> componentToTest = BuddyManager.class;
-
- // configure the cfg to use BR
- BuddyReplicationConfig brc = new BuddyReplicationConfig();
- brc.setEnabled(true);
- BuddyReplicationConfig.BuddyLocatorConfig blc = new BuddyReplicationConfig.BuddyLocatorConfig();
- blc.setBuddyLocatorClass(NextMemberBuddyLocator.class.getName());
- brc.setBuddyLocatorConfig(blc);
- configuration.setBuddyReplicationConfig(brc);
-
- // needs to be a non-LOCAL configuration
- configuration.setCacheMode(Configuration.CacheMode.REPL_ASYNC);
- BuddyManager bm = cr.getOrCreateComponent(null, componentToTest);
- assert bm != null;
-
- StateTransferManager stm = (StateTransferManager) TestingUtil.extractField(bm, "stateTransferManager");
- assert stm != null;
-
- RPCManager rpcm = (RPCManager) TestingUtil.extractField(bm, "rpcManager");
- assert rpcm != null;
-
- RegionManager rm = (RegionManager) TestingUtil.extractField(bm, "regionManager");
- assert rm != null;
-
- Configuration cfg = (Configuration) TestingUtil.extractField(bm, "configuration");
- assert cfg == configuration;
- }
-
- public void testInjectionOrder()
- {
- // injection should only occur after dependent components have been fully wired.
-
- // E.g. Test1 depends on Test2 and Test2 depends on Test3.
- //cr.reset();
-
- // DefaultFactoryFor annotation won't work since tests are compiled into a separate classpath
- cr.defaultFactories.put(Test1.class, EmptyConstructorFactory.class);
- cr.defaultFactories.put(Test2.class, EmptyConstructorFactory.class);
- cr.defaultFactories.put(Test3.class, EmptyConstructorFactory.class);
-
- Test1 t1 = cr.getOrCreateComponent(null, Test1.class);
-
- assert t1 != null;
- assert t1.test2 != null;
- assert t1.test2.test3 != null;
- assert t1.someValue == t1.test2.test3.someValue;
- }
-
- public static class Test1
- {
- private Test2 test2;
- private boolean someValue = false;
-
- @Inject
- public void setTest2(Test2 test2)
- {
- this.test2 = test2;
- someValue = test2.test3.someValue;
- }
- }
-
- public static class Test2
- {
- private Test3 test3;
-
- @Inject
- public void setTest3(Test3 test3)
- {
- this.test3 = test3;
- }
- }
-
- public static class Test3
- {
- private boolean someValue = true;
- }
+// private ComponentRegistry cr;
+// private Configuration configuration;
+//
+// @BeforeMethod
+// public void setUp() throws Exception
+// {
+// CacheFactory cf = new DefaultCacheFactory();
+//
+// Cache cache = cf.createCache(false);
+// cr = TestingUtil.extractComponentRegistry(cache);
+// configuration = cache.getConfiguration();
+// }
+//
+// public void testDefaultFactoryScanning()
+// {
+// cr.scanDefaultFactories();
+//
+// assert cr.defaultFactories != null : "Should be populated";
+//
+// // at very least, expecting a Marshaller factory and a DefaultCacheFactory.
+// assert cr.defaultFactories.containsKey(Marshaller.class);
+// assert cr.defaultFactories.get(Marshaller.class).equals(EmptyConstructorFactory.class);
+// assert cr.defaultFactories.containsKey(Notifier.class);
+// assert cr.defaultFactories.get(Notifier.class).equals(EmptyConstructorFactory.class);
+//
+// }
+//
+// public void testDependencyConsistency()
+// {
+// for (ComponentRegistry.Component component : cr.componentLookup.values())
+// {
+// // test that this component appears in all dependencies' dependencyFor collection.
+// for (ComponentRegistry.Component dep : component.dependencies)
+// {
+// assert cr.componentLookup.get(dep.name).dependencyFor.contains(component) : "Dependency " + dep.name + " does not have component " + component.name + " in it's dependencyFor collection.";
+// }
+// }
+//
+// for (ComponentRegistry.Component component : cr.componentLookup.values())
+// {
+// // test that this component appears in all dependencies' dependencyFor collection.
+// for (ComponentRegistry.Component dep : component.dependencyFor)
+// {
+// assert cr.componentLookup.get(dep.name).dependencies.contains(component) : "Dependency " + dep.name + " does not have component " + component.name + " in it's dependencies collection.";
+// }
+// }
+// }
+//
+//
+// public void testNamedComponents()
+// {
+// cr.registerComponent("blah", new Object(), Object.class);
+// Object namedComponent1 = cr.getOrCreateComponent("blah", Object.class);
+// Object namedComponent2 = cr.getOrCreateComponent("blah", Object.class);
+//
+// assert namedComponent1 == namedComponent2;
+// }
+//
+// /**
+// * Case 1:
+// * nothing injected, nothing specified in Configuration. Should use default factory.
+// */
+// public void testConstructionOrder1()
+// {
+// Class<Marshaller> componentToTest = Marshaller.class;
+// Marshaller m = cr.getOrCreateComponent(null, componentToTest);
+// assert m instanceof VersionAwareMarshaller;
+// VersionAwareMarshaller vam = (VersionAwareMarshaller) m;
+// vam.initReplicationVersions();
+// m = (Marshaller) TestingUtil.extractField(vam, "defaultMarshaller");
+// assert m instanceof CacheMarshaller210;
+// }
+//
+// /**
+// * Case 2:
+// * instance injected, class specified in Configuration. Should use injected.
+// */
+// public void testConstructionOrder2()
+// {
+// Class<Marshaller> componentToTest = Marshaller.class;
+// configuration.setMarshallerClass(CacheMarshaller200.class.getName());
+// Marshaller instance = new CacheMarshaller210();
+// configuration.setCacheMarshaller(instance);
+//
+// // the setup() would have wired the default marshaller. Need to update deps.
+// cr.unregisterComponent(Marshaller.class);
+// cr.updateDependencies();
+//
+// Marshaller m = cr.getOrCreateComponent(null, componentToTest);
+// assert m == instance : "m is " + m + " but expected " + instance;
+// }
+//
+// /**
+// * Case 3:
+// * instance injected, no class specified in Configuration. Should use injected.
+// */
+// public void testConstructionOrder3()
+// {
+// Class<Marshaller> componentToTest = Marshaller.class;
+// Marshaller instance = new CacheMarshaller210();
+// configuration.setCacheMarshaller(instance);
+//
+// // the setup() would have wired the default marshaller. Need to update deps.
+// cr.unregisterComponent(Marshaller.class);
+// cr.updateDependencies();
+//
+// Marshaller m = cr.getOrCreateComponent(null, componentToTest);
+// assert m == instance : "m is " + m + " but expected " + instance;
+// }
+//
+// /**
+// * Case 4:
+// * nothing injected, class specified in Configuration. Should use class specified.
+// */
+// public void testConstructionOrder4()
+// {
+// Class<Marshaller> componentToTest = Marshaller.class;
+// configuration.setMarshallerClass(CacheMarshaller200.class.getName());
+// Marshaller m = cr.getOrCreateComponent(null, componentToTest);
+// assert m instanceof VersionAwareMarshaller;
+// VersionAwareMarshaller vam = (VersionAwareMarshaller) m;
+// vam.initReplicationVersions();
+// m = (Marshaller) TestingUtil.extractField(vam, "defaultMarshaller");
+// assert m instanceof CacheMarshaller200;
+// }
+//
+// public void testTransitiveDependencies()
+// {
+// Class<BuddyManager> componentToTest = BuddyManager.class;
+//
+// // configure the cfg to use BR
+// BuddyReplicationConfig brc = new BuddyReplicationConfig();
+// brc.setEnabled(true);
+// BuddyReplicationConfig.BuddyLocatorConfig blc = new BuddyReplicationConfig.BuddyLocatorConfig();
+// blc.setBuddyLocatorClass(NextMemberBuddyLocator.class.getName());
+// brc.setBuddyLocatorConfig(blc);
+// configuration.setBuddyReplicationConfig(brc);
+//
+// // needs to be a non-LOCAL configuration
+// configuration.setCacheMode(Configuration.CacheMode.REPL_ASYNC);
+// BuddyManager bm = cr.getOrCreateComponent(null, componentToTest);
+// assert bm != null;
+//
+// StateTransferManager stm = (StateTransferManager) TestingUtil.extractField(bm, "stateTransferManager");
+// assert stm != null;
+//
+// RPCManager rpcm = (RPCManager) TestingUtil.extractField(bm, "rpcManager");
+// assert rpcm != null;
+//
+// RegionManager rm = (RegionManager) TestingUtil.extractField(bm, "regionManager");
+// assert rm != null;
+//
+// Configuration cfg = (Configuration) TestingUtil.extractField(bm, "configuration");
+// assert cfg == configuration;
+// }
+//
+// public void testInjectionOrder()
+// {
+// // injection should only occur after dependent components have been fully wired.
+//
+// // E.g. Test1 depends on Test2 and Test2 depends on Test3.
+// //cr.reset();
+//
+// // DefaultFactoryFor annotation won't work since tests are compiled into a separate classpath
+// cr.defaultFactories.put(Test1.class, EmptyConstructorFactory.class);
+// cr.defaultFactories.put(Test2.class, EmptyConstructorFactory.class);
+// cr.defaultFactories.put(Test3.class, EmptyConstructorFactory.class);
+//
+// Test1 t1 = cr.getOrCreateComponent(null, Test1.class);
+//
+// assert t1 != null;
+// assert t1.test2 != null;
+// assert t1.test2.test3 != null;
+// assert t1.someValue == t1.test2.test3.someValue;
+// }
+//
+// public static class Test1
+// {
+// private Test2 test2;
+// private boolean someValue = false;
+//
+// @Inject
+// public void setTest2(Test2 test2)
+// {
+// this.test2 = test2;
+// someValue = test2.test3.someValue;
+// }
+// }
+//
+// public static class Test2
+// {
+// private Test3 test3;
+//
+// @Inject
+// public void setTest3(Test3 test3)
+// {
+// this.test3 = test3;
+// }
+// }
+//
+// public static class Test3
+// {
+// private boolean someValue = true;
+// }
}
Modified: core/trunk/src/test/java/org/jboss/cache/factories/ComponentRegistryUnitTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/factories/ComponentRegistryUnitTest.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/factories/ComponentRegistryUnitTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -1,9 +1,8 @@
package org.jboss.cache.factories;
+import org.jboss.cache.Cache;
+import org.jboss.cache.DefaultCacheFactory;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.annotations.ComponentName;
-import org.jboss.cache.factories.annotations.Inject;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
@@ -13,95 +12,103 @@
@Test(groups = "functional")
public class ComponentRegistryUnitTest
{
- ComponentRegistry cr;
- Configuration cfg;
-
- @BeforeMethod
- public void setUp()
+ public void testConstruction()
{
- cr = new ComponentRegistry(new Configuration());
- cfg = cr.getConfiguration();
+ Cache c = new DefaultCacheFactory().createCache(UnitTestCacheConfigurationFactory.createConfiguration(Configuration.CacheMode.REPL_SYNC));
+ c.put("/a", "b", "c");
+ c.stop();
+ c.destroy();
}
- public void testChangingComponentState()
- {
- cr.registerComponent("c2", new C2(), C2.class);
- cr.registerComponent("c1", new C1(), C1.class);
- cr.registerComponent("c3", new C3(), C3.class);
-
- ComponentRegistry.Component c1 = cr.componentLookup.get("c1");
- ComponentRegistry.Component c2 = cr.componentLookup.get("c2");
- ComponentRegistry.Component c3 = cr.componentLookup.get("c3");
-
- // add some dependencies
- ComponentRegistry.Component d1 = cr.new Component("c1", null);
- ComponentRegistry.Component d2 = cr.new Component("c2", null);
- ComponentRegistry.Component d3 = cr.new Component("c3", null);
-
- // c1 depends on c2
- // c3 depends on c1
-
- // test dependency and dependencyFor
-
- assert c2.dependencies.isEmpty();
- assert c1.dependencies.contains(d2);
- assert c1.dependencies.size() == 1;
- assert c3.dependencies.contains(d1);
- assert c3.dependencies.size() == 1;
-
- assert c2.dependencyFor.contains(d1);
- assert c2.dependencyFor.size() == 1;
- assert c1.dependencyFor.contains(d3);
- assert c1.dependencyFor.size() == 1;
- assert c3.dependencyFor.isEmpty();
-
- assert c1.state == ComponentRegistry.State.CONSTRUCTED;
- assert c2.state == ComponentRegistry.State.CONSTRUCTED;
- assert c3.state == ComponentRegistry.State.CONSTRUCTED;
-
- c1.changeState(ComponentRegistry.State.WIRED);
-
- assert c1.state == ComponentRegistry.State.WIRED;
- assert c2.state == ComponentRegistry.State.WIRED;
- assert c3.state == ComponentRegistry.State.CONSTRUCTED;
-
- c3.changeState(ComponentRegistry.State.STARTED);
-
- assert c1.state == ComponentRegistry.State.STARTED;
- assert c2.state == ComponentRegistry.State.STARTED;
- assert c3.state == ComponentRegistry.State.STARTED;
-
- c1.changeState(ComponentRegistry.State.CONSTRUCTED);
-
- assert c1.state == ComponentRegistry.State.CONSTRUCTED;
- assert c2.state == ComponentRegistry.State.STARTED;
- assert c3.state == ComponentRegistry.State.CONSTRUCTED;
- }
-
- public static class C1
- {
- C2 c2;
-
- @Inject
- private void inject(@ComponentName("c2")C2 c2)
- {
- this.c2 = c2;
- }
- }
-
- public static class C2
- {
-
- }
-
- public static class C3
- {
- C1 c1;
-
- @Inject
- private void inject(@ComponentName("c1")C1 c1)
- {
- this.c1 = c1;
- }
- }
+// ComponentRegistry cr;
+// Configuration cfg;
+//
+// @BeforeMethod
+// public void setUp()
+// {
+// cr = new ComponentRegistry(new Configuration());
+// cfg = cr.getConfiguration();
+// }
+//
+// public void testChangingComponentState()
+// {
+// cr.registerComponent("c2", new C2(), C2.class);
+// cr.registerComponent("c1", new C1(), C1.class);
+// cr.registerComponent("c3", new C3(), C3.class);
+//
+// ComponentRegistry.Component c1 = cr.componentLookup.get("c1");
+// ComponentRegistry.Component c2 = cr.componentLookup.get("c2");
+// ComponentRegistry.Component c3 = cr.componentLookup.get("c3");
+//
+// // add some dependencies
+// ComponentRegistry.Component d1 = cr.new Component("c1", null);
+// ComponentRegistry.Component d2 = cr.new Component("c2", null);
+// ComponentRegistry.Component d3 = cr.new Component("c3", null);
+//
+// // c1 depends on c2
+// // c3 depends on c1
+//
+// // test dependency and dependencyFor
+//
+// assert c2.dependencies.isEmpty();
+// assert c1.dependencies.contains(d2);
+// assert c1.dependencies.size() == 1;
+// assert c3.dependencies.contains(d1);
+// assert c3.dependencies.size() == 1;
+//
+// assert c2.dependencyFor.contains(d1);
+// assert c2.dependencyFor.size() == 1;
+// assert c1.dependencyFor.contains(d3);
+// assert c1.dependencyFor.size() == 1;
+// assert c3.dependencyFor.isEmpty();
+//
+// assert c1.state == ComponentRegistry.State.CONSTRUCTED;
+// assert c2.state == ComponentRegistry.State.CONSTRUCTED;
+// assert c3.state == ComponentRegistry.State.CONSTRUCTED;
+//
+// c1.changeState(ComponentRegistry.State.WIRED);
+//
+// assert c1.state == ComponentRegistry.State.WIRED;
+// assert c2.state == ComponentRegistry.State.WIRED;
+// assert c3.state == ComponentRegistry.State.CONSTRUCTED;
+//
+// c3.changeState(ComponentRegistry.State.STARTED);
+//
+// assert c1.state == ComponentRegistry.State.STARTED;
+// assert c2.state == ComponentRegistry.State.STARTED;
+// assert c3.state == ComponentRegistry.State.STARTED;
+//
+// c1.changeState(ComponentRegistry.State.CONSTRUCTED);
+//
+// assert c1.state == ComponentRegistry.State.CONSTRUCTED;
+// assert c2.state == ComponentRegistry.State.STARTED;
+// assert c3.state == ComponentRegistry.State.CONSTRUCTED;
+// }
+//
+// public static class C1
+// {
+// C2 c2;
+//
+// @Inject
+// private void inject(@ComponentName("c2")C2 c2)
+// {
+// this.c2 = c2;
+// }
+// }
+//
+// public static class C2
+// {
+//
+// }
+//
+// public static class C3
+// {
+// C1 c1;
+//
+// @Inject
+// private void inject(@ComponentName("c1")C1 c1)
+// {
+// this.c1 = c1;
+// }
+// }
}
Copied: core/trunk/src/test/java/org/jboss/cache/factories/LifeCycleTest.java (from rev 5802, core/trunk/src/test/java/org/jboss/cache/LifeCycleTest.java)
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/factories/LifeCycleTest.java (rev 0)
+++ core/trunk/src/test/java/org/jboss/cache/factories/LifeCycleTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -0,0 +1,482 @@
+package org.jboss.cache.factories;
+
+import org.jboss.cache.Cache;
+import org.jboss.cache.CacheException;
+import org.jboss.cache.CacheSPI;
+import org.jboss.cache.CacheStatus;
+import org.jboss.cache.DefaultCacheFactory;
+import org.jboss.cache.Fqn;
+import org.jboss.cache.ReplicationException;
+import org.jboss.cache.SuspectException;
+import org.jboss.cache.config.Configuration;
+import org.jboss.cache.misc.TestingUtil;
+import org.jboss.cache.notifications.annotation.CacheListener;
+import org.jboss.cache.notifications.annotation.CacheStarted;
+import org.jboss.cache.notifications.annotation.CacheStopped;
+import org.jboss.cache.notifications.event.Event;
+import org.testng.AssertJUnit;
+import static org.testng.AssertJUnit.*;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.Test;
+
+import javax.transaction.NotSupportedException;
+import javax.transaction.RollbackException;
+import javax.transaction.SystemException;
+import javax.transaction.TransactionManager;
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * Tests restart (stop-destroy-create-start) of ComponentRegistry
+ *
+ * @author Bela Ban
+ * @version $Id$
+ */
+@Test(groups = "functional")
+public class LifeCycleTest
+{
+ private CacheSPI[] c;
+
+ @AfterMethod
+ public void tearDown()
+ {
+ TestingUtil.killCaches(c);
+ c = null;
+ }
+
+ private void createAndRegisterCache(Configuration.CacheMode mode, boolean start) throws Exception
+ {
+ Cache cache = createCache(mode);
+ List<Cache> caches = new LinkedList<Cache>();
+ if (c != null) caches.addAll(Arrays.asList(c));
+ caches.add(cache);
+ c = caches.toArray(new CacheSPI[]{});
+ if (start)
+ {
+ cache.start();
+ if (c.length > 1) TestingUtil.blockUntilViewsReceived(c, 10000);
+ }
+ }
+
+
+ public void testLocalRestartNoTransactions() throws Exception
+ {
+ createAndRegisterCache(Configuration.CacheMode.LOCAL, true);
+
+ c[0].put("/a/b/c", null);
+ assertTrue(c[0].getNumberOfNodes() > 0);
+ assertEquals(0, c[0].getNumberOfLocksHeld());
+
+ restartCache(c[0]);
+
+ assertEquals(0, c[0].getNumberOfNodes());
+ assertEquals(0, c[0].getNumberOfLocksHeld());
+ }
+
+ public void testLocalRestartWithTransactions() throws Exception
+ {
+ createAndRegisterCache(Configuration.CacheMode.LOCAL, true);
+
+ TransactionManager tm = beginTransaction();
+
+ c[0].put("/a/b/c", null);
+ assertTrue(c[0].getNumberOfNodes() > 0);
+ assertEquals(4, c[0].getNumberOfLocksHeld());
+
+ restartCache(c[0]);
+
+ //assertEquals(4, cache.getNumberOfLocksHeld());
+ assertEquals(0, c[0].getNumberOfNodes());
+
+ tm.rollback();
+ assertEquals(0, c[0].getNumberOfLocksHeld());
+ }
+
+ public void testStartNoCreate() throws Exception
+ {
+ createAndRegisterCache(Configuration.CacheMode.LOCAL, false);
+ c[0].start();
+
+ c[0].put("/a/b/c", null);
+ assertTrue(c[0].getNumberOfNodes() > 0);
+ assertEquals(0, c[0].getNumberOfLocksHeld());
+
+ restartCache(c[0]);
+
+ assertEquals(0, c[0].getNumberOfNodes());
+ assertEquals(0, c[0].getNumberOfLocksHeld());
+ }
+
+ public void testReStartNoCreate() throws Exception
+ {
+ createAndRegisterCache(Configuration.CacheMode.LOCAL, false);
+ c[0].start();
+ c[0].stop();
+ c[0].start();
+
+ c[0].put("/a/b/c", null);
+ assertTrue(c[0].getNumberOfNodes() > 0);
+ assertEquals(0, c[0].getNumberOfLocksHeld());
+
+ restartCache(c[0]);
+
+ assertEquals(0, c[0].getNumberOfNodes());
+ assertEquals(0, c[0].getNumberOfLocksHeld());
+ }
+
+ public void testDuplicateInvocation() throws Exception
+ {
+ createAndRegisterCache(Configuration.CacheMode.LOCAL, false);
+ c[0].create();
+ c[0].start();
+ c[0].create();
+ c[0].start();
+
+ c[0].put("/a/b/c", null);
+ assertTrue(c[0].getNumberOfNodes() > 0);
+ assertEquals(0, c[0].getNumberOfLocksHeld());
+
+ restartCache(c[0]);
+
+ assertEquals(0, c[0].getNumberOfNodes());
+ assertEquals(0, c[0].getNumberOfLocksHeld());
+
+ c[0].stop();
+ c[0].destroy();
+ c[0].stop();
+ c[0].destroy();
+ }
+
+ public void testFailedStart() throws Exception
+ {
+
+ createAndRegisterCache(Configuration.CacheMode.LOCAL, false);
+ AssertJUnit.assertEquals("Correct state", CacheStatus.INSTANTIATED, c[0].getCacheStatus());
+
+ DisruptLifecycleListener listener = new DisruptLifecycleListener();
+ c[0].addCacheListener(listener);
+
+ c[0].create();
+
+ listener.disrupt = true;
+
+ assertEquals("Correct state", CacheStatus.CREATED, c[0].getCacheStatus());
+ try
+ {
+ c[0].start();
+ fail("Listener did not prevent start");
+ }
+ catch (CacheException good)
+ {
+ }
+
+ assertEquals("Correct state", CacheStatus.FAILED, c[0].getCacheStatus());
+
+ c[0].addCacheListener(listener);
+ listener.disrupt = false;
+
+ c[0].start();
+
+ assertEquals("Correct state", CacheStatus.STARTED, c[0].getCacheStatus());
+
+ c[0].put("/a/b/c", null);
+ assertTrue(c[0].getNumberOfNodes() > 0);
+ assertEquals(0, c[0].getNumberOfLocksHeld());
+
+ listener.disrupt = true;
+ c[0].addCacheListener(listener);
+
+ try
+ {
+ c[0].stop();
+ fail("Listener did not prevent stop");
+ }
+ catch (CacheException good)
+ {
+ }
+
+ assertEquals("Correct state", CacheStatus.FAILED, c[0].getCacheStatus());
+
+ listener.disrupt = false;
+
+ c[0].stop();
+ assertEquals("Correct state", CacheStatus.STOPPED, c[0].getCacheStatus());
+ c[0].destroy();
+ assertEquals("Correct state", CacheStatus.DESTROYED, c[0].getCacheStatus());
+ }
+
+ public void testInvalidStateInvocations() throws Exception
+ {
+ createAndRegisterCache(Configuration.CacheMode.LOCAL, false);
+ try
+ {
+ c[0].get(Fqn.ROOT, "k");
+ fail("Cache isn't ready!");
+ }
+ catch (IllegalStateException good)
+ {
+ }
+
+ c[0].create();
+ try
+ {
+ c[0].get(Fqn.ROOT, "k");
+ fail("Cache isn't ready!");
+ }
+ catch (IllegalStateException good)
+ {
+ }
+
+ c[0].start();
+ c[0].get(Fqn.ROOT, "k"); // should work
+
+ c[0].stop();
+
+ try
+ {
+ c[0].get(Fqn.ROOT, "k");
+ fail("Cache isn't ready!");
+ }
+ catch (IllegalStateException good)
+ {
+ }
+
+ c[0].destroy();
+ try
+ {
+ c[0].get(Fqn.ROOT, "k");
+ fail("Cache isn't ready!");
+ }
+ catch (IllegalStateException good)
+ {
+ }
+ }
+
+ public void testRemoteInvalidStateInvocations() throws Exception
+ {
+ createAndRegisterCache(Configuration.CacheMode.REPL_SYNC, true);
+ createAndRegisterCache(Configuration.CacheMode.REPL_SYNC, true);
+ try
+ {
+ // now DIRECTLY change the status of c2.
+ // emulate the race condition where the remote cache is stopping but hasn't disconnected from the channel.
+ ComponentKernel cr1 = TestingUtil.extractComponentRegistry(c[1]);
+ cr1.state = CacheStatus.STOPPING;
+
+ // Thanks to JBCACHE-1179, this should only log a warning and not throw an exception
+ c[0].put(Fqn.ROOT, "k", "v");
+ }
+ finally
+ {
+ // reset c[1] to running so the tearDown method can clean it up
+ ComponentKernel cr1 = TestingUtil.extractComponentRegistry(c[1]);
+ cr1.state = CacheStatus.STARTED;
+ }
+ }
+
+ public void testRemoteInvalidStateInvocations2() throws Exception
+ {
+ createAndRegisterCache(Configuration.CacheMode.REPL_SYNC, true);
+ createAndRegisterCache(Configuration.CacheMode.REPL_SYNC, true);
+ TestingUtil.blockUntilViewsReceived(c, 10000);
+ try
+ {
+ // now DIRECTLY change the status of c2.
+ // emulate the race condition where the remote cache is stopping but hasn't disconnected from the channel.
+
+ // there is a lousy race condition here - we need to make sure cache[1]'s start() method doesn't set status to STARTED
+ // after we attempt to change this.
+ TestingUtil.blockUntilCacheStatusAchieved(c[1], CacheStatus.STARTED, 1000);
+ ComponentKernel cr1 = TestingUtil.extractComponentRegistry(c[1]);
+ cr1.state = CacheStatus.STARTING;
+ try
+ {
+ // This call should wait for up to StateRetrievalTimeout secs or until c[1] has entered the STARTED state, and then barf.
+ c[0].put(Fqn.ROOT, "k", "v");
+ fail("Should barf!");
+ }
+ catch (Exception good)
+ {
+
+ }
+
+ // now kick off another thread to sleep for a few secs and then set c[1] to STARTED
+ final int sleepTime = 500;
+ new Thread()
+ {
+ public void run()
+ {
+ TestingUtil.sleepThread(sleepTime);
+ ComponentKernel cr1 = TestingUtil.extractComponentRegistry(c[1]);
+ cr1.state = CacheStatus.STARTED;
+ }
+ }.start();
+
+ // should succeed but should take at least 1000ms.
+ long startTime = System.currentTimeMillis();
+ c[0].put(Fqn.ROOT, "k", "v");
+ assert System.currentTimeMillis() > (startTime + sleepTime) : "Should wait till c[1] has STARTED state";
+
+ }
+ finally
+ {
+ // reset c[1] to running so the tearDown method can clean it up
+ ComponentKernel cr1 = TestingUtil.extractComponentRegistry(c[1]);
+ cr1.state = CacheStatus.STARTED;
+ }
+ }
+
+ public void testInvalidStateTxCommit() throws Exception
+ {
+ createAndRegisterCache(Configuration.CacheMode.LOCAL, true);
+ c[0].getTransactionManager().begin();
+ c[0].put(Fqn.ROOT, "k1", "v1");
+ c[0].put(Fqn.ROOT, "k2", "v2");
+
+ // now DIRECTLY change the status of c.
+ ComponentKernel cr0 = TestingUtil.extractComponentRegistry(c[0]);
+ cr0.state = CacheStatus.STOPPING;
+
+ try
+ {
+ c[0].getTransactionManager().commit();
+ fail("Cache isn't STARTED!");
+ }
+ catch (RollbackException good)
+ {
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public void testStopInstanceWhileOtherInstanceSends() throws Exception
+ {
+ final Fqn fqn = Fqn.fromString("/a");
+ final List<Boolean> running = new LinkedList<Boolean>();
+ final List<Exception> exceptions = new LinkedList<Exception>();
+ running.add(true);
+
+ createAndRegisterCache(Configuration.CacheMode.REPL_SYNC, true);
+ createAndRegisterCache(Configuration.CacheMode.REPL_SYNC, true);
+
+ c[0].put(fqn, "k", "v");
+
+ assert "v".equals(c[0].get(fqn, "k"));
+ assert "v".equals(c[1].get(fqn, "k"));
+
+ // now kick start a thread on c[1] that will constantly update the fqn
+
+ Thread updater = new Thread()
+ {
+ public void run()
+ {
+ int i = 0;
+ while (running.get(0))
+ {
+ try
+ {
+ i++;
+ if (running.get(0)) c[1].put(fqn, "k", "v" + i);
+ }
+ catch (ReplicationException re)
+ {
+ // this sometimes happens when JGroups suspects the remote node. This is ok, as long as we don't get an ISE.
+ }
+ catch (SuspectException se)
+ {
+ // this sometimes happens when JGroups suspects the remote node. This is ok, as long as we don't get an ISE.
+ }
+ catch (Exception e)
+ {
+ exceptions.add(e);
+ }
+ TestingUtil.sleepThread(20);
+
+ }
+ }
+ };
+
+ updater.start();
+
+ c[0].stop();
+ running.add(false);
+ running.remove(true);
+ updater.join();
+
+ for (Exception e : exceptions) throw e;
+ }
+
+ public void testInvalidStateTxRollback() throws Exception
+ {
+ createAndRegisterCache(Configuration.CacheMode.LOCAL, true);
+ c[0].getTransactionManager().begin();
+ c[0].put(Fqn.ROOT, "k1", "v1");
+ c[0].put(Fqn.ROOT, "k2", "v2");
+
+ // now DIRECTLY change the status of c.
+ ComponentKernel cr0 = TestingUtil.extractComponentRegistry(c[0]);
+ cr0.state = CacheStatus.STOPPING;
+
+ // rollbacks should just log a message
+ c[0].getTransactionManager().rollback();
+ }
+
+
+ private CacheSPI<Object, Object> createCache(Configuration.CacheMode cache_mode)
+ {
+ CacheSPI<Object, Object> retval = (CacheSPI<Object, Object>) new DefaultCacheFactory().createCache(false);
+ retval.getConfiguration().setCacheMode(cache_mode);
+ retval.getConfiguration().setTransactionManagerLookupClass("org.jboss.cache.transaction.DummyTransactionManagerLookup");
+ return retval;
+ }
+
+
+ private TransactionManager beginTransaction() throws SystemException, NotSupportedException
+ {
+ TransactionManager mgr = c[0].getConfiguration().getRuntimeConfig().getTransactionManager();
+ mgr.begin();
+ return mgr;
+ }
+
+
+ private void startCache(CacheSPI c)
+ {
+ c.create();
+ c.start();
+ }
+
+ private void stopCache(CacheSPI c)
+ {
+ c.stop();
+ c.destroy();
+ }
+
+ private void restartCache(CacheSPI c) throws Exception
+ {
+ stopCache(c);
+ startCache(c);
+ }
+
+ @CacheListener
+ public class DisruptLifecycleListener
+ {
+ private boolean disrupt;
+
+ @CacheStarted
+ public void cacheStarted(Event e)
+ {
+ if (disrupt) throw new IllegalStateException("I don't want to start");
+ }
+
+ @CacheStopped
+ public void cacheStopped(Event e)
+ {
+ if (disrupt) throw new IllegalStateException("I don't want to stop");
+ }
+
+ public void setDisrupt(boolean disrupt)
+ {
+ this.disrupt = disrupt;
+ }
+ }
+}
Property changes on: core/trunk/src/test/java/org/jboss/cache/factories/LifeCycleTest.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Modified: core/trunk/src/test/java/org/jboss/cache/lock/IdentityLockTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/lock/IdentityLockTest.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/lock/IdentityLockTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -36,10 +36,7 @@
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception
{
- lock_ = new IdentityLock(NODE);
-
- // try { Thread.TestingUtil.sleepThread(10000); } catch (Exception e) {
- // }
+ lock_ = new IdentityLock(new LockStrategyFactory(), NODE);
}
@AfterMethod(alwaysRun = true)
@@ -53,15 +50,17 @@
private void setLevelRW()
{
log("set lock level to RWUpgrade ...");
- LockStrategyFactory.setIsolationLevel(IsolationLevel.REPEATABLE_READ);
- lock_ = new IdentityLock(NODE);
+ LockStrategyFactory lsf = new LockStrategyFactory();
+ lsf.setIsolationLevel(IsolationLevel.REPEATABLE_READ);
+ lock_ = new IdentityLock(lsf, NODE);
}
private void setLevelSerial()
{
log("set lock level to SimpleLock ...");
- LockStrategyFactory.setIsolationLevel(IsolationLevel.SERIALIZABLE);
- lock_ = new IdentityLock(NODE);
+ LockStrategyFactory lsf = new LockStrategyFactory();
+ lsf.setIsolationLevel(IsolationLevel.SERIALIZABLE);
+ lock_ = new IdentityLock(lsf, NODE);
}
private GlobalTransaction getGlobalTransactionFromThread()
@@ -534,7 +533,7 @@
/**
* When IdentityLock.toString is called and readLockOwners are modified an ConcurrentModificationException exception
- * might be thrown.
+ * might be thrown.
*/
public void testConcurrentModificationOfReadLocksAndToString() throws Exception
{
@@ -547,7 +546,7 @@
{
for (int i = 0; i < opCount; i++)
{
- if (i%10 ==0) System.out.println("readLockChanger loop# " + i);
+ if (i % 10 == 0) System.out.println("readLockChanger loop# " + i);
lockMap.addReader(new Object());
}
}
@@ -561,7 +560,7 @@
long initialTime = System.currentTimeMillis();
for (int i = 0; i < opCount; i++)
{
- if (i%10 ==0)
+ if (i % 10 == 0)
{
System.out.println("toStringProcessor loop# " + i + ", " + (System.currentTimeMillis() - initialTime));
initialTime = System.currentTimeMillis();
@@ -569,7 +568,8 @@
try
{
iLock.toString(new StringBuffer(), false);
- } catch (Exception e)
+ }
+ catch (Exception e)
{
e.printStackTrace();
flags[0] = true;
@@ -587,7 +587,7 @@
readLockChanger.join();
flags[1] = true;//stopping the toStringProcessor
System.out.println("readLockChanger stopped");
-
+
toStringProcessor.join();
System.out.println("toStringProcessor stopped");
Modified: core/trunk/src/test/java/org/jboss/cache/marshall/AbstractVersionAwareMarshallerTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/marshall/AbstractVersionAwareMarshallerTest.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/marshall/AbstractVersionAwareMarshallerTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -1,9 +1,10 @@
package org.jboss.cache.marshall;
+import org.jboss.cache.CacheStatus;
import org.jboss.cache.RegionManager;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.factories.CommandsFactory;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
/**
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
@@ -11,7 +12,7 @@
*/
public abstract class AbstractVersionAwareMarshallerTest
{
- protected ComponentRegistry cr;
+ protected ComponentKernel cr;
protected VersionAwareMarshaller createVAMandRestartCache(String replVersion)
{
@@ -24,11 +25,11 @@
{
cr.registerComponent(rm, RegionManager.class);
VersionAwareMarshaller vam = (VersionAwareMarshaller) cr.getComponent(Marshaller.class);
- if (cr.getOverallState() == ComponentRegistry.State.STARTED) cr.stop();
+ if (cr.getState() == CacheStatus.STARTED) cr.stop();
CommandsFactory cf = cr.getComponent(CommandsFactory.class);
if (cf == null) cf = new CommandsFactory();
- cr.registerComponent(CommandsFactory.class.getName(), cf, CommandsFactory.class);
+ cr.registerComponent(cf, CommandsFactory.class);
cr.start();
return vam;
Modified: core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshaller200Test.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshaller200Test.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshaller200Test.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -10,7 +10,7 @@
import org.jboss.cache.Region;
import org.jboss.cache.RegionManager;
import org.jboss.cache.commands.remote.ClusteredGetCommand;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import org.testng.annotations.Test;
import java.io.ByteArrayInputStream;
@@ -87,7 +87,7 @@
final CacheMarshaller200 cm200 = new CacheMarshaller200();
c.setInactiveOnStartup(false);
c.setUseRegionBasedMarshalling(true);
- ComponentRegistry cr = new ComponentRegistry(c);
+ ComponentKernel cr = new ComponentKernel(c);
cr.registerComponent(cm200, CacheMarshaller200.class);
cr.start();
Modified: core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshallerTestBase.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshallerTestBase.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/marshall/CacheMarshallerTestBase.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -12,7 +12,7 @@
import org.jboss.cache.commands.remote.ReplicateCommand;
import org.jboss.cache.commands.write.PutKeyValueCommand;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import org.testng.annotations.AfterMethod;
@@ -40,7 +40,7 @@
c.setUseRegionBasedMarshalling(false);
c.setInactiveOnStartup(false);
c.setReplVersionString(currentVersion);
- cr = new ComponentRegistry(c);
+ cr = new ComponentKernel(c);
//c.setUseReferenceCounting(true);
marshaller = createVAMandRestartCache(regionManager);
}
Modified: core/trunk/src/test/java/org/jboss/cache/marshall/MarshalledValueTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/marshall/MarshalledValueTest.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/marshall/MarshalledValueTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -9,7 +9,7 @@
import org.jboss.cache.commands.write.PutKeyValueCommand;
import org.jboss.cache.config.CacheLoaderConfig;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.factories.UnitTestCacheConfigurationFactory;
import org.jboss.cache.interceptors.MarshalledValueInterceptor;
import org.jboss.cache.interceptors.base.CommandInterceptor;
@@ -217,7 +217,7 @@
MarshalledValue mv = new MarshalledValue(pojo);
Configuration c = new Configuration();
- ComponentRegistry cr = new ComponentRegistry(c);
+ ComponentKernel cr = new ComponentKernel(c);
Marshaller marshaller = new CacheMarshaller210();
cr.registerComponent(marshaller, Marshaller.class);
Modified: core/trunk/src/test/java/org/jboss/cache/marshall/MethodIdPreservationTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/marshall/MethodIdPreservationTest.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/marshall/MethodIdPreservationTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -6,7 +6,7 @@
import org.jboss.cache.commands.write.PutDataMapCommand;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.factories.CommandsFactory;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import static org.testng.AssertJUnit.assertEquals;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -46,7 +46,7 @@
prepareComand = new PrepareCommand(null, list, null, true);
CacheMarshaller210 cm210 = new CacheMarshaller210();
- ComponentRegistry registry = new ComponentRegistry(new Configuration());
+ ComponentKernel registry = new ComponentKernel(new Configuration());
CommandsFactory factory = new CommandsFactory();
cm210.injectCommandsFactory(factory);
Modified: core/trunk/src/test/java/org/jboss/cache/marshall/VersionAwareMarshallerTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/marshall/VersionAwareMarshallerTest.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/marshall/VersionAwareMarshallerTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -8,7 +8,7 @@
import org.jboss.cache.Version;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.util.stream.MarshalledValueInputStream;
import static org.testng.AssertJUnit.assertEquals;
import org.testng.annotations.AfterMethod;
@@ -29,7 +29,7 @@
@BeforeMethod
public void setUp()
{
- cr = new ComponentRegistry(new Configuration());
+ cr = new ComponentKernel(new Configuration());
}
@AfterMethod
Modified: core/trunk/src/test/java/org/jboss/cache/misc/TestingUtil.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/misc/TestingUtil.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/misc/TestingUtil.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -11,10 +11,9 @@
import org.jboss.cache.CacheSPI;
import org.jboss.cache.CacheStatus;
import org.jboss.cache.Fqn;
-import org.jboss.cache.LifecycleManager;
import org.jboss.cache.commands.VisitableCommand;
import org.jboss.cache.factories.CommandsFactory;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.interceptors.InterceptorChain;
import org.jboss.cache.interceptors.base.CommandInterceptor;
import org.jboss.cache.invocation.CacheInvocationDelegate;
@@ -472,22 +471,20 @@
* @param cache cache to introspect
* @return component registry
*/
- public static ComponentRegistry extractComponentRegistry(Cache cache)
+ public static ComponentKernel extractComponentRegistry(Cache cache)
{
- LifecycleManager clm = (LifecycleManager) extractField(cache, "lifecycleManager");
- return (ComponentRegistry) extractField(clm, "componentRegistry");
+ return (ComponentKernel) extractField(cache, "componentRegistry");
}
/**
* For testing only - introspects a cache and extracts the ComponentRegistry
*
- * @param cache cache to introspect
+ * @param ci interceptor chain to introspect
* @return component registry
*/
- public static ComponentRegistry extractComponentRegistry(InterceptorChain ci)
+ public static ComponentKernel extractComponentRegistry(InterceptorChain ci)
{
- ComponentRegistry cr = (ComponentRegistry) extractField(ci, "componentRegistry");
- return cr;
+ return (ComponentKernel) extractField(ci, "componentRegistry");
}
@@ -500,7 +497,7 @@
*/
public static void replaceInterceptorChain(CacheSPI<?, ?> cache, CommandInterceptor interceptor)
{
- ComponentRegistry cr = extractComponentRegistry(cache);
+ ComponentKernel cr = extractComponentRegistry(cache);
// make sure all interceptors here are wired.
CommandInterceptor i = interceptor;
do
@@ -522,7 +519,7 @@
*/
public static CacheInvocationDelegate getInvocationDelegate(CacheSPI cache)
{
- ComponentRegistry cr = extractComponentRegistry(cache);
+ ComponentKernel cr = extractComponentRegistry(cache);
return cr.getComponent(CacheInvocationDelegate.class);
}
@@ -547,7 +544,7 @@
public static void replicateCommand(CacheSPI cache, VisitableCommand command) throws Throwable
{
- ComponentRegistry cr = extractComponentRegistry(cache);
+ ComponentKernel cr = extractComponentRegistry(cache);
InterceptorChain ic = cr.getComponent(InterceptorChain.class);
ic.invoke(command);
}
Modified: core/trunk/src/test/java/org/jboss/cache/notifications/RemoteCacheListenerTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/notifications/RemoteCacheListenerTest.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/notifications/RemoteCacheListenerTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -29,7 +29,7 @@
import org.jboss.cache.Fqn;
import org.jboss.cache.Node;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.lock.IsolationLevel;
import org.jboss.cache.misc.TestingUtil;
import org.jboss.cache.notifications.event.Event;
@@ -110,7 +110,7 @@
public void testSeparateNotifiersAndListeners()
{
assert cache1 != cache2;
- ComponentRegistry cr1, cr2;
+ ComponentKernel cr1, cr2;
cr1 = TestingUtil.extractComponentRegistry(cache1);
cr2 = TestingUtil.extractComponentRegistry(cache2);
assert cr1 != cr2;
Modified: core/trunk/src/test/java/org/jboss/cache/optimistic/NodeInterceptorGetChildrenNamesTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/optimistic/NodeInterceptorGetChildrenNamesTest.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/optimistic/NodeInterceptorGetChildrenNamesTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -2,7 +2,7 @@
import org.jboss.cache.CacheSPI;
import org.jboss.cache.Fqn;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.interceptors.OptimisticCreateIfNotExistsInterceptor;
import org.jboss.cache.interceptors.OptimisticNodeInterceptor;
import org.jboss.cache.interceptors.base.CommandInterceptor;
@@ -37,7 +37,7 @@
listener = new TestListener();
cache = createCacheWithListener(listener);
- ComponentRegistry cr = TestingUtil.extractComponentRegistry(cache);
+ ComponentKernel cr = TestingUtil.extractComponentRegistry(cache);
CommandInterceptor interceptor = new OptimisticCreateIfNotExistsInterceptor();
cr.registerComponent(interceptor, OptimisticCreateIfNotExistsInterceptor.class);
Modified: core/trunk/src/test/java/org/jboss/cache/statetransfer/FailedStateTransferTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/statetransfer/FailedStateTransferTest.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/statetransfer/FailedStateTransferTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -27,7 +27,7 @@
import org.jboss.cache.DefaultCacheFactory;
import org.jboss.cache.Version;
import org.jboss.cache.config.Configuration.CacheMode;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.factories.UnitTestCacheConfigurationFactory;
import org.jboss.cache.lock.TimeoutException;
import org.jboss.cache.misc.TestingUtil;
@@ -60,9 +60,9 @@
caches.put("secretive", cache);
// inject our own message listener and re-wire deps
- ComponentRegistry cr = TestingUtil.extractComponentRegistry(cache);
+ ComponentKernel cr = TestingUtil.extractComponentRegistry(cache);
// cr.unregisterComponent(ChannelMessageListener.class);
- cr.registerComponent(ChannelMessageListener.class.getName(), new SecretiveStateCacheMessageListener(), ChannelMessageListener.class);
+ cr.registerComponent(new SecretiveStateCacheMessageListener(), ChannelMessageListener.class);
// cr.updateDependencies();
cache.start();
@@ -81,7 +81,7 @@
// inject our own message listener and re-wire deps
cr = TestingUtil.extractComponentRegistry(recipient);
//cr.unregisterComponent(ChannelMessageListener.class);
- cr.registerComponent(ChannelMessageListener.class.getName(), new SecretiveStateCacheMessageListener(), ChannelMessageListener.class);
+ cr.registerComponent(new SecretiveStateCacheMessageListener(), ChannelMessageListener.class);
//cr.updateDependencies();
try
Modified: core/trunk/src/test/java/org/jboss/cache/transaction/PrepareCommitContentionTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/transaction/PrepareCommitContentionTest.java 2008-05-07 11:23:35 UTC (rev 5802)
+++ core/trunk/src/test/java/org/jboss/cache/transaction/PrepareCommitContentionTest.java 2008-05-08 08:50:28 UTC (rev 5803)
@@ -9,7 +9,7 @@
import org.jboss.cache.commands.tx.CommitCommand;
import org.jboss.cache.commands.tx.PrepareCommand;
import static org.jboss.cache.config.Configuration.CacheMode.REPL_SYNC;
-import org.jboss.cache.factories.ComponentRegistry;
+import org.jboss.cache.factories.ComponentKernel;
import org.jboss.cache.factories.UnitTestCacheConfigurationFactory;
import org.jboss.cache.misc.TestingUtil;
import org.jgroups.Address;
@@ -58,7 +58,7 @@
public void testOOBFlag() throws Exception
{
DelegatingRPCManager delegatingRPCManager = new DelegatingRPCManager();
- ComponentRegistry cr = TestingUtil.extractComponentRegistry(c1);
+ ComponentKernel cr = TestingUtil.extractComponentRegistry(c1);
RPCManager origRpcManager = cr.getComponent(RPCManager.class);
delegatingRPCManager.delegate = origRpcManager;
cr.registerComponent(delegatingRPCManager, RPCManager.class);
16 years, 7 months
JBoss Cache SVN: r5802 - benchmarks/benchmark-fwk/trunk/cache-products/ehcache-1.4.1/src/org/cachebench/cachewrappers.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-05-07 07:23:35 -0400 (Wed, 07 May 2008)
New Revision: 5802
Modified:
benchmarks/benchmark-fwk/trunk/cache-products/ehcache-1.4.1/src/org/cachebench/cachewrappers/EHCacheWrapper.java
Log:
EHCache to deal with serializable objects
Modified: benchmarks/benchmark-fwk/trunk/cache-products/ehcache-1.4.1/src/org/cachebench/cachewrappers/EHCacheWrapper.java
===================================================================
--- benchmarks/benchmark-fwk/trunk/cache-products/ehcache-1.4.1/src/org/cachebench/cachewrappers/EHCacheWrapper.java 2008-05-07 11:19:43 UTC (rev 5801)
+++ benchmarks/benchmark-fwk/trunk/cache-products/ehcache-1.4.1/src/org/cachebench/cachewrappers/EHCacheWrapper.java 2008-05-07 11:23:35 UTC (rev 5802)
@@ -7,7 +7,7 @@
import net.sf.ehcache.config.ConfigurationFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.cachebench.SerializableCacheWrapper;
+import org.cachebench.CacheWrapper;
import java.io.Serializable;
import java.net.URL;
@@ -17,13 +17,13 @@
/**
* An implementation of SerializableCacheWrapper that uses EHCache as an underlying implementation.
- *
+ * <p/>
* Pass in a -Dbind.address=IP_ADDRESS
*
* @author Manik Surtani (manik(a)surtani.org)
* @version $Id: EHCacheWrapper.java,v 1.6 2007/05/21 16:17:56 msurtani Exp $
*/
-public class EHCacheWrapper implements SerializableCacheWrapper
+public class EHCacheWrapper implements CacheWrapper
{
private CacheManager manager;
private Ehcache cache;
@@ -43,7 +43,7 @@
// frig the manager to use a bind address as per sys props
String bindAddress = System.getProperty("bind.address");
- if (bindAddress!= null)
+ if (bindAddress != null)
{
String props = c.getCacheManagerPeerListenerFactoryConfiguration().getProperties();
props = injectBindAddress(props, bindAddress);
@@ -51,7 +51,7 @@
}
manager = new CacheManager(c);
-
+
logger.debug("Finish Initializing the cache");
}
@@ -136,7 +136,7 @@
*/
public void put(Object key, Object value) throws Exception
{
- throw new Exception("Put: Does not deal with non-Serializables, should not be called.");
+ putSerializable((Serializable) key, (Serializable) value);
}
/* (non-Javadoc)
@@ -144,7 +144,7 @@
*/
public Object get(Object key) throws Exception
{
- throw new Exception("Get: Does not deal with non-Serializables, should not be called.");
+ return getSerializable((Serializable) key);
}
public int getNumMembers()
16 years, 7 months
JBoss Cache SVN: r5801 - benchmarks/benchmark-fwk/trunk/cache-products/ehcache-1.4.1/lib.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-05-07 07:19:43 -0400 (Wed, 07 May 2008)
New Revision: 5801
Added:
benchmarks/benchmark-fwk/trunk/cache-products/ehcache-1.4.1/lib/backport-util-concurrent-3.0.jar
Log:
Added: benchmarks/benchmark-fwk/trunk/cache-products/ehcache-1.4.1/lib/backport-util-concurrent-3.0.jar
===================================================================
(Binary files differ)
Property changes on: benchmarks/benchmark-fwk/trunk/cache-products/ehcache-1.4.1/lib/backport-util-concurrent-3.0.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
16 years, 7 months