JBoss Cache SVN: r7700 - in core/branches/flat/src/test/java/org/horizon: test and 1 other directory.
by jbosscache-commits@lists.jboss.org
Author: mircea.markus
Date: 2009-02-17 10:24:59 -0500 (Tue, 17 Feb 2009)
New Revision: 7700
Added:
core/branches/flat/src/test/java/org/horizon/test/ViewChangeListener.java
Modified:
core/branches/flat/src/test/java/org/horizon/loader/decorators/SingletonStoreTest.java
Log:
make tests compilable
Modified: core/branches/flat/src/test/java/org/horizon/loader/decorators/SingletonStoreTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/loader/decorators/SingletonStoreTest.java 2009-02-17 14:38:40 UTC (rev 7699)
+++ core/branches/flat/src/test/java/org/horizon/loader/decorators/SingletonStoreTest.java 2009-02-17 15:24:59 UTC (rev 7700)
@@ -11,7 +11,7 @@
import org.horizon.loader.dummy.DummyInMemoryCacheLoader;
import org.horizon.manager.CacheManager;
import org.horizon.test.TestingUtil;
-import org.horizon.util.internals.ViewChangeListener;
+import org.horizon.test.ViewChangeListener;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.fail;
import org.testng.annotations.AfterMethod;
Added: core/branches/flat/src/test/java/org/horizon/test/ViewChangeListener.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/test/ViewChangeListener.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/test/ViewChangeListener.java 2009-02-17 15:24:59 UTC (rev 7700)
@@ -0,0 +1,45 @@
+package org.horizon.test;
+
+import org.horizon.Cache;
+import org.horizon.manager.CacheManager;
+import org.horizon.notifications.Listener;
+import org.horizon.notifications.cachemanagerlistener.annotation.ViewChanged;
+import org.horizon.notifications.cachemanagerlistener.event.ViewChangedEvent;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Listens for view changes. Note that you do NOT have to register this listener; it does so automatically when
+ * constructed.
+ */
+@Listener
+public class ViewChangeListener {
+ CacheManager cm;
+ final CountDownLatch latch = new CountDownLatch(1);
+
+ public ViewChangeListener(Cache c) {
+ this(c.getCacheManager());
+ }
+
+ public ViewChangeListener(CacheManager cm) {
+ this.cm = cm;
+ cm.addListener(this);
+ }
+
+ @ViewChanged
+ public void onViewChange(ViewChangedEvent e) {
+ latch.countDown();
+ }
+
+ /**
+ * Blocks for a certain amount of time until a view change is received. Note that this class will start listening
+ * for the view change the moment it is constructed.
+ *
+ * @param time time to wait
+ * @param unit time unit
+ */
+ public void waitForViewChange(long time, TimeUnit unit) throws InterruptedException {
+ if (!latch.await(time, unit)) assert false : "View change not seen after " + time + " " + unit;
+ }
+}
Property changes on: core/branches/flat/src/test/java/org/horizon/test/ViewChangeListener.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
15 years, 10 months
JBoss Cache SVN: r7699 - in core/branches/flat: src/main/java/org/horizon and 42 other directories.
by jbosscache-commits@lists.jboss.org
Author: mircea.markus
Date: 2009-02-17 09:38:40 -0500 (Tue, 17 Feb 2009)
New Revision: 7699
Added:
core/branches/flat/src/main/java/org/horizon/remoting/ReplicationQueue.java
core/branches/flat/src/test/java/org/horizon/test/
core/branches/flat/src/test/java/org/horizon/test/AbstractCacheTest.java
core/branches/flat/src/test/java/org/horizon/test/JGroupsConfigBuilder.java
core/branches/flat/src/test/java/org/horizon/test/MultipleCacheManagersTest.java
core/branches/flat/src/test/java/org/horizon/test/ReplListener.java
core/branches/flat/src/test/java/org/horizon/test/SingleCacheManagerTest.java
core/branches/flat/src/test/java/org/horizon/test/TestNameVerifier.java
core/branches/flat/src/test/java/org/horizon/test/TestingUtil.java
core/branches/flat/src/test/java/org/horizon/test/testng/
core/branches/flat/src/test/java/org/horizon/test/testng/SuiteResourcesAndLogTest.java
core/branches/flat/src/test/java/org/horizon/test/testng/UnitTestTestNGListener.java
core/branches/flat/src/test/resources/stacks/
core/branches/flat/src/test/resources/stacks/tcp.xml
core/branches/flat/src/test/resources/stacks/udp.xml
Removed:
core/branches/flat/src/main/java/org/horizon/cluster/
core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java
core/branches/flat/src/test/java/org/horizon/BaseClusteredTest.java
core/branches/flat/src/test/java/org/horizon/UnitTestCacheFactory.java
core/branches/flat/src/test/java/org/horizon/UnitTestCacheManager.java
core/branches/flat/src/test/java/org/horizon/util/UnitTestTestNGListener.java
core/branches/flat/src/test/java/org/horizon/util/internals/
Modified:
core/branches/flat/pom.xml
core/branches/flat/src/main/java/org/horizon/config/GlobalConfiguration.java
core/branches/flat/src/main/java/org/horizon/factories/KnownComponentNames.java
core/branches/flat/src/main/java/org/horizon/factories/NamedExecutorsFactory.java
core/branches/flat/src/main/java/org/horizon/factories/ReplicationQueueFactory.java
core/branches/flat/src/main/java/org/horizon/interceptors/base/BaseRpcInterceptor.java
core/branches/flat/src/main/resources/config-samples/all.xml
core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java
core/branches/flat/src/test/java/org/horizon/api/CacheClusterJoinTest.java
core/branches/flat/src/test/java/org/horizon/api/MixedModeTest.java
core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTMTest.java
core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTMTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/LockAssert.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/CacheAPIMVCCTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/ReadCommittedLockTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/CacheAPIMVCCTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/RepeatableReadLockTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeLockSupport.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java
core/branches/flat/src/test/java/org/horizon/api/tree/TreeStructureHashCodeTest.java
core/branches/flat/src/test/java/org/horizon/atomic/APITest.java
core/branches/flat/src/test/java/org/horizon/atomic/AtomicHashMapTest.java
core/branches/flat/src/test/java/org/horizon/atomic/ClusteredAPITest.java
core/branches/flat/src/test/java/org/horizon/config/parsing/ConfigurationParserTest.java
core/branches/flat/src/test/java/org/horizon/config/parsing/GlobalConfigurationParserTest.java
core/branches/flat/src/test/java/org/horizon/config/parsing/XmlFileParsingTest.java
core/branches/flat/src/test/java/org/horizon/container/DataContainerTest.java
core/branches/flat/src/test/java/org/horizon/eviction/EvictionFunctionalTest.java
core/branches/flat/src/test/java/org/horizon/eviction/EvictionManagerTest.java
core/branches/flat/src/test/java/org/horizon/eviction/algorithms/fifo/FifoAlgorithmTest.java
core/branches/flat/src/test/java/org/horizon/eviction/algorithms/fifo/FifoQueueTest.java
core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lfu/LfuAlgorithmTest.java
core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lfu/LfuQueueTest.java
core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lru/LruAlgorithmTest.java
core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lru/LruQueueTest.java
core/branches/flat/src/test/java/org/horizon/eviction/algorithms/mru/MruAlgorithmTest.java
core/branches/flat/src/test/java/org/horizon/eviction/algorithms/mru/MruQueueTest.java
core/branches/flat/src/test/java/org/horizon/expiry/ExpiryTest.java
core/branches/flat/src/test/java/org/horizon/expiry/ReplicatedExpiryTest.java
core/branches/flat/src/test/java/org/horizon/factories/scopes/ScopeDetectorTest.java
core/branches/flat/src/test/java/org/horizon/interceptors/MarshalledValueInterceptorTest.java
core/branches/flat/src/test/java/org/horizon/invalidation/AsyncInvalidationTest.java
core/branches/flat/src/test/java/org/horizon/invalidation/BaseInvalidationTest.java
core/branches/flat/src/test/java/org/horizon/invalidation/SyncInvalidationTest.java
core/branches/flat/src/test/java/org/horizon/loader/BaseCacheLoaderTest.java
core/branches/flat/src/test/java/org/horizon/loader/CacheLoaderFunctionalTest.java
core/branches/flat/src/test/java/org/horizon/loader/decorators/AsyncTest.java
core/branches/flat/src/test/java/org/horizon/loader/decorators/ReadOnlyCacheStoreTest.java
core/branches/flat/src/test/java/org/horizon/loader/decorators/SingletonStoreTest.java
core/branches/flat/src/test/java/org/horizon/loader/dummy/DummyInMemoryCacheLoaderTest.java
core/branches/flat/src/test/java/org/horizon/lock/LockContainerHashingTest.java
core/branches/flat/src/test/java/org/horizon/manager/CacheManagerComponentRegistryTest.java
core/branches/flat/src/test/java/org/horizon/manager/CacheManagerTest.java
core/branches/flat/src/test/java/org/horizon/manager/CacheManagerXmlConfigurationTest.java
core/branches/flat/src/test/java/org/horizon/marshall/MarshalledValueTest.java
core/branches/flat/src/test/java/org/horizon/notifications/AsyncNotificationTest.java
core/branches/flat/src/test/java/org/horizon/notifications/CacheListenerCacheLoaderTest.java
core/branches/flat/src/test/java/org/horizon/notifications/CacheListenerPassivationTest.java
core/branches/flat/src/test/java/org/horizon/notifications/CacheListenerRemovalTest.java
core/branches/flat/src/test/java/org/horizon/notifications/ConcurrentNotificationTest.java
core/branches/flat/src/test/java/org/horizon/notifications/cachelistener/CacheNotifierImplTest.java
core/branches/flat/src/test/java/org/horizon/notifications/cachelistener/CacheNotifierTest.java
core/branches/flat/src/test/java/org/horizon/notifications/cachelistener/ListenerRegistrationTest.java
core/branches/flat/src/test/java/org/horizon/notifications/cachemanagerlistener/CacheManagerNotifierImplTest.java
core/branches/flat/src/test/java/org/horizon/notifications/cachemanagerlistener/CacheManagerNotifierTest.java
core/branches/flat/src/test/java/org/horizon/profiling/AbstractProfileTest.java
core/branches/flat/src/test/java/org/horizon/profiling/MemConsumptionTest.java
core/branches/flat/src/test/java/org/horizon/profiling/ProfileTest.java
core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java
core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java
core/branches/flat/src/test/java/org/horizon/replication/AsyncReplicatedAPITest.java
core/branches/flat/src/test/java/org/horizon/replication/BaseReplicatedAPITest.java
core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java
core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java
core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java
core/branches/flat/src/test/java/org/horizon/replication/SyncReplicatedAPITest.java
core/branches/flat/src/test/java/org/horizon/tx/LocalModeTxTest.java
core/branches/flat/src/test/java/org/horizon/tx/MarkAsRollbackTest.java
core/branches/flat/src/test/java/org/horizon/util/BidirectionalLinkedHashMapTest.java
core/branches/flat/src/test/java/org/horizon/util/VisitableLinkedHashSetTest.java
Log:
added support for parallel test execution
Modified: core/branches/flat/pom.xml
===================================================================
--- core/branches/flat/pom.xml 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/pom.xml 2009-02-17 14:38:40 UTC (rev 7699)
@@ -148,16 +148,30 @@
<!--<version>2.4.3-JBOSS</version>-->
<version>2.4.3</version>
<configuration>
- <!--<parallel>methods</parallel>-->
- <!--<threadCount>1</threadCount>-->
+ <parallel>tests</parallel>
+ <threadCount>10</threadCount>
<forkMode>none</forkMode>
- <!--<trimStackTrace>false</trimStackTrace>-->
- <!--<properties>-->
- <!--<property>-->
- <!--<name>listener</name>-->
- <!--<value>org.horizon.util.UnitTestTestNGListener</value>-->
- <!--</property>-->
- <!--</properties>-->
+ <systemProperties>
+ <property>
+ <name>jgroups.stack</name>
+ <value>${protocol.stack}</value>
+ </property>
+ <property>
+ <name>bind.address</name>
+ <value>127.0.0.1</value>
+ </property>
+ <property>
+ <name>java.net.preferIPv4Stack</name>
+ <value>true</value>
+ </property>
+ </systemProperties>
+ <trimStackTrace>false</trimStackTrace>
+ <properties>
+ <property>
+ <name>listener</name>
+ <value>org.horizon.test.testng.UnitTestTestNGListener</value>
+ </property>
+ </properties>
</configuration>
</plugin>
<plugin>
@@ -410,8 +424,12 @@
<profile>
<id>test-hudson</id>
+ <activation>
+ <activeByDefault>true</activeByDefault>
+ </activation>
<properties>
<defaultTestGroup>functional,unit</defaultTestGroup>
+ <protocol.stack>tcp</protocol.stack>
</properties>
</profile>
@@ -419,6 +437,7 @@
<id>test-functional</id>
<properties>
<defaultTestGroup>functional</defaultTestGroup>
+ <protocol.stack>tcp</protocol.stack>
</properties>
</profile>
Modified: core/branches/flat/src/main/java/org/horizon/config/GlobalConfiguration.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/GlobalConfiguration.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/main/java/org/horizon/config/GlobalConfiguration.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -350,7 +350,7 @@
/**
* Helper method that gets you a default constructed GlobalConfiguration, preconfigured to use the default clustering
- * stack
+ * stack.
*
* @return a new global configuration
*/
@@ -372,6 +372,4 @@
gc.setTransportProperties((Properties) null);
return gc;
}
-
-
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/KnownComponentNames.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/KnownComponentNames.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/main/java/org/horizon/factories/KnownComponentNames.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -11,4 +11,5 @@
public static final String ASYNC_SERIALIZATION_EXECUTOR = "org.horizon.executors.serialization";
public static final String ASYNC_NOTIFICATION_EXECUTOR = "org.horizon.executors.notification";
public static final String EVICTION_SCHEDULED_EXECUTOR = "org.horizon.executors.eviction";
+ public static final String ASYNC_REPLICATION_QUEUE_EXECUTOR = "org.horizon.executors.replicationQueue";
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/NamedExecutorsFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/NamedExecutorsFactory.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/main/java/org/horizon/factories/NamedExecutorsFactory.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -32,6 +32,9 @@
} else if (componentName.equals(KnownComponentNames.EVICTION_SCHEDULED_EXECUTOR)) {
return (T) buildAndConfigureScheduledExecutorService(globalConfiguration.getEvictionScheduledExecutorFactoryClass(),
globalConfiguration.getEvictionScheduledExecutorProperties());
+ } else if (componentName.equals(KnownComponentNames.ASYNC_REPLICATION_QUEUE_EXECUTOR)) {
+ return (T) buildAndConfigureScheduledExecutorService(globalConfiguration.getReplicationQueueScheduledExecutorFactoryClass(),
+ globalConfiguration.getReplicationQueueScheduledExecutorProperties());
} else {
throw new ConfigurationException("Unknown named executor " + componentName);
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/ReplicationQueueFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/ReplicationQueueFactory.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/main/java/org/horizon/factories/ReplicationQueueFactory.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -21,12 +21,11 @@
*/
package org.horizon.factories;
-import org.horizon.cluster.ReplicationQueue;
-import org.horizon.config.Configuration;
import org.horizon.factories.annotations.DefaultFactoryFor;
+import org.horizon.remoting.ReplicationQueue;
/**
- * RPCManager factory
+ * Factory for ReplicationQueue.
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
* @since 1.0
@@ -35,8 +34,7 @@
public class ReplicationQueueFactory extends EmptyConstructorNamedCacheFactory implements AutoInstantiableFactory {
@Override
public <T> T construct(Class<T> componentType) {
- if ((configuration.getCacheMode() == Configuration.CacheMode.REPL_ASYNC || configuration.getCacheMode() == Configuration.CacheMode.INVALIDATION_ASYNC)
- && configuration.isUseReplQueue()) {
+ if ((!configuration.getCacheMode().isSynchronous()) && configuration.isUseReplQueue()) {
return super.construct(componentType);
} else {
return null;
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/base/BaseRpcInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/base/BaseRpcInterceptor.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/base/BaseRpcInterceptor.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -21,7 +21,7 @@
*/
package org.horizon.interceptors.base;
-import org.horizon.cluster.ReplicationQueue;
+import org.horizon.remoting.ReplicationQueue;
import org.horizon.commands.CommandsFactory;
import org.horizon.commands.RPCCommand;
import org.horizon.commands.ReplicableCommand;
Copied: core/branches/flat/src/main/java/org/horizon/remoting/ReplicationQueue.java (from rev 7681, core/branches/flat/src/main/java/org/horizon/cluster/ReplicationQueue.java)
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/ReplicationQueue.java (rev 0)
+++ core/branches/flat/src/main/java/org/horizon/remoting/ReplicationQueue.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -0,0 +1,153 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.horizon.remoting;
+
+import org.horizon.commands.CommandsFactory;
+import org.horizon.commands.RPCCommand;
+import org.horizon.commands.ReplicableCommand;
+import org.horizon.commands.remote.ReplicateCommand;
+import org.horizon.config.Configuration;
+import org.horizon.factories.KnownComponentNames;
+import org.horizon.factories.annotations.ComponentName;
+import org.horizon.factories.annotations.Inject;
+import org.horizon.factories.annotations.Start;
+import org.horizon.factories.annotations.Stop;
+import org.horizon.logging.Log;
+import org.horizon.logging.LogFactory;
+
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Periodically (or when certain size is exceeded) takes elements and replicates them.
+ *
+ * @author <a href="mailto:bela@jboss.org">Bela Ban</a>
+ * @author Mircea.Markus(a)jboss.com
+ * @since 1.0
+ */
+public class ReplicationQueue {
+ private static final Log log = LogFactory.getLog(ReplicationQueue.class);
+
+ /**
+ * Max elements before we flush
+ */
+ private long maxElements = 500;
+
+ /**
+ * Holds the replication jobs.
+ */
+ final List<RPCCommand> elements = new LinkedList<RPCCommand>();
+
+ /**
+ * For periodical replication
+ */
+ private ScheduledExecutorService scheduledExecutor = null;
+ private RPCManager rpcManager;
+ private Configuration configuration;
+ private boolean enabled;
+ private CommandsFactory commandsFactory;
+ private final AtomicInteger counter = new AtomicInteger(0);
+
+ public boolean isEnabled() {
+ return enabled;
+ }
+
+ @Inject
+ private void injectDependencies((a)ComponentName(KnownComponentNames.ASYNC_REPLICATION_QUEUE_EXECUTOR) ScheduledExecutorService executor,
+ RPCManager rpcManager, Configuration configuration, CommandsFactory commandsFactory) {
+ this.rpcManager = rpcManager;
+ this.configuration = configuration;
+ this.commandsFactory = commandsFactory;
+ this.scheduledExecutor = executor;
+ }
+
+ /**
+ * Starts the asynchronous flush queue.
+ */
+ @Start
+ public synchronized void start() {
+ long interval = configuration.getReplQueueInterval();
+ this.maxElements = configuration.getReplQueueMaxElements();
+ // check again
+ enabled = configuration.isUseReplQueue();
+ if (enabled && interval > 0) {
+ scheduledExecutor.scheduleWithFixedDelay(new Runnable() {
+ public void run() {
+ flush();
+ }
+ }, 500l, interval, TimeUnit.MILLISECONDS);
+ }
+ }
+
+ /**
+ * Stops the asynchronous flush queue.
+ */
+ @Stop
+ public synchronized void stop() {
+ if (scheduledExecutor != null) {
+ scheduledExecutor.shutdownNow();
+ }
+ scheduledExecutor = null;
+ }
+
+
+ /**
+ * Adds a new method call.
+ */
+ public void add(RPCCommand job) {
+ if (job == null)
+ throw new NullPointerException("job is null");
+ synchronized (elements) {
+ elements.add(job);
+ if (elements.size() >= maxElements)
+ flush();
+ }
+ }
+
+ /**
+ * Flushes existing method calls.
+ */
+ public void flush() {
+ List<ReplicableCommand> toReplicate;
+ synchronized (elements) {
+ if (log.isTraceEnabled())
+ log.trace("flush(): flushing repl queue (num elements=" + elements.size() + ")");
+ toReplicate = new ArrayList<ReplicableCommand>(elements);
+ elements.clear();
+ }
+
+ if (toReplicate.size() > 0) {
+ try {
+ ReplicateCommand replicateCommand = commandsFactory.buildReplicateCommand(toReplicate);
+ // send to all live nodes in the cluster
+ rpcManager.invokeRemotely(null, replicateCommand, ResponseMode.ASYNCHRONOUS, configuration.getSyncReplTimeout());
+ }
+ catch (Throwable t) {
+ log.error("failed replicating " + toReplicate.size() + " elements in replication queue", t);
+ }
+ }
+ }
+}
\ No newline at end of file
Property changes on: core/branches/flat/src/main/java/org/horizon/remoting/ReplicationQueue.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Deleted: core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,605 +0,0 @@
-/*
- * JBoss, the OpenSource J2EE webOS
- *
- * Distributable under LGPL license.
- * See terms of license at gnu.org.
- */
-
-package org.horizon.util;
-
-import org.horizon.AdvancedCache;
-import org.horizon.Cache;
-import org.horizon.CacheDelegate;
-import org.horizon.commands.CommandsFactory;
-import org.horizon.commands.VisitableCommand;
-import org.horizon.factories.ComponentRegistry;
-import org.horizon.factories.GlobalComponentRegistry;
-import org.horizon.interceptors.InterceptorChain;
-import org.horizon.interceptors.base.CommandInterceptor;
-import org.horizon.lifecycle.ComponentStatus;
-import org.horizon.lock.LockManager;
-import org.horizon.manager.CacheManager;
-import org.horizon.remoting.transport.Address;
-import org.horizon.tree.TreeCache;
-
-import javax.transaction.TransactionManager;
-import java.io.File;
-import java.lang.reflect.Field;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Random;
-
-/**
- * Utilities for unit testing JBossCache.
- *
- * @author <a href="mailto://brian.stansberry@jboss.com">Brian Stansberry</a>
- * @since 1.0
- */
-public class TestingUtil {
- private static Random random = new Random();
-
- /**
- * Extracts the value of a field in a given target instance using reflection, able to extract private fields as
- * well.
- *
- * @param target object to extract field from
- * @param fieldName name of field to extract
- * @return field value
- */
- public static Object extractField(Object target, String fieldName) {
- return extractField(target.getClass(), target, fieldName);
- }
-
- public static void replaceField(Object newValue, String fieldName, Object owner, Class baseType) {
- Field field;
- try {
- field = baseType.getDeclaredField(fieldName);
- field.setAccessible(true);
- field.set(owner, newValue);
- }
- catch (Exception e) {
- throw new RuntimeException(e);//just to simplify exception handeling
- }
- }
-
-
- public static Object extractField(Class type, Object target, String fieldName) {
- Field field;
- try {
- field = type.getDeclaredField(fieldName);
- field.setAccessible(true);
- return field.get(target);
- }
- catch (Exception e) {
- if (type.equals(Object.class)) {
- e.printStackTrace();
- return null;
- } else {
- // try with superclass!!
- return extractField(type.getSuperclass(), target, fieldName);
- }
- }
- }
-
- public static <T extends CommandInterceptor> T findInterceptor(Cache<?, ?> cache, Class<T> interceptorToFind) {
- for (CommandInterceptor i : cache.getAdvancedCache().getInterceptorChain()) {
- if (interceptorToFind.isInstance(i)) return interceptorToFind.cast(i);
- }
- return null;
- }
-
- /**
- * Loops, continually calling {@link #areCacheViewsComplete(Cache[])} until it either returns true or
- * <code>timeout</code> ms have elapsed.
- *
- * @param caches caches which must all have consistent views
- * @param timeout max number of ms to loop
- * @throws RuntimeException if <code>timeout</code> ms have elapse without all caches having the same number of
- * members.
- */
- public static void blockUntilViewsReceived(Cache[] caches, long timeout) {
- long failTime = System.currentTimeMillis() + timeout;
-
- while (System.currentTimeMillis() < failTime) {
- sleepThread(100);
- if (areCacheViewsComplete(caches)) {
- return;
- }
- }
-
- throw new RuntimeException("timed out before caches had complete views");
- }
-
- /**
- * Version of blockUntilViewsReceived that uses varargs
- */
- public static void blockUntilViewsReceived(long timeout, Cache... caches) {
- blockUntilViewsReceived(caches, timeout);
- }
-
- /**
- * Version of blockUntilViewsReceived that uses varargsa and cache managers
- */
- public static void blockUntilViewsReceived(long timeout, CacheManager... cacheManagers) {
- blockUntilViewsReceived(timeout, true, cacheManagers);
- }
-
- public static void blockUntilViewsReceived(long timeout, boolean barfIfTooManyMembers, CacheManager... cacheManagers) {
- long failTime = System.currentTimeMillis() + timeout;
-
- while (System.currentTimeMillis() < failTime) {
- sleepThread(100);
- if (areCacheViewsComplete(barfIfTooManyMembers, cacheManagers)) {
- return;
- }
- }
-
- throw new RuntimeException("timed out before caches had complete views");
- }
-
- /**
- * Loops, continually calling {@link #areCacheViewsComplete(CacheSPI[])} until it either returns true or
- * <code>timeout</code> ms have elapsed.
- *
- * @param caches caches which must all have consistent views
- * @param timeout max number of ms to loop
- * @throws RuntimeException if <code>timeout</code> ms have elapse without all caches having the same number of
- * members.
- */
-// public static void blockUntilViewsReceived(Cache[] caches, long timeout) {
-// long failTime = System.currentTimeMillis() + timeout;
-//
-// while (System.currentTimeMillis() < failTime) {
-// sleepThread(100);
-// if (areCacheViewsComplete(caches)) {
-// return;
-// }
-// }
-//
-// throw new RuntimeException("timed out before caches had complete views");
-// }
-
-
- /**
- * An overloaded version of {@link #blockUntilViewsReceived(long,Cache[])} that allows for 'shrinking' clusters.
- * I.e., the usual method barfs if there are more members than expected. This one takes a param
- * (barfIfTooManyMembers) which, if false, will NOT barf but will wait until the cluster 'shrinks' to the desired
- * size. Useful if in tests, you kill a member and want to wait until this fact is known across the cluster.
- *
- * @param timeout
- * @param barfIfTooManyMembers
- * @param caches
- */
- public static void blockUntilViewsReceived(long timeout, boolean barfIfTooManyMembers, Cache... caches) {
- long failTime = System.currentTimeMillis() + timeout;
-
- while (System.currentTimeMillis() < failTime) {
- sleepThread(100);
- if (areCacheViewsComplete(caches, barfIfTooManyMembers)) {
- return;
- }
- }
-
- throw new RuntimeException("timed out before caches had complete views");
- }
-
- /**
- * Loops, continually calling {@link #areCacheViewsComplete(Cache[])} until it either returns true or
- * <code>timeout</code> ms have elapsed.
- *
- * @param groupSize number of caches expected in the group
- * @param timeout max number of ms to loop
- * @throws RuntimeException if <code>timeout</code> ms have elapse without all caches having the same number of
- * members.
- */
- public static void blockUntilViewReceived(Cache cache, int groupSize, long timeout) {
- blockUntilViewReceived(cache, groupSize, timeout, true);
- }
-
- public static void blockUntilViewReceived(Cache cache, int groupSize, long timeout, boolean barfIfTooManyMembersInView) {
- long failTime = System.currentTimeMillis() + timeout;
-
- while (System.currentTimeMillis() < failTime) {
- sleepThread(100);
- if (isCacheViewComplete(cache.getCacheManager().getMembers(), cache.getCacheManager().getAddress(), groupSize, barfIfTooManyMembersInView)) {
- return;
- }
- }
-
- throw new RuntimeException("timed out before caches had complete views");
- }
-
- /**
- * Checks each cache to see if the number of elements in the array returned by {@link CacheManager#getMembers()}
- * matches the size of the <code>caches</code> parameter.
- *
- * @param caches caches that should form a View
- * @return <code>true</code> if all caches have <code>caches.length</code> members; false otherwise
- * @throws IllegalStateException if any of the caches have MORE view members than caches.length
- */
- public static boolean areCacheViewsComplete(Cache[] caches) {
- return areCacheViewsComplete(caches, true);
- }
-
- public static boolean areCacheViewsComplete(Cache[] caches, boolean barfIfTooManyMembers) {
- int memberCount = caches.length;
-
- for (int i = 0; i < memberCount; i++) {
- if (!isCacheViewComplete(caches[i].getCacheManager().getMembers(), caches[i].getCacheManager().getAddress(), memberCount, barfIfTooManyMembers)) {
- return false;
- }
- }
-
- return true;
- }
-
- public static boolean areCacheViewsComplete(boolean barfIfTooManyMembers, CacheManager... cacheManagers) {
- if (cacheManagers == null) throw new NullPointerException("Cache Manager array is null");
- int memberCount = cacheManagers.length;
-
- for (int i = 0; i < memberCount; i++) {
- if (!isCacheViewComplete(cacheManagers[i].getMembers(), cacheManagers[i].getAddress(), memberCount, barfIfTooManyMembers)) {
- return false;
- }
- }
-
- return true;
- }
-
-// /**
-// * @param cache
-// * @param memberCount
-// */
-// public static boolean isCacheViewComplete(Cache cache, int memberCount) {
-// List members = cache.getCacheManager().getMembers();
-// if (members == null || memberCount > members.size()) {
-// return false;
-// } else if (memberCount < members.size()) {
-// // This is an exceptional condition
-// StringBuilder sb = new StringBuilder("Cache at address ");
-// sb.append(cache.getCacheManager().getAddress());
-// sb.append(" had ");
-// sb.append(members.size());
-// sb.append(" members; expecting ");
-// sb.append(memberCount);
-// sb.append(". Members were (");
-// for (int j = 0; j < members.size(); j++) {
-// if (j > 0) {
-// sb.append(", ");
-// }
-// sb.append(members.get(j));
-// }
-// sb.append(')');
-//
-// throw new IllegalStateException(sb.toString());
-// }
-//
-// return true;
-// }
-
- /**
- * @param c
- * @param memberCount
- */
- public static boolean isCacheViewComplete(Cache c, int memberCount) {
- return isCacheViewComplete(c.getCacheManager().getMembers(), c.getCacheManager().getAddress(), memberCount, true);
- }
-
- public static boolean isCacheViewComplete(List members, Address address, int memberCount, boolean barfIfTooManyMembers) {
- if (members == null || memberCount > members.size()) {
- return false;
- } else if (memberCount < members.size()) {
- if (barfIfTooManyMembers) {
- // This is an exceptional condition
- StringBuilder sb = new StringBuilder("Cache at address ");
- sb.append(address);
- sb.append(" had ");
- sb.append(members.size());
- sb.append(" members; expecting ");
- sb.append(memberCount);
- sb.append(". Members were (");
- for (int j = 0; j < members.size(); j++) {
- if (j > 0) {
- sb.append(", ");
- }
- sb.append(members.get(j));
- }
- sb.append(')');
-
- throw new IllegalStateException(sb.toString());
- } else return false;
- }
-
- return true;
- }
-
-
- /**
- * Puts the current thread to sleep for the desired number of ms, suppressing any exceptions.
- *
- * @param sleeptime number of ms to sleep
- */
- public static void sleepThread(long sleeptime) {
- try {
- Thread.sleep(sleeptime);
- }
- catch (InterruptedException ie) {
- }
- }
-
- public static void sleepRandom(int maxTime) {
- sleepThread(random.nextInt(maxTime));
- }
-
- public static void recursiveFileRemove(String directoryName) {
- File file = new File(directoryName);
- recursiveFileRemove(file);
- }
-
- public static void recursiveFileRemove(File file) {
- if (file.exists()) {
- System.out.println("Deleting file " + file);
- recursivedelete(file);
- }
- }
-
- private static void recursivedelete(File f) {
- if (f.isDirectory()) {
- File[] files = f.listFiles();
- for (File file : files) {
- recursivedelete(file);
- }
- }
- //System.out.println("File " + f.toURI() + " deleted = " + f.delete());
- f.delete();
- }
-
- public static void killTreeCaches(Collection treeCaches) {
- if (treeCaches != null) killTreeCaches((TreeCache[]) treeCaches.toArray(new TreeCache[]{}));
- }
-
- public static void killCaches(Collection caches) {
- if (caches != null) killCaches((Cache[]) caches.toArray(new Cache[]{}));
- }
-
- public static void killTreeCaches(TreeCache... treeCaches) {
- for (TreeCache tc : treeCaches) {
- if (tc != null) killCaches(tc.getCache());
- }
- }
-
- public static void killCacheManagers(CacheManager... cacheManagers) {
- if (cacheManagers != null) {
- for (CacheManager cm : cacheManagers) {
- if (cm != null) cm.stop();
- }
- }
- }
-
- /**
- * Kills a cache - stops it, clears any data in any cache loaders, and rolls back any associated txs
- */
- public static void killCaches(Cache... caches) {
- for (Cache c : caches) {
- try {
- if (c != null && c.getStatus() == ComponentStatus.RUNNING) {
- TransactionManager tm = getTransactionManager(c);
- if (tm != null) {
- try {
- tm.rollback();
- }
- catch (Exception e) {
- // don't care
- }
- }
- c.stop();
- }
- }
- catch (Throwable t) {
-
- }
- }
- }
-
- /**
- * Clears transaction with the current thread in the given transaction manager.
- *
- * @param txManager a TransactionManager to be cleared
- */
- public static void killTransaction(TransactionManager txManager) {
- if (txManager != null) {
- try {
- txManager.rollback();
- }
- catch (Exception e) {
- // don't care
- }
- }
- }
-
-
- /**
- * Clears any associated transactions with the current thread in the caches' transaction managers.
- */
- public static void killTransactions(Cache... caches) {
- for (Cache c : caches) {
- if (c != null && c.getStatus() == ComponentStatus.RUNNING) {
- TransactionManager tm = getTransactionManager(c);
- if (tm != null) {
- try {
- tm.rollback();
- }
- catch (Exception e) {
- // don't care
- }
- }
- }
- }
- }
-
- /**
- * For testing only - introspects a cache and extracts the ComponentRegistry
- *
- * @param cache cache to introspect
- * @return component registry
- */
- public static ComponentRegistry extractComponentRegistry(Cache cache) {
- return (ComponentRegistry) extractField(cache, "componentRegistry");
- }
-
- public static GlobalComponentRegistry extractGlobalComponentRegistry(CacheManager cacheManager) {
- return (GlobalComponentRegistry) extractField(cacheManager, "globalComponentRegistry");
- }
-
- public static LockManager extractLockManager(Cache cache) {
- return extractComponentRegistry(cache).getComponent(LockManager.class);
- }
-
- /**
- * For testing only - introspects a cache and extracts the ComponentRegistry
- *
- * @param ci interceptor chain to introspect
- * @return component registry
- */
- public static ComponentRegistry extractComponentRegistry(InterceptorChain ci) {
- return (ComponentRegistry) extractField(ci, "componentRegistry");
- }
-
-
- /**
- * Replaces the existing interceptor chain in the cache wih one represented by the interceptor passed in. This
- * utility updates dependencies on all components that rely on the interceptor chain as well.
- *
- * @param cache cache that needs to be altered
- * @param interceptor the first interceptor in the new chain.
- */
- public static void replaceInterceptorChain(Cache<?, ?> cache, CommandInterceptor interceptor) {
- ComponentRegistry cr = extractComponentRegistry(cache);
- // make sure all interceptors here are wired.
- CommandInterceptor i = interceptor;
- do {
- cr.wireDependencies(i);
- }
- while ((i = i.getNext()) != null);
-
- InterceptorChain inch = cr.getComponent(InterceptorChain.class);
- inch.setFirstInChain(interceptor);
- }
-
- /**
- * Retrieves the remote delegate for a given cache. It is on this remote delegate that the JGroups RPCDispatcher
- * invokes remote methods.
- *
- * @param cache cache instance for which a remote delegate is to be retrieved
- * @return remote delegate, or null if the cacge is not configured for replication.
- */
- public static CacheDelegate getInvocationDelegate(Cache cache) {
- return (CacheDelegate) cache;
- }
-
- /**
- * Blocks until the cache has reached a specified state.
- *
- * @param cache cache to watch
- * @param cacheStatus status to wait for
- * @param timeout timeout to wait for
- */
- public static void blockUntilCacheStatusAchieved(Cache cache, ComponentStatus cacheStatus, long timeout) {
- AdvancedCache spi = cache.getAdvancedCache();
- long killTime = System.currentTimeMillis() + timeout;
- while (System.currentTimeMillis() < killTime) {
- if (spi.getStatus() == cacheStatus) return;
- sleepThread(50);
- }
- throw new RuntimeException("Timed out waiting for condition");
- }
-
- public static void replicateCommand(Cache cache, VisitableCommand command) throws Throwable {
- ComponentRegistry cr = extractComponentRegistry(cache);
- InterceptorChain ic = cr.getComponent(InterceptorChain.class);
- ic.invoke(command);
- }
-
- public static void blockUntilViewsReceived(int timeout, List caches) {
- blockUntilViewsReceived((Cache[]) caches.toArray(new Cache[]{}), timeout);
- }
-
-
- public static CommandsFactory extractCommandsFactory(Cache<Object, Object> cache) {
- return (CommandsFactory) extractField(cache, "commandsFactory");
- }
-
- public static void dumpCacheContents(List caches) {
- System.out.println("**** START: Cache Contents ****");
- int count = 1;
- for (Object o : caches) {
- Cache c = (Cache) o;
- if (c == null) {
- System.out.println(" ** Cache " + count + " is null!");
- } else {
- System.out.println(" ** Cache " + count + " is " + c.getCacheManager().getAddress());
- }
- count++;
- }
- System.out.println("**** END: Cache Contents ****");
- }
-
- public static void dumpCacheContents(Cache... caches) {
- dumpCacheContents(Arrays.asList(caches));
- }
-
- /**
- * Extracts a component of a given type from the cache's internal component registry
- *
- * @param cache
- * @param componentType
- * @param <T>
- * @return
- */
- public static <T> T extractComponent(Cache cache, Class<T> componentType) {
- ComponentRegistry cr = extractComponentRegistry(cache);
- return cr.getComponent(componentType);
- }
-
- public static TransactionManager getTransactionManager(Cache cache) {
- return cache == null ? null : extractComponent(cache, TransactionManager.class);
- }
-
- /**
- * Replaces a component in a running cache
- *
- * @param cache cache in which to replace component
- * @param componentType component type of which to replace
- * @param replacementComponent new instance
- * @param rewire if true, ComponentRegistry.rewire() is called after replacing.
- * @return the original component that was replaced
- */
- public static <T> T replaceComponent(Cache<?, ?> cache, Class<T> componentType, T replacementComponent, boolean rewire) {
- ComponentRegistry cr = extractComponentRegistry(cache);
- T old = cr.getComponent(componentType);
- cr.registerComponent(replacementComponent, componentType);
- if (rewire) cr.rewire();
- return old;
- }
-
- /**
- * Replaces a component in a running cache manager (global component registry)
- *
- * @param cacheManager cache in which to replace component
- * @param componentType component type of which to replace
- * @param replacementComponent new instance
- * @param rewire if true, ComponentRegistry.rewire() is called after replacing.
- * @return the original component that was replaced
- */
- public static <T> T replaceComponent(CacheManager cacheManager, Class<T> componentType, T replacementComponent, boolean rewire) {
- GlobalComponentRegistry cr = extractGlobalComponentRegistry(cacheManager);
- T old = cr.getComponent(componentType);
- cr.registerComponent(replacementComponent, componentType);
- if (rewire) {
- cr.rewire();
- cr.rewireNamedRegistries();
- }
- return old;
- }
-}
Modified: core/branches/flat/src/main/resources/config-samples/all.xml
===================================================================
--- core/branches/flat/src/main/resources/config-samples/all.xml 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/main/resources/config-samples/all.xml 2009-02-17 14:38:40 UTC (rev 7699)
@@ -102,7 +102,7 @@
<!--
Uncomment this for async replication.
-->
- <!--<async useReplQueue="true" replQueueInterval="10000" replQueueMaxElements="500" serializationExecutorPoolSize="20" serializationExecutorQueueSize="5000000"/>-->
+ <!--<async useReplQueue="true" replQueueInterval="10000" replQueueMaxElements="500"/>-->
</clustering>
</default>
@@ -163,7 +163,6 @@
</namedCache>
-
<namedCache name="cacheWithCustomInterceptors">
<!--
Define custom interceptors. All custom interceptors need to extend org.jboss.cache.interceptors.base.CommandInterceptor
Deleted: core/branches/flat/src/test/java/org/horizon/BaseClusteredTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/BaseClusteredTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/BaseClusteredTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,217 +0,0 @@
-package org.horizon;
-
-import org.horizon.commands.DataCommand;
-import org.horizon.commands.VisitableCommand;
-import org.horizon.commands.tx.CommitCommand;
-import org.horizon.commands.tx.PrepareCommand;
-import org.horizon.config.Configuration;
-import org.horizon.config.GlobalConfiguration;
-import org.horizon.context.InvocationContext;
-import org.horizon.interceptors.base.CommandInterceptor;
-import org.horizon.manager.CacheManager;
-import org.horizon.manager.DefaultCacheManager;
-import org.horizon.util.TestingUtil;
-import org.testng.annotations.AfterMethod;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- * A base class that <i>all</i> tests that use clustering needs to extend. <tt>CacheManager</tt>s should <i>only</b> be
- * created using the methods here, since this class takes care of proper cleanup of the clustering stack.
- * <p/>
- * This class also offers some cluster-specific helper methods, like {@link #assertClusterSize(String, int)} and {@link
- * #attachReplicationListener(Cache)}, the latter which allows you to attach listeners to caches and block until RPC
- * calls are received. While this is most useful on asynchronous tests, it does not break synchronous tests either so
- * test code could be reused.
- * <p/>
- * See {@link org.horizon.BaseClusteredTest.ReplListener} for details.
- */
-public abstract class BaseClusteredTest {
- ThreadLocal<List<CacheManager>> cacheManagerThreadLocal = new ThreadLocal<List<CacheManager>>() {
- @Override
- protected List<CacheManager> initialValue() {
- return new LinkedList<CacheManager>();
- }
- };
-
- /**
- * @return a list of registered cache managers on the current thread.
- */
- protected List<CacheManager> getCacheManagers() {
- return cacheManagerThreadLocal.get();
- }
-
- /**
- * Creates a new cache manager, starts it, and adds it to the list of known cache managers on the current thread.
- * Uses a default clustered cache manager global config.
- *
- * @return the new CacheManager
- */
- protected CacheManager addClusterEnabledCacheManager() {
- return addCacheManager(GlobalConfiguration.getClusteredDefault());
- }
-
- /**
- * Creates a new cache manager, starts it, and adds it to the list of known cache managers on the current thread.
- *
- * @param globalConfig config to use
- * @return the new CacheManager
- */
- protected CacheManager addCacheManager(GlobalConfiguration globalConfig) {
- CacheManager cm = new DefaultCacheManager(globalConfig);
- cacheManagerThreadLocal.get().add(cm);
- return cm;
- }
-
- protected void defineCacheOnAllManagers(String cacheName, Configuration c) {
- for (CacheManager cm : cacheManagerThreadLocal.get()) {
- cm.defineCache(cacheName, c);
- }
- }
-
- protected List<Cache> createClusteredCaches(int numMembersInCluster, String cacheName, Configuration c) {
- List<Cache> caches = new ArrayList<Cache>(numMembersInCluster);
- for (int i = 0; i < numMembersInCluster; i++) {
- CacheManager cm = addClusterEnabledCacheManager();
- cm.defineCache(cacheName, c);
- caches.add(cm.getCache(cacheName));
- }
- return caches;
- }
-
- protected void assertClusterSize(String message, int size) {
- for (CacheManager cm : cacheManagerThreadLocal.get()) {
- assert cm.getMembers() != null && cm.getMembers().size() == size : message;
- }
- }
-
- protected ReplListener attachReplicationListener(Cache c) {
- return new ReplListener(c);
- }
-
- @AfterMethod(alwaysRun = true)
- public void cleanupThreadLocals() {
- TestingUtil.killCacheManagers(cacheManagerThreadLocal.get().toArray(new CacheManager[cacheManagerThreadLocal.get().size()]));
- cacheManagerThreadLocal.get().clear();
- }
-
- /**
- * A listener that listens for replication events on a cache it is watching. Typical usage: <code> ReplListener r =
- * attachReplicationListener(cache); r.expect(RemoveCommand.class); // ... r.waitForRPC(); </code>
- */
- protected static class ReplListener {
- Cache c;
- Set<Class<? extends VisitableCommand>> expectedCommands;
- CountDownLatch latch = new CountDownLatch(1);
-
- public ReplListener(Cache c) {
- this.c = c;
- this.c.getAdvancedCache().addInterceptor(new ReplListenerInterceptor(), 0);
- }
-
- /**
- * Expects any commands. The moment a single command is detected, the {@link #waitForRPC()} command will be
- * unblocked.
- */
- public void expectAny() {
- expect();
- }
-
- /**
- * Expects a specific set of commands, within transactional scope (i.e., as a payload to a PrepareCommand). If
- * the cache mode is synchronous, a CommitCommand is expected as well.
- *
- * @param commands commands to expect (not counting transaction boundary commands like PrepareCommand and
- * CommitCommand)
- */
- public void expectWithTx(Class<? extends VisitableCommand>... commands) {
- expect(PrepareCommand.class);
- expect(commands);
- //this is because for async replication we have an 1pc transaction
- if (c.getConfiguration().getCacheMode().isSynchronous()) expect(CommitCommand.class);
- }
-
- /**
- * Expects any commands, within transactional scope (i.e., as a payload to a PrepareCommand). If the cache mode
- * is synchronous, a CommitCommand is expected as well.
- */
- public void expectAnyWithTx() {
- expect(PrepareCommand.class);
- //this is because for async replication we have an 1pc transaction
- if (c.getConfiguration().getCacheMode().isSynchronous()) expect(CommitCommand.class);
- }
-
- /**
- * Expects a specific set of commands. {@link #waitForRPC()} will block until all of these commands are
- * detected.
- *
- * @param expectedCommands commands to expect
- */
- public void expect(Class<? extends VisitableCommand>... expectedCommands) {
- if (this.expectedCommands == null) {
- this.expectedCommands = new HashSet<Class<? extends VisitableCommand>>();
- }
- this.expectedCommands.addAll(Arrays.asList(expectedCommands));
- }
-
- /**
- * Blocks for a predefined amount of time (120 Seconds) until commands defined in any of the expect*() methods
- * have been detected. If the commands have not been detected by this time, an exception is thrown.
- */
- public void waitForRPC() {
- waitForRPC(120, TimeUnit.SECONDS);
- }
-
- /**
- * The same as {@link #waitForRPC()} except that you are allowed to specify the max wait time.
- */
- public void waitForRPC(long time, TimeUnit unit) {
- assert expectedCommands != null : "there are no replication expectations; please use ReplListener.expect() before calling this method";
- try {
- if (!latch.await(time, unit)) {
- assert false : "Waiting for more than " + time + " " + unit + " and following commands did not replicate: " + expectedCommands;
- }
- }
- catch (InterruptedException e) {
- throw new IllegalStateException("unexpected", e);
- }
- finally {
- expectedCommands = null;
- latch = new CountDownLatch(1);
- }
- }
-
- protected class ReplListenerInterceptor extends CommandInterceptor {
- @Override
- protected Object handleDefault(InvocationContext ctx, VisitableCommand cmd) throws Throwable {
- // first pass up chain
- Object o = invokeNextInterceptor(ctx, cmd);
- markAsVisited(cmd);
- return o;
- }
-
- @Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand cmd) throws Throwable {
- // first pass up chain
- Object o = invokeNextInterceptor(ctx, cmd);
- markAsVisited(cmd);
- for (DataCommand mod : cmd.getModifications()) markAsVisited(mod);
- return o;
- }
-
- private void markAsVisited(VisitableCommand cmd) {
- if (expectedCommands != null) {
- expectedCommands.remove(cmd.getClass());
- if (expectedCommands.isEmpty()) latch.countDown();
- }
- }
- }
- }
-}
Deleted: core/branches/flat/src/test/java/org/horizon/UnitTestCacheFactory.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/UnitTestCacheFactory.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/UnitTestCacheFactory.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,332 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- *
- * Distributable under LGPL license.
- * See terms of license at gnu.org.
- */
-package org.horizon;
-
-import org.horizon.config.Configuration;
-import org.horizon.config.ConfigurationException;
-import org.horizon.config.parsing.XmlConfigurationParser;
-import org.horizon.config.parsing.XmlConfigurationParserImpl;
-import org.horizon.logging.Log;
-import org.horizon.logging.LogFactory;
-import org.horizon.manager.DefaultCacheManager;
-import org.horizon.util.TestingUtil;
-import org.jgroups.conf.XmlConfigurator;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * @author <a href="mailto:dpospisi@redhat.com">Dominik Pospisil (dpospisi(a)redhat.com)</a>
- */
-public class UnitTestCacheFactory<K, V>// implements CacheFactory<K, V>
-{
-
- private final Log log = LogFactory.getLog(UnitTestCacheFactory.class);
-
-
- /**
- * Holds unique mcast_addr for each thread used for JGroups channel construction.
- */
- private static final ThreadLocal<String> threadMcastIP = new ThreadLocal<String>() {
- private final AtomicInteger uniqueAddr = new AtomicInteger(11);
-
- @Override
- protected String initialValue() {
- return "228.10.10." + uniqueAddr.getAndIncrement();
- }
- };
-
- /**
- * Holds unique mcast_port for each thread used for JGroups channel construction.
- */
- private static final ThreadLocal<Integer> threadMcastPort = new ThreadLocal<Integer>() {
- private final AtomicInteger uniquePort = new AtomicInteger(45589);
-
- @Override
- protected Integer initialValue() {
- return uniquePort.getAndIncrement();
- }
- };
-
- /**
- * For each thread holds list of caches created using this factory.
- */
- private static final ThreadLocal<List<Cache>> threadCaches =
- new ThreadLocal<List<Cache>>() {
- @Override
- protected List<Cache> initialValue() {
- return new ArrayList<Cache>();
- }
- };
-
- private final static List<Cache> allCaches = new ArrayList<Cache>();
-
- /**
- * For each thread holds the name of the test class which executed createCache factory method.
- */
- private static final ThreadLocal<String> threadTestName = new ThreadLocal<String>();
-
- // factory methods
-
- public Cache<K, V> createCache() throws ConfigurationException {
- return createCache(true);
- }
-
- public Cache<K, V> createCache(boolean start) throws ConfigurationException {
- return createCache(new Configuration(), start);
- }
-
- public Cache<K, V> createCache(String configFileName) throws ConfigurationException, IOException {
- return createCache(configFileName, true);
- }
-
- public Cache<K, V> createCache(String configFileName, boolean start) throws ConfigurationException, IOException {
- XmlConfigurationParser parser = new XmlConfigurationParserImpl(configFileName);
- Configuration c;
-
- // TODO: gotta build a proper cache manager here
- return null;
-
- //return createCache(c, start);
- }
-
- public Cache<K, V> createCache(Configuration configuration) throws ConfigurationException {
- return createCache(configuration, true);
- }
-
- public Cache<K, V> createCache(InputStream is) throws ConfigurationException, IOException {
- return createCache(is, true);
- }
-
- public Cache<K, V> createCache(InputStream is, boolean start) throws ConfigurationException, IOException {
- XmlConfigurationParser parser = new XmlConfigurationParserImpl(is);
- //Configuration c = parser.parseStream(is);
- //return createCache(c, start);
- // TODO: gotta build a proper cache manager here
- return null;
- }
-
- public Cache<K, V> createCache(Configuration configuration, boolean start) throws ConfigurationException {
- // - Do not print out this exception - since tests are ALSO run from IDEs on the main thread. - MANIK
-// if (!Thread.currentThread().getName().contains("pool"))
-// {
-// System.out.println("CreateCache called from wrong thread: " + Thread.currentThread().getName());
-// }
-
- checkCaches();
-
- switch (configuration.getCacheMode()) {
- case LOCAL:
- // local cache, no channel used
- break;
- case REPL_SYNC:
- case REPL_ASYNC:
- case INVALIDATION_ASYNC:
- case INVALIDATION_SYNC:
- // replicated cache, update channel setup
- mangleConfiguration(configuration);
- break;
- default:
- log.info("Unknown cache mode!");
- }
-
-// Cache<K, V> cache = new DefaultCacheFactory<K, V>().createCache(configuration, start);
- DefaultCacheManager cm = new DefaultCacheManager(configuration);
- Cache<K, V> cache = cm.getCache();
-
- List<Cache> caches = threadCaches.get();
- caches.add(cache);
-
- synchronized (allCaches) {
- allCaches.add(cache);
- }
- return cache;
-
- }
-
- /**
- * Destroys all caches created by this factory in the current thread.
- *
- * @return true if some cleanup was actually performed
- */
- public boolean cleanUp() {
- List<Cache> caches = new ArrayList<Cache>(threadCaches.get());
- boolean ret = false;
-
- for (Cache cache : caches) {
- TestingUtil.killCaches(cache);
- ret = true;
- }
- return ret;
- }
-
- public void removeCache(Cache c) {
-
- // - Do not print out this exception - since tests are ALSO run from IDEs on the main thread. - MANIK
-// if (!Thread.currentThread().getName().contains("pool"))
-// {
-// System.out.println("RemoveCache called from wrong thread.");
-// }
-
- List<Cache> caches = threadCaches.get();
- synchronized (allCaches) {
- if (caches.contains(c)) {
- caches.remove(c);
- allCaches.remove(c);
- } else if (allCaches.contains(c)) {
- System.out.println("[" + Thread.currentThread().getName() + "] WARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Remove cache called from different thread.");
- Thread.dumpStack();
- }
- }
- }
-
- /**
- * Updates cluster configuration to ensure mutual thread isolation.
- *
- * @param configuration Configuration to update.
- */
- public void mangleConfiguration(Configuration configuration) {
- // TODO fix this to use the cache manager
-
-// configuration.setClusterConfig(mangleClusterConfiguration(configuration.getClusterConfig()));
- // Check if the cluster name contains thread id. If not, append.
- // We can not just append the threadId, since some of the tests are crating instances
- // using configurations derived from configurations returned by this factory.
-
-// String clusterName = configuration.getClusterName();
-
- // append thread id
-// if (clusterName.indexOf(Thread.currentThread().getName()) == -1) {
-// clusterName = clusterName + "-" + Thread.currentThread().getName();
-//// System.out.println(getThreadId() + " Setting cluster name " + newClusterName);
-// }
-
-// String testName = extractTestName();
-
- // prepend test name
- /*
- if (clusterName.indexOf(testName) == -1) {
- clusterName = testName + "-" + clusterName;
- }
- */
-
-// configuration.setClusterName(clusterName);
-
- }
-
- /**
- * Updates cluster configuration to ensure mutual thread isolation.
- */
- public String mangleClusterConfiguration(String clusterConfig) {
- if (clusterConfig == null) {
- // No explicit cluster configuration found. we need to resolve the default config
- // now in orded to be able to update it before the cache (and the channel) starts.
-
- clusterConfig = getDefaultClusterConfiguration();
- }
-
- // replace mcast_addr
- Pattern pattern = Pattern.compile("mcast_addr=[^;]*");
- Matcher m = pattern.matcher(clusterConfig);
- if (m.find()) {
- String origAddr = m.group().substring(m.group().indexOf("=") + 1);
- String newAddr = threadMcastIP.get();
-// System.out.println(getThreadId() + " Replacing mcast_addr " + origAddr + " with " + newAddr);
- clusterConfig = m.replaceFirst("mcast_addr=" + newAddr);
- } else {
- Thread.dumpStack();
- System.exit(1);
- }
-
- // replace mcast_port
- pattern = Pattern.compile("mcast_port=[^;]*");
- m = pattern.matcher(clusterConfig);
- if (m.find()) {
-// String origPort = m.group().substring(m.group().indexOf("=") + 1);
- String newPort = threadMcastPort.get().toString();
- // System.out.println(getThreadId() + " Replacing mcast_port " + origPort + " with " + newPort);
- clusterConfig = m.replaceFirst("mcast_port=" + newPort);
- }
-
- return clusterConfig;
- }
-
-// private String getThreadId()
-// {
-// return "[" + Thread.currentThread().getName() + "]";
-// }
-
- private void checkCaches() {
- String lastTestName = threadTestName.get();
- String currentTestName = extractTestName();
-
- if ((lastTestName != null) && (!lastTestName.equals(currentTestName))) {
-
- String threadId = "[" + Thread.currentThread().getName() + "] ";
-
- // we are running new test class
- // check if there is a cache(s) instance left & kill it if possitive
-
- if (cleanUp()) {
- System.out.print(threadId + "WARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ");
- System.out.print(threadId + " A test method in " + lastTestName + " did not clean all cache instances properly. ");
- System.out.println(threadId + " Use UnitTestCacheFactory.cleanUp() or TestngUtil.killCaches(...) ");
- }
-
- }
- threadTestName.set(currentTestName);
- }
-
- private String extractTestName() {
- StackTraceElement[] stack = Thread.currentThread().getStackTrace();
- if (stack.length == 0) return null;
- for (int i = stack.length - 1; i > 0; i--) {
- StackTraceElement e = stack[i];
- String className = e.getClassName();
- if (className.indexOf("org.horizon") != -1) return className; //+ "." + e.getMethodName();
- }
- return null;
- }
-
- private String getDefaultClusterConfiguration() {
- // TODO: fix this to use the cache manager
-// return getClusterConfigFromFile(new Configuration().getDefaultClusterConfig());
- return null;
- }
-
- /**
- * Helper method that takes a <b>JGroups</b> configuration file and creates an old-style JGroups config {@link
- * String} that can be used in {@link Configuration#setClusterConfig(String)}. Note that expressions in the file -
- * such as <tt>${jgroups.udp.mcast_port:45588}</tt> are expanded out accordingly.
- *
- * @param url url to the cfg file
- * @return a String
- */
- public static String getClusterConfigFromFile(URL url) {
- try {
- XmlConfigurator conf = XmlConfigurator.getInstance(url);
- String tmp = conf.getProtocolStackString();
- // parse this string for ${} substitutions
- // Highly crappy approach!!
- tmp = tmp.replace("${jgroups.udp.mcast_addr:228.10.10.10}", "228.10.10.10");
- tmp = tmp.replace("${jgroups.udp.mcast_port:45588}", "45588");
- tmp = tmp.replace("${jgroups.udp.ip_ttl:2}", "2");
-// System.out.println("config string: " + tmp);
- return tmp;
- }
- catch (Exception e) {
- throw new RuntimeException("Problems with url " + url, e);
- }
- }
-
-}
Deleted: core/branches/flat/src/test/java/org/horizon/UnitTestCacheManager.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/UnitTestCacheManager.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/UnitTestCacheManager.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,30 +0,0 @@
-/*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
-
-package org.horizon;
-
-import org.horizon.config.Configuration;
-
-/**
- * Always use this cache manager when writing unit tests. This allows for parallel tests to run.
- *
- * @author dpospisi
- */
-public class UnitTestCacheManager {
- Configuration c;
-
- public UnitTestCacheManager(Configuration c) {
- this.c = c.clone();
- }
-
- protected Cache createNewCache() {
- UnitTestCacheFactory dcf = new UnitTestCacheFactory();
- return dcf.createCache(c);
- }
-
- public Cache createCache(String name) {
- return createNewCache();
- }
-}
Modified: core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,17 +1,16 @@
package org.horizon.api;
import org.horizon.Cache;
-import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
import org.horizon.config.ConfigurationException;
import org.horizon.lock.IsolationLevel;
+import org.horizon.manager.CacheManager;
+import org.horizon.test.SingleCacheManagerTest;
+import org.horizon.test.TestingUtil;
import org.horizon.transaction.DummyTransactionManager;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.HashMap;
@@ -22,36 +21,27 @@
*
* @author <a href="mailto:manik@jboss.org">Manik Surtani</a>
*/
+@Test(groups = "functional")
+public abstract class CacheAPITest extends SingleCacheManagerTest {
+ Cache cache;
-@Test(groups = "functional", sequential = true)
-public abstract class CacheAPITest {
- private ThreadLocal<Cache<String, String>> cacheTL = new ThreadLocal<Cache<String, String>>();
-
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception {
+ protected CacheManager createCacheManager() throws Exception {
// start a single cache instance
Configuration c = new Configuration();
c.setIsolationLevel(getIsolationLevel());
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- UnitTestCacheFactory<String, String> cf = new UnitTestCacheFactory<String, String>();
- Cache<String, String> cache = cf.createCache(c.clone());
- cacheTL.set(cache);
+ CacheManager cm = TestingUtil.createLocalCacheManager();
+ cm.defineCache("test", c);
+ cache = cm.getCache("test");
+ return cm;
}
protected abstract IsolationLevel getIsolationLevel();
- @AfterMethod(alwaysRun = true)
- public void tearDown() {
- Cache<String, String> cache = cacheTL.get();
- TestingUtil.killCaches(cache);
- cacheTL.set(null);
- }
-
/**
* Tests that the configuration contains the values expected, as well as immutability of certain elements
*/
public void testConfiguration() {
- Cache<String, String> cache = cacheTL.get();
Configuration c = cache.getConfiguration();
assertEquals(Configuration.CacheMode.LOCAL, c.getCacheMode());
assertEquals(DummyTransactionManagerLookup.class.getName(), c.getTransactionManagerLookupClass());
@@ -70,12 +60,10 @@
}
public void testGetMembersInLocalMode() {
- Cache<String, String> cache = cacheTL.get();
assert cache.getCacheManager().getAddress() == null : "Cache members should be null if running in LOCAL mode";
}
public void testConvenienceMethods() {
- Cache<String, String> cache = cacheTL.get();
String key = "key", value = "value";
Map<String, String> data = new HashMap<String, String>();
data.put(key, value);
@@ -99,7 +87,6 @@
* Tests basic eviction
*/
public void testEvict() {
- Cache<String, String> cache = cacheTL.get();
String key1 = "keyOne", key2 = "keyTwo", value = "value";
cache.put(key1, value);
@@ -124,7 +111,6 @@
}
public void testStopClearsData() throws Exception {
- Cache<String, String> cache = cacheTL.get();
String key = "key", value = "value";
cache.put(key, value);
assert cache.get(key).equals(value);
@@ -138,7 +124,6 @@
}
public void testRollbackAfterPut() throws Exception {
- Cache<String, String> cache = cacheTL.get();
String key = "key", value = "value";
cache.put(key, value);
assert cache.get(key).equals(value);
@@ -154,7 +139,6 @@
}
public void testRollbackAfterOverwrite() throws Exception {
- Cache<String, String> cache = cacheTL.get();
String key = "key", value = "value";
cache.put(key, value);
assert cache.get(key).equals(value);
@@ -171,7 +155,6 @@
}
public void testRollbackAfterRemove() throws Exception {
- Cache<String, String> cache = cacheTL.get();
String key = "key", value = "value";
cache.put(key, value);
assert cache.get(key).equals(value);
@@ -187,7 +170,6 @@
}
public void testRollbackAfterClear() throws Exception {
- Cache<String, String> cache = cacheTL.get();
String key = "key", value = "value";
cache.put(key, value);
assert cache.get(key).equals(value);
@@ -203,31 +185,29 @@
}
public void testConcurrentMapMethods() {
- Cache<String, String> c = cacheTL.get();
- assert c.putIfAbsent("A", "B") == null;
- assert c.putIfAbsent("A", "C").equals("B");
- assert c.get("A").equals("B");
+ assert ((Cache<String, String>) cache).putIfAbsent("A", "B") == null;
+ assert ((Cache<String, String>) cache).putIfAbsent("A", "C").equals("B");
+ assert ((Cache<String, String>) cache).get("A").equals("B");
- assert !c.remove("A", "C");
- assert c.containsKey("A");
- assert c.remove("A", "B");
- assert !c.containsKey("A");
+ assert !((Cache<String, String>) cache).remove("A", "C");
+ assert ((Cache<String, String>) cache).containsKey("A");
+ assert ((Cache<String, String>) cache).remove("A", "B");
+ assert !((Cache<String, String>) cache).containsKey("A");
- c.put("A", "B");
+ ((Cache<String, String>) cache).put("A", "B");
- assert !c.replace("A", "D", "C");
- assert c.get("A").equals("B");
- assert c.replace("A", "B", "C");
- assert c.get("A").equals("C");
+ assert !((Cache<String, String>) cache).replace("A", "D", "C");
+ assert ((Cache<String, String>) cache).get("A").equals("B");
+ assert ((Cache<String, String>) cache).replace("A", "B", "C");
+ assert ((Cache<String, String>) cache).get("A").equals("C");
- assert c.replace("A", "X").equals("C");
- assert c.replace("X", "A") == null;
- assert !c.containsKey("X");
+ assert ((Cache<String, String>) cache).replace("A", "X").equals("C");
+ assert ((Cache<String, String>) cache).replace("X", "A") == null;
+ assert !((Cache<String, String>) cache).containsKey("X");
}
public void testSizeAndContents() throws Exception {
- Cache cache = cacheTL.get();
String key = "key", value = "value";
assert cache.isEmpty();
Modified: core/branches/flat/src/test/java/org/horizon/api/CacheClusterJoinTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/CacheClusterJoinTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/CacheClusterJoinTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,30 +1,36 @@
package org.horizon.api;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.config.Configuration;
import org.horizon.config.Configuration.CacheMode;
import org.horizon.manager.CacheManager;
-import org.horizon.util.TestingUtil;
+import org.horizon.test.TestingUtil;
+import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
-@Test(groups = "functional", sequential = true)
-public class CacheClusterJoinTest extends BaseClusteredTest {
+@Test(groups = "functional", testName = "api.CacheClusterJoinTest")
+public class CacheClusterJoinTest {
Cache cache1, cache2;
CacheManager cm1, cm2;
Configuration cfg;
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
- cm1 = addClusterEnabledCacheManager();
+ cm1 = TestingUtil.createClusteredCacheManager();
cfg = new Configuration();
cfg.setCacheMode(CacheMode.REPL_SYNC);
cm1.defineCache("cache", cfg);
}
+ @AfterMethod
+ public void tearDown()
+ {
+ TestingUtil.killCacheManagers(cm1, cm2);
+ }
+
public void testGetMembers() throws Exception {
cm1.getCache("cache"); // this will make sure any lazy components are started.
List memb1 = cm1.getMembers();
@@ -32,7 +38,7 @@
Object coord = memb1.get(0);
- cm2 = addClusterEnabledCacheManager();
+ cm2 = TestingUtil.createClusteredCacheManager();
cm2.defineCache("cache", cfg);
cm2.getCache("cache"); // this will make sure any lazy components are started.
TestingUtil.blockUntilViewsReceived(50000, true, cm1, cm2);
@@ -52,7 +58,7 @@
cm1.getCache("cache"); // this will make sure any lazy components are started.
assert cm1.isCoordinator();
- cm2 = addClusterEnabledCacheManager();
+ cm2 = TestingUtil.createClusteredCacheManager();
cm2.defineCache("cache", cfg);
cm2.getCache("cache"); // this will make sure any lazy components are started.
assert cm1.isCoordinator();
Modified: core/branches/flat/src/test/java/org/horizon/api/MixedModeTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/MixedModeTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/MixedModeTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,27 +1,20 @@
package org.horizon.api;
import org.horizon.AdvancedCache;
-import org.horizon.BaseClusteredTest;
import org.horizon.config.Configuration;
import org.horizon.invocation.Options;
-import org.horizon.manager.CacheManager;
-import org.horizon.util.TestingUtil;
-import org.testng.annotations.BeforeMethod;
+import org.horizon.test.MultipleCacheManagersTest;
import org.testng.annotations.Test;
-@Test(groups = "functional", sequential = true)
-public class MixedModeTest extends BaseClusteredTest {
+@Test(groups = "functional", testName = "api.MixedModeTest")
+public class MixedModeTest extends MultipleCacheManagersTest {
AdvancedCache replSyncCache1, replSyncCache2;
AdvancedCache replAsyncCache1, replAsyncCache2;
AdvancedCache invalAsyncCache1, invalAsyncCache2;
AdvancedCache invalSyncCache1, invalSyncCache2;
AdvancedCache localCache1, localCache2;
- @BeforeMethod
- public void setUp() {
- CacheManager cm1 = addClusterEnabledCacheManager();
- CacheManager cm2 = addClusterEnabledCacheManager();
-
+ protected void createCaches() throws Throwable {
Configuration replSync = new Configuration();
replSync.setCacheMode(Configuration.CacheMode.REPL_SYNC);
@@ -37,29 +30,26 @@
Configuration local = new Configuration();
local.setCacheMode(Configuration.CacheMode.LOCAL);
- defineCacheOnAllManagers("replSync", replSync);
+ createClusteredCaches(2, "replSync", replSync);
defineCacheOnAllManagers("replAsync", replAsync);
defineCacheOnAllManagers("invalSync", invalSync);
defineCacheOnAllManagers("invalAsync", invalAsync);
defineCacheOnAllManagers("local", local);
- replSyncCache1 = cm1.getCache("replSync").getAdvancedCache();
- replSyncCache2 = cm2.getCache("replSync").getAdvancedCache();
- replAsyncCache1 = cm1.getCache("replAsync").getAdvancedCache();
- replAsyncCache2 = cm2.getCache("replAsync").getAdvancedCache();
- invalSyncCache1 = cm1.getCache("invalSync").getAdvancedCache();
- invalSyncCache2 = cm2.getCache("invalSync").getAdvancedCache();
- invalAsyncCache1 = cm1.getCache("invalAsync").getAdvancedCache();
- invalAsyncCache2 = cm2.getCache("invalAsync").getAdvancedCache();
- localCache1 = cm1.getCache("local").getAdvancedCache();
- localCache2 = cm2.getCache("local").getAdvancedCache();
-
- TestingUtil.blockUntilViewsReceived(60000, cm1, cm2);
+ replSyncCache1 = cache(0, "replSync").getAdvancedCache();
+ replSyncCache2 = cache(1, "replSync").getAdvancedCache();
+ replAsyncCache1 = cache(0, "replAsync").getAdvancedCache();
+ replAsyncCache2 = cache(1, "replAsync").getAdvancedCache();
+ invalSyncCache1 = cache(0, "invalSync").getAdvancedCache();
+ invalSyncCache2 = cache(1, "invalSync").getAdvancedCache();
+ invalAsyncCache1 = cache(0, "invalAsync").getAdvancedCache();
+ invalAsyncCache2 = cache(1, "invalAsync").getAdvancedCache();
+ localCache1 = cache(0, "local").getAdvancedCache();
+ localCache2 = cache(1, "local").getAdvancedCache();
}
+
public void testMixedMode() {
- ReplListener r1 = attachReplicationListener(replAsyncCache2);
- ReplListener r2 = attachReplicationListener(invalAsyncCache2);
invalSyncCache2.put("k", "v", Options.CACHE_MODE_LOCAL);
assert invalSyncCache2.get("k").equals("v");
@@ -68,8 +58,8 @@
assert invalAsyncCache2.get("k").equals("v");
assert invalAsyncCache1.get("k") == null;
- r1.expectAny();
- r2.expectAny();
+ replListener(replAsyncCache2).expectAny();
+ replListener(invalAsyncCache2).expectAny();
replSyncCache1.put("k", "replSync");
replAsyncCache1.put("k", "replAsync");
@@ -77,8 +67,8 @@
invalAsyncCache1.put("k", "invalAsync");
localCache1.put("k", "local");
- r1.waitForRPC();
- r2.waitForRPC();
+ replListener(replAsyncCache2).waitForRPC();
+ replListener(invalAsyncCache2).waitForRPC();
assert replSyncCache1.get("k").equals("replSync");
assert replSyncCache2.get("k").equals("replSync");
Modified: core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTMTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTMTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTMTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,103 +1,101 @@
package org.horizon.api.batch;
import org.horizon.Cache;
-import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
+import org.horizon.manager.CacheManager;
+import org.horizon.test.TestingUtil;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import javax.transaction.TransactionManager;
-@Test(groups = {"functional", "transaction"})
+@Test(groups = {"functional", "transaction"}, testName = "api.batch.BatchWithTMTest")
public class BatchWithTMTest extends AbstractBatchTest {
+
+ CacheManager cm;
+
+ @BeforeClass
+ public void createCacheManager() {
+ cm = TestingUtil.createLocalCacheManager();
+ }
+
+ @AfterClass
+ public void destroyCacheManager() {
+ TestingUtil.killCacheManagers(cm);
+ }
+
public void testBatchWithOngoingTM() throws Exception {
Cache<String, String> cache = null;
- try {
- cache = createCache();
- TransactionManager tm = TestingUtil.getTransactionManager(cache);
- tm.begin();
- cache.put("k", "v");
- cache.startBatch();
- cache.put("k2", "v2");
- tm.commit();
+ cache = createCache("testBatchWithOngoingTM");
+ TransactionManager tm = TestingUtil.getTransactionManager(cache);
+ tm.begin();
+ cache.put("k", "v");
+ cache.startBatch();
+ cache.put("k2", "v2");
+ tm.commit();
- assert "v".equals(cache.get("k"));
- assert "v2".equals(cache.get("k2"));
+ assert "v".equals(cache.get("k"));
+ assert "v2".equals(cache.get("k2"));
- cache.endBatch(false); // should be a no op
- assert "v".equals(cache.get("k"));
- assert "v2".equals(cache.get("k2"));
- }
- finally {
- TestingUtil.killCaches(cache);
- }
+ cache.endBatch(false); // should be a no op
+ assert "v".equals(cache.get("k"));
+ assert "v2".equals(cache.get("k2"));
}
public void testBatchWithoutOngoingTMSuspension() throws Exception {
- Cache<String, String> cache = null;
- try {
- cache = createCache();
- TransactionManager tm = TestingUtil.getTransactionManager(cache);
- assert tm.getTransaction() == null : "Should have no ongoing txs";
- cache.startBatch();
- cache.put("k", "v");
- assert tm.getTransaction() == null : "Should have no ongoing txs";
- cache.put("k2", "v2");
+ Cache cache = createCache("testBatchWithoutOngoingTMSuspension");
+ TransactionManager tm = TestingUtil.getTransactionManager(cache);
+ assert tm.getTransaction() == null : "Should have no ongoing txs";
+ cache.startBatch();
+ cache.put("k", "v");
+ assert tm.getTransaction() == null : "Should have no ongoing txs";
+ cache.put("k2", "v2");
- assert getOnDifferentThread(cache, "k") == null;
- assert getOnDifferentThread(cache, "k2") == null;
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
- try {
- tm.commit(); // should have no effect
- }
- catch (Exception e) {
- // the TM may barf here ... this is OK.
- }
+ try {
+ tm.commit(); // should have no effect
+ }
+ catch (Exception e) {
+ // the TM may barf here ... this is OK.
+ }
- assert tm.getTransaction() == null : "Should have no ongoing txs";
+ assert tm.getTransaction() == null : "Should have no ongoing txs";
- assert getOnDifferentThread(cache, "k") == null;
- assert getOnDifferentThread(cache, "k2") == null;
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
- cache.endBatch(true); // should be a no op
+ cache.endBatch(true); // should be a no op
- assert "v".equals(getOnDifferentThread(cache, "k"));
- assert "v2".equals(getOnDifferentThread(cache, "k2"));
- }
- finally {
- TestingUtil.killCaches(cache);
- }
+ assert "v".equals(getOnDifferentThread(cache, "k"));
+ assert "v2".equals(getOnDifferentThread(cache, "k2"));
}
public void testBatchRollback() throws Exception {
- Cache<String, String> cache = null;
- try {
- cache = createCache();
- cache.startBatch();
- cache.put("k", "v");
- cache.put("k2", "v2");
+ Cache cache = createCache("testBatchRollback");
+ cache.startBatch();
+ cache.put("k", "v");
+ cache.put("k2", "v2");
- assert getOnDifferentThread(cache, "k") == null;
- assert getOnDifferentThread(cache, "k2") == null;
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
- cache.endBatch(false);
+ cache.endBatch(false);
- assert getOnDifferentThread(cache, "k") == null;
- assert getOnDifferentThread(cache, "k2") == null;
- }
- finally {
- TestingUtil.killCaches(cache);
- }
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
}
- private Cache<String, String> createCache() {
- UnitTestCacheFactory<String, String> cf = new UnitTestCacheFactory<String, String>();
+ private Cache<String, String> createCache(String name) {
Configuration c = new Configuration();
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
c.setInvocationBatchingEnabled(true);
assert c.getTransactionManagerLookupClass() != null : "Should have a transaction manager lookup class attached!!";
- return cf.createCache(c);
+ cm.defineCache(name, c);
+ return cm.getCache(name);
}
}
Modified: core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTMTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTMTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTMTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,120 +1,110 @@
package org.horizon.api.batch;
import org.horizon.Cache;
-import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
import org.horizon.config.ConfigurationException;
-import org.horizon.util.TestingUtil;
+import org.horizon.manager.CacheManager;
+import org.horizon.test.TestingUtil;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
-@Test(groups = "functional")
+@Test(groups = "functional", testName = "api.batch.BatchWithoutTMTest")
public class BatchWithoutTMTest extends AbstractBatchTest {
+
+ CacheManager cm;
+
+ @BeforeClass
+ public void createCacheManager() {
+ cm = TestingUtil.createLocalCacheManager();
+ }
+
+ @AfterClass
+ public void destroyCacheManager() {
+ TestingUtil.killCacheManagers(cm);
+ }
+
public void testBatchWithoutCfg() {
Cache<String, String> cache = null;
+ cache = createCache(false, "testBatchWithoutCfg");
try {
- cache = createCache(false);
- try {
- cache.startBatch();
- assert false : "Should have failed";
- }
- catch (ConfigurationException good) {
- // do nothing
- }
-
- try {
- cache.endBatch(true);
- assert false : "Should have failed";
- }
- catch (ConfigurationException good) {
- // do nothing
- }
-
- try {
- cache.endBatch(false);
- assert false : "Should have failed";
- }
- catch (ConfigurationException good) {
- // do nothing
- }
+ cache.startBatch();
+ assert false : "Should have failed";
}
- finally {
- TestingUtil.killCaches(cache);
+ catch (ConfigurationException good) {
+ // do nothing
}
- }
- public void testEndBatchWithoutStartBatch() {
- Cache<String, String> cache = null;
try {
- cache = createCache(true);
cache.endBatch(true);
+ assert false : "Should have failed";
+ }
+ catch (ConfigurationException good) {
+ // do nothing
+ }
+
+ try {
cache.endBatch(false);
- // should not fail.
+ assert false : "Should have failed";
}
- finally {
- TestingUtil.killCaches(cache);
+ catch (ConfigurationException good) {
+ // do nothing
}
}
+ public void testEndBatchWithoutStartBatch() {
+ Cache<String, String> cache = null;
+ cache = createCache(true, "testEndBatchWithoutStartBatch");
+ cache.endBatch(true);
+ cache.endBatch(false);
+ // should not fail.
+ }
+
public void testStartBatchIdempotency() {
Cache<String, String> cache = null;
- try {
- cache = createCache(true);
- cache.startBatch();
- cache.put("k", "v");
- cache.startBatch(); // again
- cache.put("k2", "v2");
- cache.endBatch(true);
+ cache = createCache(true, "testStartBatchIdempotency");
+ cache.startBatch();
+ cache.put("k", "v");
+ cache.startBatch(); // again
+ cache.put("k2", "v2");
+ cache.endBatch(true);
- assert "v".equals(cache.get("k"));
- assert "v2".equals(cache.get("k2"));
- }
- finally {
- TestingUtil.killCaches(cache);
- }
+ assert "v".equals(cache.get("k"));
+ assert "v2".equals(cache.get("k2"));
}
public void testBatchVisibility() throws InterruptedException {
Cache<String, String> cache = null;
- try {
- cache = createCache(true);
- cache.startBatch();
- cache.put("k", "v");
- assert getOnDifferentThread(cache, "k") == null : "Other thread should not see batch update till batch completes!";
+ cache = createCache(true, "testBatchVisibility");
+ cache.startBatch();
+ cache.put("k", "v");
+ assert getOnDifferentThread(cache, "k") == null : "Other thread should not see batch update till batch completes!";
- cache.endBatch(true);
+ cache.endBatch(true);
- assert "v".equals(getOnDifferentThread(cache, "k"));
- }
- finally {
- TestingUtil.killCaches(cache);
- }
+ assert "v".equals(getOnDifferentThread(cache, "k"));
}
public void testBatchRollback() throws Exception {
Cache<String, String> cache = null;
- try {
- cache = createCache(true);
- cache.startBatch();
- cache.put("k", "v");
- cache.put("k2", "v2");
+ cache = createCache(true, "testBatchRollback");
+ cache.startBatch();
+ cache.put("k", "v");
+ cache.put("k2", "v2");
- assert getOnDifferentThread(cache, "k") == null;
- assert getOnDifferentThread(cache, "k2") == null;
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
- cache.endBatch(false);
+ cache.endBatch(false);
- assert getOnDifferentThread(cache, "k") == null;
- assert getOnDifferentThread(cache, "k2") == null;
- }
- finally {
- TestingUtil.killCaches(cache);
- }
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
}
- private Cache<String, String> createCache(boolean enableBatch) {
- UnitTestCacheFactory<String, String> cf = new UnitTestCacheFactory<String, String>();
+ private Cache<String, String> createCache(boolean enableBatch, String name) {
Configuration c = new Configuration();
c.setInvocationBatchingEnabled(enableBatch);
- return cf.createCache(c);
+ cm.defineCache(name, c);
+ return cm.getCache(name);
}
}
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/LockAssert.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/LockAssert.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/LockAssert.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -2,7 +2,7 @@
import org.horizon.invocation.InvocationContextContainer;
import org.horizon.lock.LockManager;
-import org.horizon.util.TestingUtil;
+import org.horizon.test.TestingUtil;
import org.horizon.util.concurrent.locks.LockContainer;
/**
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,6 +1,7 @@
package org.horizon.api.mvcc;
import org.horizon.Cache;
+import org.horizon.test.TestingUtil;
import org.horizon.config.Configuration;
import org.horizon.invocation.InvocationContextContainer;
import org.horizon.lock.IsolationLevel;
@@ -11,7 +12,6 @@
import org.horizon.manager.CacheManager;
import org.horizon.manager.DefaultCacheManager;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -23,7 +23,7 @@
/**
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
*/
-@Test(groups = {"functional", "mvcc"}, sequential = true)
+@Test(groups = {"functional", "mvcc"})
public abstract class LockTestBase {
protected boolean repeatableRead = true;
protected boolean lockParentForChildInsertRemove = false;
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -2,25 +2,24 @@
import org.easymock.EasyMock;
import static org.easymock.EasyMock.*;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.commands.RPCCommand;
import org.horizon.commands.write.PutKeyValueCommand;
import org.horizon.commands.write.RemoveCommand;
import org.horizon.config.Configuration;
import org.horizon.invocation.Options;
-import org.horizon.manager.CacheManager;
import org.horizon.remoting.RPCManager;
import org.horizon.remoting.RPCManagerImpl;
import org.horizon.remoting.ResponseFilter;
import org.horizon.remoting.ResponseMode;
import org.horizon.remoting.transport.Address;
import org.horizon.remoting.transport.Transport;
+import org.horizon.test.MultipleCacheManagersTest;
+import org.horizon.test.ReplListener;
+import org.horizon.test.TestingUtil;
import org.horizon.transaction.DummyTransactionManagerLookup;
import org.horizon.transaction.TransactionTable;
-import org.horizon.util.TestingUtil;
import static org.testng.AssertJUnit.*;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.transaction.Transaction;
@@ -28,31 +27,27 @@
import java.util.ArrayList;
import java.util.List;
-@Test(groups = "functional", sequential = true)
-public class PutForExternalReadTest extends BaseClusteredTest {
+@Test(groups = "functional", testName = "api.mvcc.PutForExternalReadTest")
+public class PutForExternalReadTest extends MultipleCacheManagersTest {
final String key = "k", value = "v", value2 = "v2";
Cache cache1, cache2;
TransactionManager tm1, tm2;
ReplListener replListener1, replListener2;
- @BeforeMethod(alwaysRun = true)
- public void setUp() {
+ protected void createCaches() throws Throwable {
Configuration c = new Configuration();
c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- CacheManager cm1 = addClusterEnabledCacheManager();
- CacheManager cm2 = addClusterEnabledCacheManager();
- defineCacheOnAllManagers("replSync", c);
+ createClusteredCaches(2, "replSync", c);
- cache1 = cm1.getCache("replSync");
- cache2 = cm2.getCache("replSync");
+ cache1 = cache(0, "replSync");
+ cache2 = cache(1, "replSync");
tm1 = TestingUtil.getTransactionManager(cache1);
tm2 = TestingUtil.getTransactionManager(cache2);
- TestingUtil.blockUntilViewsReceived(10000, cache1, cache2);
- replListener1 = attachReplicationListener(cache1);
- replListener2 = attachReplicationListener(cache2);
+ replListener1 = replListener(cache1);
+ replListener2 = replListener(cache2);
}
public void testNoOpWhenKeyPresent() {
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/CacheAPIMVCCTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/CacheAPIMVCCTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/CacheAPIMVCCTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -4,10 +4,10 @@
import org.horizon.lock.IsolationLevel;
import org.testng.annotations.Test;
-@Test(groups = "functional")
+@Test(groups = "functional", testName = "api.mvcc.read_committed.CacheAPIMVCCTest")
public class CacheAPIMVCCTest extends CacheAPITest {
@Override
protected IsolationLevel getIsolationLevel() {
return IsolationLevel.READ_COMMITTED;
}
-}
\ No newline at end of file
+}
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/ReadCommittedLockTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/ReadCommittedLockTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/ReadCommittedLockTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -6,7 +6,7 @@
import javax.transaction.Transaction;
-@Test(groups = {"functional", "mvcc"})
+@Test(groups = {"functional", "mvcc"}, testName = "api.mvcc.read_committed.ReadCommittedLockTest")
public class ReadCommittedLockTest extends LockTestBase {
public ReadCommittedLockTest() {
repeatableRead = false;
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/CacheAPIMVCCTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/CacheAPIMVCCTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/CacheAPIMVCCTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -4,7 +4,7 @@
import org.horizon.lock.IsolationLevel;
import org.testng.annotations.Test;
-@Test(groups = "functional")
+@Test(groups = "functional", testName = "api.mvcc.repeatable_read.CacheAPIMVCCTest")
public class CacheAPIMVCCTest extends CacheAPITest {
@Override
protected IsolationLevel getIsolationLevel() {
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/RepeatableReadLockTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/RepeatableReadLockTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/RepeatableReadLockTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -7,7 +7,7 @@
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
-@Test(groups = {"functional", "mvcc"})
+@Test(groups = {"functional", "mvcc"}, testName = "api.mvcc.repeatable_read.RepeatableReadLockTest")
public class RepeatableReadLockTest extends LockTestBase {
public RepeatableReadLockTest() {
repeatableRead = true;
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -9,7 +9,7 @@
import org.horizon.manager.CacheManager;
import org.horizon.manager.DefaultCacheManager;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
+import org.horizon.test.TestingUtil;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@@ -21,7 +21,7 @@
import java.util.Set;
import java.util.concurrent.CountDownLatch;
-@Test(groups = {"functional", "mvcc"}, sequential = true)
+@Test(groups = {"functional", "mvcc"}, testName = "api.mvcc.repeatable_read.WriteSkewTest")
public class WriteSkewTest {
protected TransactionManager tm;
protected LockManager lockManager;
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -8,7 +8,7 @@
import org.horizon.tree.Node;
import org.horizon.tree.TreeCache;
import org.horizon.tree.TreeCacheImpl;
-import org.horizon.util.TestingUtil;
+import org.horizon.test.TestingUtil;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
@@ -25,7 +25,7 @@
*
* @author <a href="mailto:manik AT jboss DOT org">Manik Surtani</a>
*/
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "api.tree.NodeAPITest")
public class NodeAPITest {
static final Fqn A = Fqn.fromString("/a"), B = Fqn.fromString("/b"), C = Fqn.fromString("/c"), D = Fqn.fromString("/d");
Fqn A_B = Fqn.fromRelativeFqn(A, B);
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/NodeLockSupport.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/NodeLockSupport.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeLockSupport.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -24,11 +24,11 @@
package org.horizon.api.tree;
import org.horizon.Cache;
+import org.horizon.test.TestingUtil;
import org.horizon.lock.LockManager;
import org.horizon.tree.Fqn;
import org.horizon.tree.TreeCache;
import org.horizon.tree.TreeStructureSupport;
-import org.horizon.util.TestingUtil;
import javax.transaction.TransactionManager;
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,29 +1,23 @@
package org.horizon.api.tree;
-import org.horizon.Cache;
-import org.horizon.UnitTestCacheFactory;
import org.horizon.api.mvcc.LockAssert;
-import org.horizon.config.CacheLoaderManagerConfig;
import org.horizon.config.Configuration;
-import org.horizon.config.parsing.XmlConfigHelper;
-import org.horizon.config.parsing.element.LoadersElementParser;
import org.horizon.factories.ComponentRegistry;
import org.horizon.invocation.InvocationContextContainer;
import org.horizon.lock.LockManager;
import org.horizon.logging.Log;
import org.horizon.logging.LogFactory;
+import org.horizon.manager.CacheManager;
+import org.horizon.test.SingleCacheManagerTest;
+import org.horizon.test.TestingUtil;
import org.horizon.tree.Fqn;
import org.horizon.tree.Node;
import org.horizon.tree.NodeNotExistsException;
import org.horizon.tree.TreeCache;
import org.horizon.tree.TreeCacheImpl;
import org.horizon.tree.TreeStructureSupport;
-import org.horizon.util.TestingUtil;
import static org.testng.AssertJUnit.*;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import org.w3c.dom.Element;
import javax.transaction.TransactionManager;
import java.util.Random;
@@ -34,8 +28,8 @@
*
* @author <a href="mailto:manik AT jboss DOT org">Manik Surtani</a>
*/
-@Test(groups = {"functional", "pessimistic"}, testName = "api.NodeMoveAPITest")
-public class NodeMoveAPITest {
+@Test(groups = {"functional", "pessimistic"}, testName = "api.tree.NodeMoveAPITest")
+public class NodeMoveAPITest extends SingleCacheManagerTest {
protected final Log log = LogFactory.getLog(getClass());
protected static final Fqn A = Fqn.fromString("/a"), B = Fqn.fromString("/b"), C = Fqn.fromString("/c"), D = Fqn.fromString("/d"), E = Fqn.fromString("/e");
@@ -48,31 +42,23 @@
static final Fqn D_B_C = Fqn.fromRelativeFqn(D_B, C);
protected static final Object k = "key", vA = "valueA", vB = "valueB", vC = "valueC", vD = "valueD", vE = "valueE";
- protected ThreadLocal<TreeCache<Object, Object>> cacheTL = new ThreadLocal<TreeCache<Object, Object>>();
- protected ThreadLocal<TransactionManager> tmTL = new ThreadLocal<TransactionManager>();
+ TreeCache<Object, Object> treeCache;
+ TransactionManager tm;
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception {
- // start a single cache instance
+ protected CacheManager createCacheManager() throws Exception {
+ CacheManager cm = TestingUtil.createLocalCacheManager();
Configuration c = new Configuration();
c.setFetchInMemoryState(false);
c.setInvocationBatchingEnabled(true);
- Cache<Object, Object> cache = new UnitTestCacheFactory<Object, Object>().createCache(c);
-
- cacheTL.set(new TreeCacheImpl<Object, Object>(cache));
- tmTL.set(TestingUtil.getTransactionManager(cache));
+ cm.defineCache("test", c);
+ cache = cm.getCache("test");
+ tm = TestingUtil.extractComponent(cache, TransactionManager.class);
+ treeCache = new TreeCacheImpl(cache);
+ return cm;
}
- @AfterMethod(alwaysRun = true)
- public void tearDown() {
- TestingUtil.killTreeCaches(cacheTL.get());
- cacheTL.set(null);
- }
-
public void testBasicMove() {
- TreeCache<Object, Object> cache = cacheTL.get();
- TransactionManager tm = tmTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
+ Node<Object, Object> rootNode = treeCache.getRoot();
Node<Object, Object> nodeA = rootNode.addChild(A);
nodeA.put(k, vA);
@@ -98,16 +84,16 @@
// parentage
assertEquals(nodeA, nodeC.getParent());
- log.info("BEFORE MOVE " + cache);
+ log.info("BEFORE MOVE " + treeCache);
// move
- cache.move(nodeC.getFqn(), nodeB.getFqn());
+ treeCache.move(nodeC.getFqn(), nodeB.getFqn());
// re-fetch nodeC
- nodeC = cache.getNode(Fqn.fromRelativeFqn(nodeB.getFqn(), C));
+ nodeC = treeCache.getNode(Fqn.fromRelativeFqn(nodeB.getFqn(), C));
- log.info("POST MOVE " + cache);
+ log.info("POST MOVE " + treeCache);
log.info("HC " + nodeC + " " + System.identityHashCode(nodeC));
- Node x = cache.getRoot().getChild(Fqn.fromString("b/c"));
+ Node x = treeCache.getRoot().getChild(Fqn.fromString("b/c"));
log.info("HC " + x + " " + System.identityHashCode(x));
/*
/a
@@ -136,9 +122,7 @@
}
public void testMoveWithChildren() {
- TreeCache<Object, Object> cache = cacheTL.get();
- TransactionManager tm = tmTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
+ Node<Object, Object> rootNode = treeCache.getRoot();
Node<Object, Object> nodeA = rootNode.addChild(A);
nodeA.put(k, vA);
@@ -174,7 +158,7 @@
// move
log.info("move " + nodeC + " to " + nodeB);
- cache.move(nodeC.getFqn(), nodeB.getFqn());
+ treeCache.move(nodeC.getFqn(), nodeB.getFqn());
//System.out.println("nodeB " + nodeB);
//System.out.println("nodeC " + nodeC);
@@ -207,9 +191,7 @@
}
public void testTxCommit() throws Exception {
- TreeCache<Object, Object> cache = cacheTL.get();
- TransactionManager tm = tmTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
+ Node<Object, Object> rootNode = treeCache.getRoot();
Node<Object, Object> nodeA = rootNode.addChild(A);
Node<Object, Object> nodeB = nodeA.addChild(B);
@@ -221,7 +203,7 @@
tm.begin();
// move node B up to hang off the root
- cache.move(nodeB.getFqn(), Fqn.ROOT);
+ treeCache.move(nodeB.getFqn(), Fqn.ROOT);
tm.commit();
@@ -237,9 +219,7 @@
}
public void testTxRollback() throws Exception {
- TreeCache<Object, Object> cache = cacheTL.get();
- TransactionManager tm = tmTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
+ Node<Object, Object> rootNode = treeCache.getRoot();
Node<Object, Object> nodeA = rootNode.addChild(A);
Node<Object, Object> nodeB = nodeA.addChild(B);
@@ -252,11 +232,11 @@
tm.begin();
// move node B up to hang off the root
- System.out.println("Before: " + TreeStructureSupport.printTree(cache, true));
- cache.move(nodeB.getFqn(), Fqn.ROOT);
- System.out.println("After: " + TreeStructureSupport.printTree(cache, true));
+ System.out.println("Before: " + TreeStructureSupport.printTree(treeCache, true));
+ treeCache.move(nodeB.getFqn(), Fqn.ROOT);
+ System.out.println("After: " + TreeStructureSupport.printTree(treeCache, true));
tm.rollback();
- System.out.println("Rolled back: " + TreeStructureSupport.printTree(cache, true));
+ System.out.println("Rolled back: " + TreeStructureSupport.printTree(treeCache, true));
nodeA = rootNode.getChild(A);
nodeB = nodeA.getChild(B);
@@ -268,115 +248,8 @@
assertEquals(nodeB, nodeA.getChildren().iterator().next());
}
- /*
- public void testWithCacheloaders() throws Exception
- {
- doCacheLoaderTest(false, false);
- }
-
- public void testWithPassivation() throws Exception
- {
- doCacheLoaderTest(true, false);
- }
-
- public void testWithCacheloadersTx() throws Exception
- {
- doCacheLoaderTest(false, true);
- }
-
- public void testWithPassivationTx() throws Exception
- {
- doCacheLoaderTest(true, true);
- }
- */
-
- /*
-protected void doCacheLoaderTest(boolean pasv, boolean useTx) throws Exception
-{
-TreeCache<Object, Object> cache = cacheTL.get();
-TransactionManager tm = tmTL.get();
-Node<Object, Object> rootNode = cache.getRoot();
-
-cache.destroy();
-cache.getConfiguration().setCacheLoaderConfig(getSingleCacheLoaderConfig(pasv, "/", DummyInMemoryCacheLoader.class.getName(), "debug=true", false, false, false, false));
-cache.start();
-
-DummyInMemoryCacheLoader loaderold = (DummyInMemoryCacheLoader) cache.getCacheLoaderManager().getCacheLoader();
-
-rootNode.put("key", "value");
-
-if (!pasv)
-{
-Map m = loaderold.get(Fqn.ROOT);
-assertNotNull("Should not be null", m);
-assertEquals("value", m.get("key"));
-}
-
-Node<Object, Object> nodeA = rootNode.addChild(A);
-nodeA.put(k, vA);
-Node<Object, Object> nodeB = rootNode.addChild(B);
-nodeB.put(k, vB);
-Node<Object, Object> nodeC = nodeA.addChild(C);
-nodeC.put(k, vC);
-Node<Object, Object> nodeD = nodeC.addChild(D);
-nodeD.put(k, vD);
-Node<Object, Object> nodeE = nodeD.addChild(E);
-nodeE.put(k, vE);
-cache.evict(Fqn.ROOT, true);
-
-// move
-if (useTx) tm.begin();
-cache.move(nodeC.getFqn(), nodeB.getFqn());
-if (useTx) tm.commit();
-
-// after eviction, the node objects we hold are probably stale.
-nodeA = rootNode.getChild(A);
-nodeB = rootNode.getChild(B);
-nodeC = nodeB.getChild(C);
-log.info("nodeC get child B ");
-nodeD = nodeC.getChild(D);
-log.info("nodeD get child E ");
-nodeE = nodeD.getChild(E);
-
-Fqn old_C = C;
-Fqn old_D = Fqn.fromRelativeFqn(old_C, D);
-Fqn old_E = Fqn.fromRelativeFqn(old_D, E);
-
-// test data
-assertEquals(vA, nodeA.get(k));
-assertEquals(vB, nodeB.get(k));
-assertEquals(vC, nodeC.get(k));
-assertEquals(vD, nodeD.get(k));
-assertEquals(vE, nodeE.get(k));
-
-// parentage
-assertEquals(rootNode, nodeA.getParent());
-assertEquals(rootNode, nodeB.getParent());
-assertEquals(nodeB, nodeC.getParent());
-assertEquals(nodeC, nodeD.getParent());
-assertEquals(nodeD, nodeE.getParent());
-
-
-if (pasv) cache.evict(Fqn.ROOT, true);
-
-//now inspect the loaderold.
-assertEquals(vA, loaderold.get(nodeA.getFqn()).get(k));
-assertEquals(vB, loaderold.get(nodeB.getFqn()).get(k));
-assertEquals(vC, loaderold.get(nodeC.getFqn()).get(k));
-assertEquals(vD, loaderold.get(nodeD.getFqn()).get(k));
-assertEquals(vE, loaderold.get(nodeE.getFqn()).get(k));
-
-assertNull(loaderold.get(old_C));
-assertNull(loaderold.get(old_D));
-assertNull(loaderold.get(old_E));
-
-}
- */
-
public void testLocksDeepMove() throws Exception {
- TreeCache<Object, Object> cache = cacheTL.get();
- TransactionManager tm = tmTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
+ Node<Object, Object> rootNode = treeCache.getRoot();
Node<Object, Object> nodeA = rootNode.addChild(A);
Node<Object, Object> nodeB = nodeA.addChild(B);
@@ -386,7 +259,7 @@
assertNoLocks();
tm.begin();
- cache.move(nodeC.getFqn(), nodeB.getFqn());
+ treeCache.move(nodeC.getFqn(), nodeB.getFqn());
checkLocksDeep();
@@ -397,9 +270,7 @@
}
public void testLocks() throws Exception {
- TreeCache<Object, Object> cache = cacheTL.get();
- TransactionManager tm = tmTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
+ Node<Object, Object> rootNode = treeCache.getRoot();
Node<Object, Object> nodeA = rootNode.addChild(A);
Node<Object, Object> nodeB = nodeA.addChild(B);
@@ -407,7 +278,7 @@
assertNoLocks();
tm.begin();
- cache.move(nodeC.getFqn(), nodeB.getFqn());
+ treeCache.move(nodeC.getFqn(), nodeB.getFqn());
checkLocks();
@@ -416,8 +287,7 @@
}
public void testConcurrency() throws InterruptedException {
- final TreeCache<Object, Object> cache = cacheTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
+ Node<Object, Object> rootNode = treeCache.getRoot();
final int N = 3;// number of threads
final int loops = 1 << 6;// number of loops
@@ -460,14 +330,14 @@
System.out.println(getName() + ": Attempt " + counter);
try {
- cache.move(NODE_X.getFqn(), NODES[r.nextInt(NODES.length)].getFqn());
+ treeCache.move(NODE_X.getFqn(), NODES[r.nextInt(NODES.length)].getFqn());
}
catch (NodeNotExistsException e) {
// this may happen ...
}
TestingUtil.sleepRandom(250);
try {
- cache.move(NODE_Y.getFqn(), NODES[r.nextInt(NODES.length)].getFqn());
+ treeCache.move(NODE_Y.getFqn(), NODES[r.nextInt(NODES.length)].getFqn());
}
catch (NodeNotExistsException e) {
// this may happen ...
@@ -512,55 +382,31 @@
}
public void testMoveInSamePlace() {
- TreeCache<Object, Object> cache = cacheTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
+ Node<Object, Object> rootNode = treeCache.getRoot();
final Fqn FQN_X = Fqn.fromString("/x");
// set up the initial structure.
Node aNode = rootNode.addChild(A);
Node xNode = aNode.addChild(FQN_X);
assertEquals(aNode.getChildren().size(), 1);
- System.out.println("Before: " + TreeStructureSupport.printTree(cache, true));
+ System.out.println("Before: " + TreeStructureSupport.printTree(treeCache, true));
- cache.move(xNode.getFqn(), aNode.getFqn());
+ treeCache.move(xNode.getFqn(), aNode.getFqn());
- System.out.println("After: " + TreeStructureSupport.printTree(cache, true));
+ System.out.println("After: " + TreeStructureSupport.printTree(treeCache, true));
assertEquals(aNode.getChildren().size(), 1);
assertNoLocks();
}
- protected CacheLoaderManagerConfig getSingleCacheLoaderConfig(boolean passivation, String preload, String cacheloaderClass, String properties, boolean async, boolean fetchPersistentState, boolean shared, boolean purgeOnStartup) throws Exception {
- String xml =
- " <loaders passivation=\"" + passivation + "\" shared=\"" + shared + "\">\n" +
- " <preload>\n" +
- " <node fqn=\"" + preload + "\"/>\n" +
- " </preload>\n" +
- " <loader class=\"" + cacheloaderClass + "\" async=\"" + async + "\" fetchPersistentState=\"" + fetchPersistentState + "\"\n" +
- " purgeOnStartup=\"" + purgeOnStartup + "\">\n" +
- " <properties>\n" +
- properties +
- " </properties>\n" +
- " </loader>\n" +
- " </loaders>";
- Element element = XmlConfigHelper.stringToElementInCoreNS(xml);
- LoadersElementParser elementParser = new LoadersElementParser();
- return elementParser.parseLoadersElement(element);
- }
-
protected void checkLocks() {
- TreeCache<Object, Object> tree = cacheTL.get();
- Cache<Object, Object> cache = tree.getCache();
LockManager lm = TestingUtil.extractLockManager(cache);
assert TreeStructureSupport.isLocked(cache, lm, C);
assert TreeStructureSupport.isLocked(cache, lm, A_B_C);
}
protected void checkLocksDeep() {
- TreeCache<Object, Object> tree = cacheTL.get();
- Cache<Object, Object> cache = tree.getCache();
LockManager lm = TestingUtil.extractLockManager(cache);
// /a/b, /c, /c/e, /a/b/c and /a/b/c/e should all be locked.
@@ -571,48 +417,45 @@
}
protected void assertNoLocks() {
- TreeCache<Object, Object> cache = cacheTL.get();
- ComponentRegistry cr = TestingUtil.extractComponentRegistry(cache.getCache());
+ ComponentRegistry cr = TestingUtil.extractComponentRegistry(cache);
LockManager lm = cr.getComponent(LockManager.class);
InvocationContextContainer icc = cr.getComponent(InvocationContextContainer.class);
LockAssert.assertNoLocks(lm, icc);
}
public void testNonexistentSource() {
- TreeCache<Object, Object> cache = cacheTL.get();
- cache.put(A_B_C, "k", "v");
- assert "v".equals(cache.get(A_B_C, "k"));
- assert 1 == cache.getNode(A_B).getChildren().size();
- assert cache.getNode(A_B).getChildrenNames().contains(C.getLastElement());
- assert !cache.getNode(A_B).getChildrenNames().contains(D.getLastElement());
+ treeCache.put(A_B_C, "k", "v");
+ assert "v".equals(treeCache.get(A_B_C, "k"));
+ assert 1 == treeCache.getNode(A_B).getChildren().size();
+ assert treeCache.getNode(A_B).getChildrenNames().contains(C.getLastElement());
+ assert !treeCache.getNode(A_B).getChildrenNames().contains(D.getLastElement());
- cache.move(D, A_B);
+ treeCache.move(D, A_B);
- assert "v".equals(cache.get(A_B_C, "k"));
- assert 1 == cache.getNode(A_B).getChildren().size();
- assert cache.getNode(A_B).getChildrenNames().contains(C.getLastElement());
- assert !cache.getNode(A_B).getChildrenNames().contains(D.getLastElement());
+ assert "v".equals(treeCache.get(A_B_C, "k"));
+ assert 1 == treeCache.getNode(A_B).getChildren().size();
+ assert treeCache.getNode(A_B).getChildrenNames().contains(C.getLastElement());
+ assert !treeCache.getNode(A_B).getChildrenNames().contains(D.getLastElement());
}
public void testNonexistentTarget() {
- TreeCache<Object, Object> cache = cacheTL.get();
- cache.put(A_B_C, "k", "v");
- assert "v".equals(cache.get(A_B_C, "k"));
- assert 1 == cache.getNode(A_B).getChildren().size();
- assert cache.getNode(A_B).getChildrenNames().contains(C.getLastElement());
- assert null == cache.getNode(D);
+ treeCache.put(A_B_C, "k", "v");
+ assert "v".equals(treeCache.get(A_B_C, "k"));
+ assert 1 == treeCache.getNode(A_B).getChildren().size();
+ assert treeCache.getNode(A_B).getChildrenNames().contains(C.getLastElement());
+ assert null == treeCache.getNode(D);
- System.out.println(TreeStructureSupport.printTree(cache, true));
+ System.out.println(TreeStructureSupport.printTree(treeCache, true));
- cache.move(A_B, D);
+ treeCache.move(A_B, D);
- System.out.println(TreeStructureSupport.printTree(cache, true));
+ System.out.println(TreeStructureSupport.printTree(treeCache, true));
- assert null == cache.getNode(A_B_C);
- assert null == cache.getNode(A_B);
- assert null != cache.getNode(D);
- assert null != cache.getNode(D_B);
- assert null != cache.getNode(D_B_C);
- assert "v".equals(cache.get(D_B_C, "k"));
+ assert null == treeCache.getNode(A_B_C);
+ assert null == treeCache.getNode(A_B);
+ assert null != treeCache.getNode(D);
+ assert null != treeCache.getNode(D_B);
+ assert null != treeCache.getNode(D_B_C);
+ assert "v".equals(treeCache.get(D_B_C, "k"));
}
}
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -6,25 +6,23 @@
*/
package org.horizon.api.tree;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.config.Configuration;
-import org.horizon.manager.CacheManager;
+import org.horizon.test.MultipleCacheManagersTest;
+import org.horizon.test.TestingUtil;
import org.horizon.transaction.DummyTransactionManagerLookup;
import org.horizon.tree.Fqn;
import org.horizon.tree.Node;
import org.horizon.tree.TreeCache;
import org.horizon.tree.TreeCacheImpl;
-import org.horizon.util.TestingUtil;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.transaction.TransactionManager;
-@Test(groups = "functional", sequential = true, testName = "api.NodeReplicatedMoveTest")
-public class NodeReplicatedMoveTest extends BaseClusteredTest {
+@Test(groups = "functional", testName = "api.tree.NodeReplicatedMoveTest")
+public class NodeReplicatedMoveTest extends MultipleCacheManagersTest {
static final Fqn A = Fqn.fromString("/a"), B = Fqn.fromString("/b"), C = Fqn.fromString("/c"), D = Fqn.fromString("/d"), E = Fqn.fromString("/e");
static final Object k = "key", vA = "valueA", vB = "valueB", vC = "valueC", vD = "valueD", vE = "valueE";
@@ -32,8 +30,7 @@
TreeCache<Object, Object> cache1, cache2;
TransactionManager tm1;
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception {
+ protected void createCaches() throws Throwable {
Configuration c = new Configuration();
c.setInvocationBatchingEnabled(true);
c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
@@ -41,16 +38,12 @@
c.setSyncCommitPhase(true);
c.setSyncRollbackPhase(true);
- CacheManager cm1 = addClusterEnabledCacheManager();
- CacheManager cm2 = addClusterEnabledCacheManager();
+ createClusteredCaches(2, "replSync", c);
- defineCacheOnAllManagers("replSync", c);
+ Cache c1 = cache(0, "replSync");
+ Cache c2 = cache(1, "replSync");
- Cache c1 = cm1.getCache("replSync");
- Cache c2 = cm2.getCache("replSync");
-
tm1 = TestingUtil.getTransactionManager(c1);
- TestingUtil.blockUntilViewsReceived(10000, cm1, cm2);
cache1 = new TreeCacheImpl<Object, Object>(c1);
cache2 = new TreeCacheImpl<Object, Object>(c2);
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -7,18 +7,15 @@
package org.horizon.api.tree;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.config.Configuration;
import org.horizon.invocation.Options;
-import org.horizon.manager.CacheManager;
+import org.horizon.test.MultipleCacheManagersTest;
import org.horizon.tree.Fqn;
import org.horizon.tree.Node;
import org.horizon.tree.TreeCache;
import org.horizon.tree.TreeCacheImpl;
-import org.horizon.util.TestingUtil;
import static org.testng.AssertJUnit.*;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.HashMap;
@@ -27,27 +24,21 @@
/**
* @author <a href="mailto:manik AT jboss DOT org">Manik Surtani (manik AT jboss DOT org)</a>
*/
-@Test(groups = "functional", sequential = true, testName = "api.SyncReplTest")
-public class SyncReplTest extends BaseClusteredTest {
+@Test(groups = "functional", testName = "api.tree.SyncReplTest")
+public class SyncReplTest extends MultipleCacheManagersTest {
private TreeCache<Object, Object> cache1, cache2;
- @BeforeMethod(alwaysRun = true)
- public void setUp() {
+ protected void createCaches() throws Throwable {
Configuration c = new Configuration();
c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
c.setInvocationBatchingEnabled(true);
c.setFetchInMemoryState(false);
- CacheManager cm1 = addClusterEnabledCacheManager();
- CacheManager cm2 = addClusterEnabledCacheManager();
+ createClusteredCaches(2, "replSync", c);
- defineCacheOnAllManagers("replSync", c);
+ Cache c1 = cache(0, "replSync");
+ Cache c2 = cache(1, "replSync");
- Cache c1 = cm1.getCache("replSync");
- Cache c2 = cm2.getCache("replSync");
-
- TestingUtil.blockUntilViewsReceived(new Cache[]{c1, c2}, 5000);
-
cache1 = new TreeCacheImpl<Object, Object>(c1);
cache2 = new TreeCacheImpl<Object, Object>(c2);
}
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -7,18 +7,16 @@
package org.horizon.api.tree;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.config.Configuration;
-import org.horizon.manager.CacheManager;
+import org.horizon.test.MultipleCacheManagersTest;
+import org.horizon.test.TestingUtil;
import org.horizon.transaction.DummyTransactionManagerLookup;
import org.horizon.tree.Fqn;
import org.horizon.tree.Node;
import org.horizon.tree.TreeCache;
import org.horizon.tree.TreeCacheImpl;
-import org.horizon.util.TestingUtil;
import static org.testng.AssertJUnit.*;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.transaction.HeuristicMixedException;
@@ -31,12 +29,11 @@
/**
* @author <a href="mailto:manik AT jboss DOT org">Manik Surtani (manik AT jboss DOT org)</a>
*/
-@Test(groups = "functional", sequential = true, testName = "api.SyncReplTxTest")
-public class SyncReplTxTest extends BaseClusteredTest {
+@Test(groups = "functional", testName = "api.tree.SyncReplTxTest")
+public class SyncReplTxTest extends MultipleCacheManagersTest {
TreeCache<Object, Object> cache1, cache2;
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws CloneNotSupportedException {
+ protected void createCaches() throws Throwable {
Configuration c = new Configuration();
c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
c.setFetchInMemoryState(false);
@@ -45,16 +42,11 @@
c.setSyncRollbackPhase(true);
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- CacheManager cm1 = addClusterEnabledCacheManager();
- CacheManager cm2 = addClusterEnabledCacheManager();
+ createClusteredCaches(2, "replSync", c);
- defineCacheOnAllManagers("replSync", c);
+ Cache c1 = cache(0, "replSync");
+ Cache c2 = cache(1, "replSync");
- Cache c1 = cm1.getCache("replSync");
- Cache c2 = cm2.getCache("replSync");
-
- TestingUtil.blockUntilViewsReceived(10000, cm1, cm2);
-
cache1 = new TreeCacheImpl<Object, Object>(c1);
cache2 = new TreeCacheImpl<Object, Object>(c2);
}
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -8,7 +8,7 @@
import org.horizon.tree.Node;
import org.horizon.tree.TreeCache;
import org.horizon.tree.TreeCacheImpl;
-import org.horizon.util.TestingUtil;
+import org.horizon.test.TestingUtil;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
@@ -24,7 +24,7 @@
* @author <a href="mailto:manik AT jboss DOT org">Manik Surtani</a>
*/
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "api.tree.TreeCacheAPITest")
public class TreeCacheAPITest {
private TreeCache<String, String> cache;
private TransactionManager tm;
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/TreeStructureHashCodeTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/TreeStructureHashCodeTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/TreeStructureHashCodeTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -15,8 +15,9 @@
/**
* Tests the degree to which hash codes get spread
*/
-@Test
+@Test (groups = "unit" , testName = "api.tree.TreeStructureHashCodeTest")
public class TreeStructureHashCodeTest {
+
public void testHashCodesAppendedCount() {
List<Fqn> fqns = new ArrayList<Fqn>();
fqns.add(Fqn.ROOT);
Modified: core/branches/flat/src/test/java/org/horizon/atomic/APITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/atomic/APITest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/atomic/APITest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -25,8 +25,8 @@
import static org.horizon.atomic.AtomicHashMapTestAssertions.assertIsEmptyMap;
import org.horizon.config.Configuration;
import org.horizon.manager.DefaultCacheManager;
+import org.horizon.test.TestingUtil;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
@@ -36,7 +36,7 @@
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "atomic.APITest")
public class APITest {
AtomicMapCache cache;
Modified: core/branches/flat/src/test/java/org/horizon/atomic/AtomicHashMapTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/atomic/AtomicHashMapTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/atomic/AtomicHashMapTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -29,7 +29,7 @@
import java.io.IOException;
import java.io.ObjectOutput;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "atomic.AtomicHashMapTest")
public class AtomicHashMapTest {
public void testDeltasWithEmptyMap() throws IOException {
AtomicHashMap m = new AtomicHashMap();
Modified: core/branches/flat/src/test/java/org/horizon/atomic/ClusteredAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/atomic/ClusteredAPITest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/atomic/ClusteredAPITest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,25 +1,24 @@
package org.horizon.atomic;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import static org.horizon.atomic.AtomicHashMapTestAssertions.assertIsEmpty;
import static org.horizon.atomic.AtomicHashMapTestAssertions.assertIsEmptyMap;
import org.horizon.config.Configuration;
+import org.horizon.container.DataContainer;
+import org.horizon.test.MultipleCacheManagersTest;
+import org.horizon.test.TestingUtil;
import org.horizon.transaction.DummyTransactionManager;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
-@Test(groups = "functional", sequential = true)
-public class ClusteredAPITest extends BaseClusteredTest {
+@Test(groups = "functional", testName = "atomic.ClusteredAPITest")
+public class ClusteredAPITest extends MultipleCacheManagersTest {
AtomicMapCache cache1, cache2;
- @BeforeMethod
- public void setUp() {
+ protected void createCaches() throws Throwable {
Configuration c = new Configuration();
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
@@ -28,7 +27,6 @@
List<Cache> caches = createClusteredCaches(2, "atomic", c);
cache1 = (AtomicMapCache) caches.get(0);
cache2 = (AtomicMapCache) caches.get(1);
- TestingUtil.blockUntilViewsReceived(20000, cache1, cache2);
}
public void testReplicationCommit() throws Exception {
@@ -51,6 +49,10 @@
}
public void testReplicationRollback() throws Exception {
+ System.out.println("ClusteredAPITest.testReplicationRollback");
+ DataContainer dataContainer = TestingUtil.extractComponent(cache2, DataContainer.class);
+ System.out.println("dataContainer = " + dataContainer);
+ assertIsEmptyMap(cache2, "map");
AtomicMap map = cache1.getAtomicMap("map");
DummyTransactionManager.getInstance().begin();
Modified: core/branches/flat/src/test/java/org/horizon/config/parsing/ConfigurationParserTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/config/parsing/ConfigurationParserTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/config/parsing/ConfigurationParserTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -14,7 +14,7 @@
import org.testng.annotations.Test;
import org.w3c.dom.Element;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "config.parsing.ConfigurationParserTest")
public class ConfigurationParserTest {
public void testLocking() throws Exception {
Modified: core/branches/flat/src/test/java/org/horizon/config/parsing/GlobalConfigurationParserTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/config/parsing/GlobalConfigurationParserTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/config/parsing/GlobalConfigurationParserTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -10,7 +10,7 @@
import org.w3c.dom.Element;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "config.parsing.GlobalConfigurationParserTest")
public class GlobalConfigurationParserTest {
public void testTransport() throws Exception {
Modified: core/branches/flat/src/test/java/org/horizon/config/parsing/XmlFileParsingTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/config/parsing/XmlFileParsingTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/config/parsing/XmlFileParsingTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -8,7 +8,7 @@
import java.io.IOException;
import java.util.Map;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "config.parsing.XmlFileParsingTest")
public class XmlFileParsingTest {
public void testNamedCacheFile() throws IOException {
XmlConfigurationParser parser = new XmlConfigurationParserImpl("configs/named-cache-test.xml");
Modified: core/branches/flat/src/test/java/org/horizon/container/DataContainerTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/container/DataContainerTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/container/DataContainerTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -5,12 +5,12 @@
import java.util.HashSet;
import java.util.Set;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "container.DataContainerTest")
public class DataContainerTest {
public void testExpiredData() throws InterruptedException {
DataContainer dc = new UnsortedDataContainer();
dc.put("k", "v", -1);
- Thread.sleep(1);
+ Thread.sleep(100);
assert dc.getModifiedTimestamp("k") <= System.currentTimeMillis();
@@ -18,7 +18,7 @@
assert dc.purgeExpiredEntries().isEmpty();
dc.put("k", "v", 0);
- Thread.sleep(1);
+ Thread.sleep(100);
assert dc.size() == 1;
assert dc.getModifiedTimestamp("k") <= System.currentTimeMillis();
@@ -26,7 +26,7 @@
assert dc.size() == 0;
dc.put("k", "v", 0);
- Thread.sleep(1);
+ Thread.sleep(100);
assert dc.size() == 1;
assert dc.getModifiedTimestamp("k") <= System.currentTimeMillis();
Modified: core/branches/flat/src/test/java/org/horizon/eviction/EvictionFunctionalTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/eviction/EvictionFunctionalTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/eviction/EvictionFunctionalTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,6 +1,7 @@
package org.horizon.eviction;
import org.horizon.Cache;
+import org.horizon.test.TestingUtil;
import org.horizon.config.Configuration;
import org.horizon.config.EvictionConfig;
import org.horizon.container.DataContainer;
@@ -9,7 +10,6 @@
import org.horizon.manager.CacheManager;
import org.horizon.manager.DefaultCacheManager;
import org.horizon.util.ReflectionUtil;
-import org.horizon.util.TestingUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -18,7 +18,7 @@
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "eviction.EvictionFunctionalTest")
public class EvictionFunctionalTest {
Cache cache;
Modified: core/branches/flat/src/test/java/org/horizon/eviction/EvictionManagerTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/eviction/EvictionManagerTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/eviction/EvictionManagerTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -14,7 +14,7 @@
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "eviction.EvictionManagerTest")
public class EvictionManagerTest {
private Configuration getCfg() {
Modified: core/branches/flat/src/test/java/org/horizon/eviction/algorithms/fifo/FifoAlgorithmTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/eviction/algorithms/fifo/FifoAlgorithmTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/eviction/algorithms/fifo/FifoAlgorithmTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -3,7 +3,7 @@
import org.horizon.eviction.algorithms.BaseAlgorithmTest;
import org.testng.annotations.Test;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "eviction.algorithms.fifo.FifoAlgorithmTest")
public class FifoAlgorithmTest extends BaseAlgorithmTest {
protected FIFOAlgorithmConfig getNewEvictionAlgorithmConfig() {
return new FIFOAlgorithmConfig();
Modified: core/branches/flat/src/test/java/org/horizon/eviction/algorithms/fifo/FifoQueueTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/eviction/algorithms/fifo/FifoQueueTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/eviction/algorithms/fifo/FifoQueueTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -6,7 +6,7 @@
import java.util.Iterator;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "eviction.algorithms.fifo.FifoQueueTest")
public class FifoQueueTest extends BaseQueueTest {
public void testOrder() throws Exception {
Modified: core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lfu/LfuAlgorithmTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lfu/LfuAlgorithmTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lfu/LfuAlgorithmTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -3,7 +3,7 @@
import org.horizon.eviction.algorithms.BaseAlgorithmTest;
import org.testng.annotations.Test;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "eviction.algorithms.lfu.LfuAlgorithmTest")
public class LfuAlgorithmTest extends BaseAlgorithmTest {
@Override
protected boolean timeOrderedQueue() {
Modified: core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lfu/LfuQueueTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lfu/LfuQueueTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lfu/LfuQueueTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -8,7 +8,7 @@
import java.util.Iterator;
import java.util.Set;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "eviction.algorithms.lfu.LfuQueueTest")
public class LfuQueueTest extends BaseQueueTest {
@Override
Modified: core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lru/LruAlgorithmTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lru/LruAlgorithmTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lru/LruAlgorithmTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -3,7 +3,7 @@
import org.horizon.eviction.algorithms.BaseAlgorithmTest;
import org.testng.annotations.Test;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "eviction.algorithms.lru.LruAlgorithmTest")
public class LruAlgorithmTest extends BaseAlgorithmTest {
protected LRUAlgorithmConfig getNewEvictionAlgorithmConfig() {
return new LRUAlgorithmConfig();
Modified: core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lru/LruQueueTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lru/LruQueueTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/eviction/algorithms/lru/LruQueueTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -6,7 +6,7 @@
import java.util.Iterator;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "eviction.algorithms.lru.LruQueueTest")
public class LruQueueTest extends BaseQueueTest {
protected EvictionQueue getNewEvictionQueue() {
return new LRUQueue();
Modified: core/branches/flat/src/test/java/org/horizon/eviction/algorithms/mru/MruAlgorithmTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/eviction/algorithms/mru/MruAlgorithmTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/eviction/algorithms/mru/MruAlgorithmTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -3,7 +3,7 @@
import org.horizon.eviction.algorithms.BaseAlgorithmTest;
import org.testng.annotations.Test;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "eviction.algorithms.mru.MruAlgorithmTest")
public class MruAlgorithmTest extends BaseAlgorithmTest {
protected MRUAlgorithmConfig getNewEvictionAlgorithmConfig() {
return new MRUAlgorithmConfig();
Modified: core/branches/flat/src/test/java/org/horizon/eviction/algorithms/mru/MruQueueTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/eviction/algorithms/mru/MruQueueTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/eviction/algorithms/mru/MruQueueTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -5,7 +5,7 @@
import java.util.Iterator;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "eviction.algorithms.mru.MruQueueTest")
public class MruQueueTest extends BaseQueueTest {
protected MRUQueue getNewEvictionQueue() {
return new MRUQueue();
Modified: core/branches/flat/src/test/java/org/horizon/expiry/ExpiryTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/expiry/ExpiryTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/expiry/ExpiryTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -5,7 +5,7 @@
import org.horizon.loader.StoredEntry;
import org.horizon.manager.CacheManager;
import org.horizon.manager.DefaultCacheManager;
-import org.horizon.util.TestingUtil;
+import org.horizon.test.TestingUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -14,7 +14,7 @@
import java.util.Map;
import java.util.concurrent.TimeUnit;
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "expiry.ExpiryTest")
public class ExpiryTest {
CacheManager cm;
Modified: core/branches/flat/src/test/java/org/horizon/expiry/ReplicatedExpiryTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/expiry/ReplicatedExpiryTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/expiry/ReplicatedExpiryTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,21 +1,19 @@
package org.horizon.expiry;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.config.Configuration;
-import org.testng.annotations.BeforeMethod;
+import org.horizon.test.MultipleCacheManagersTest;
import org.testng.annotations.Test;
import java.util.List;
import java.util.concurrent.TimeUnit;
-@Test(groups = "functional", sequential = true)
-public class ReplicatedExpiryTest extends BaseClusteredTest {
+@Test(groups = "functional", testName = "expiry.ReplicatedExpiryTest")
+public class ReplicatedExpiryTest extends MultipleCacheManagersTest {
Cache c1, c2;
- @BeforeMethod
- public void setUp() {
+ protected void createCaches() throws Throwable {
Configuration cfg = new Configuration();
cfg.setCacheMode(Configuration.CacheMode.REPL_SYNC);
List<Cache> caches = createClusteredCaches(2, "cache", cfg);
@@ -25,18 +23,16 @@
public void testExpiryReplicates() throws InterruptedException {
long start = System.currentTimeMillis();
- long lifespan = 10000;
+ long lifespan = 3000;
c1.put("k", "v", lifespan, TimeUnit.MILLISECONDS);
- while (System.currentTimeMillis() < start + lifespan + 1000) {
- if (System.currentTimeMillis() < start + lifespan) {
- assert c1.get("k").equals("v");
- assert c2.get("k").equals("v");
- } else {
- assert c1.get("k") == null;
- assert c2.get("k") == null;
- }
+ while (System.currentTimeMillis() < start + lifespan) {
+ assert c1.get("k").equals("v");
+ assert c2.get("k").equals("v");
Thread.sleep(250);
}
+ Thread.sleep(1000);
+ assert c1.get("k") == null;
+ assert c2.get("k") == null;
}
}
Modified: core/branches/flat/src/test/java/org/horizon/factories/scopes/ScopeDetectorTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/factories/scopes/ScopeDetectorTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/factories/scopes/ScopeDetectorTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -6,7 +6,7 @@
* @author Manik Surtani
* @since 1.0
*/
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "factories.scopes.ScopeDetectorTest")
public class ScopeDetectorTest {
public void testScopeOnClass() {
testScopes(Test1.class, Scopes.GLOBAL);
Modified: core/branches/flat/src/test/java/org/horizon/interceptors/MarshalledValueInterceptorTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/interceptors/MarshalledValueInterceptorTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/interceptors/MarshalledValueInterceptorTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,12 +1,12 @@
package org.horizon.interceptors;
import org.horizon.Cache;
+import org.horizon.test.TestingUtil;
import org.horizon.config.Configuration;
import org.horizon.config.GlobalConfiguration;
import org.horizon.manager.CacheManager;
import org.horizon.manager.DefaultCacheManager;
import org.horizon.marshall.MarshalledValue;
-import org.horizon.util.TestingUtil;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@@ -21,7 +21,7 @@
* @author Mircea.Markus(a)jboss.com
* @since 1.0
*/
-@Test(groups = "functional", sequential = true, testName = "interceptors.MarshalledValueInterceptorTest")
+@Test(groups = "functional", testName = "interceptors.MarshalledValueInterceptorTest")
public class MarshalledValueInterceptorTest {
CacheManager cm;
Modified: core/branches/flat/src/test/java/org/horizon/invalidation/AsyncInvalidationTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/invalidation/AsyncInvalidationTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/invalidation/AsyncInvalidationTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -2,7 +2,7 @@
import org.testng.annotations.Test;
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "invalidation.AsyncInvalidationTest")
public class AsyncInvalidationTest extends BaseInvalidationTest {
public AsyncInvalidationTest() {
isSync = false;
Modified: core/branches/flat/src/test/java/org/horizon/invalidation/BaseInvalidationTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/invalidation/BaseInvalidationTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/invalidation/BaseInvalidationTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -2,7 +2,6 @@
import static org.easymock.EasyMock.*;
import org.horizon.AdvancedCache;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.commands.RPCCommand;
import org.horizon.commands.write.ClearCommand;
@@ -15,10 +14,10 @@
import org.horizon.remoting.ResponseMode;
import org.horizon.remoting.transport.Address;
import org.horizon.remoting.transport.Transport;
+import org.horizon.test.MultipleCacheManagersTest;
+import org.horizon.test.TestingUtil;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
import static org.testng.AssertJUnit.*;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.transaction.RollbackException;
@@ -27,13 +26,12 @@
import java.util.ArrayList;
import java.util.List;
-@Test(groups = "functional", sequential = true)
-public abstract class BaseInvalidationTest extends BaseClusteredTest {
+@Test(groups = "functional")
+public abstract class BaseInvalidationTest extends MultipleCacheManagersTest {
protected AdvancedCache cache1, cache2;
protected boolean isSync;
- @BeforeMethod
- public void setUp() {
+ protected void createCaches() throws Throwable {
Configuration c = new Configuration();
c.setStateRetrievalTimeout(1000);
c.setFetchInMemoryState(false);
@@ -42,7 +40,6 @@
List<Cache> caches = createClusteredCaches(2, "invalidation", c);
cache1 = caches.get(0).getAdvancedCache();
cache2 = caches.get(1).getAdvancedCache();
- TestingUtil.blockUntilViewsReceived(10000, cache1, cache2);
}
public void testRemove() throws Exception {
@@ -51,48 +48,45 @@
cache2.put("key", "value", Options.CACHE_MODE_LOCAL);
assertEquals("value", cache2.get("key"));
- ReplListener rl = attachReplicationListener(cache2);
- rl.expectAny();
+ replListener(cache2).expectAny();
assertEquals("value", cache1.remove("key"));
- rl.waitForRPC();
+ replListener(cache2).waitForRPC();
assertEquals(false, cache2.containsKey("key"));
}
public void testResurrectEntry() throws Exception {
- ReplListener r2 = attachReplicationListener(cache2);
- r2.expect(InvalidateCommand.class);
+ replListener(cache2).expect(InvalidateCommand.class);
cache1.put("key", "value");
- r2.waitForRPC();
+ replListener(cache2).waitForRPC();
assertEquals("value", cache1.get("key"));
assertEquals(null, cache2.get("key"));
- r2.expect(InvalidateCommand.class);
+ replListener(cache2).expect(InvalidateCommand.class);
cache1.put("key", "newValue");
- r2.waitForRPC();
+ replListener(cache2).waitForRPC();
assertEquals("newValue", cache1.get("key"));
assertEquals(null, cache2.get("key"));
- r2.expect(InvalidateCommand.class);
+ replListener(cache2).expect(InvalidateCommand.class);
assertEquals("newValue", cache1.remove("key"));
- r2.waitForRPC();
+ replListener(cache2).waitForRPC();
assertEquals(null, cache1.get("key"));
assertEquals(null, cache2.get("key"));
// Restore locally
- r2.expect(InvalidateCommand.class);
+ replListener(cache2).expect(InvalidateCommand.class);
cache1.put("key", "value");
- r2.waitForRPC();
+ replListener(cache2).waitForRPC();
assertEquals("value", cache1.get("key"));
assertEquals(null, cache2.get("key"));
- ReplListener r1 = attachReplicationListener(cache1);
- r1.expect(InvalidateCommand.class);
+ replListener(cache1).expect(InvalidateCommand.class);
cache2.put("key", "value2");
- r1.waitForRPC();
+ replListener(cache1).waitForRPC();
assertEquals("value2", cache2.get("key"));
assertEquals(null, cache1.get("key"));
@@ -102,23 +96,21 @@
assertNull("Should be null", cache1.get("key"));
assertNull("Should be null", cache2.get("key"));
- ReplListener rl2 = attachReplicationListener(cache2);
- rl2.expect(InvalidateCommand.class);
+ replListener(cache2).expect(InvalidateCommand.class);
cache1.put("key", "value");
- rl2.waitForRPC();
+ replListener(cache2).waitForRPC();
assertEquals("value", cache1.get("key"));
assertNull("Should be null", cache2.get("key"));
// OK, here's the real test
TransactionManager tm = TestingUtil.getTransactionManager(cache2);
- ReplListener rl1 = attachReplicationListener(cache1);
- rl1.expect(InvalidateCommand.class); // invalidates always happen outside of a tx
+ replListener(cache1).expect(InvalidateCommand.class); // invalidates always happen outside of a tx
tm.begin();
// Remove an entry that doesn't exist in cache2
cache2.remove("key");
tm.commit();
- rl1.waitForRPC();
+ replListener(cache1).waitForRPC();
assert cache1.get("key") == null;
assert cache2.get("key") == null;
@@ -197,10 +189,9 @@
assert cache2.get("key").equals("value");
assert cache1.get("key") == null;
- ReplListener r = attachReplicationListener(cache2);
- r.expect(InvalidateCommand.class);
+ replListener(cache2).expect(InvalidateCommand.class);
cache1.putIfAbsent("key", "value");
- r.waitForRPC();
+ replListener(cache2).waitForRPC();
assert cache1.get("key").equals("value");
assert cache2.get("key") == null;
@@ -227,10 +218,9 @@
assert cache1.get("key").equals("value1") : "Should not remove";
assert cache2.get("key").equals("value2") : "Should not evict";
- ReplListener r = attachReplicationListener(cache2);
- r.expect(InvalidateCommand.class);
+ replListener(cache2).expect(InvalidateCommand.class);
cache1.remove("key", "value1");
- r.waitForRPC();
+ replListener(cache2).waitForRPC();
assert cache1.get("key") == null;
assert cache2.get("key") == null;
@@ -242,10 +232,9 @@
assert cache1.get("key").equals("value1");
assert cache2.get("key").equals("value2");
- ReplListener r = attachReplicationListener(cache2);
- r.expect(ClearCommand.class);
+ replListener(cache2).expect(ClearCommand.class);
cache1.clear();
- r.waitForRPC();
+ replListener(cache2).waitForRPC();
assert cache1.get("key") == null;
assert cache2.get("key") == null;
@@ -263,10 +252,9 @@
cache1.put("key", "valueN", Options.CACHE_MODE_LOCAL);
- ReplListener r = attachReplicationListener(cache2);
- r.expect(InvalidateCommand.class);
+ replListener(cache2).expect(InvalidateCommand.class);
cache1.replace("key", "value1");
- r.waitForRPC();
+ replListener(cache2).waitForRPC();
assert cache1.get("key").equals("value1");
assert cache2.get("key") == null;
@@ -289,10 +277,9 @@
assert cache1.get("key").equals("valueN");
assert cache2.get("key").equals("value2");
- ReplListener r = attachReplicationListener(cache2);
- r.expect(InvalidateCommand.class);
+ replListener(cache2).expect(InvalidateCommand.class);
cache1.replace("key", "valueN", "value1");
- r.waitForRPC();
+ replListener(cache2).waitForRPC();
assert cache1.get("key").equals("value1");
assert cache2.get("key") == null;
Modified: core/branches/flat/src/test/java/org/horizon/invalidation/SyncInvalidationTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/invalidation/SyncInvalidationTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/invalidation/SyncInvalidationTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -2,7 +2,7 @@
import org.testng.annotations.Test;
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "invalidation.SyncInvalidationTest")
public class SyncInvalidationTest extends BaseInvalidationTest {
public SyncInvalidationTest() {
isSync = true;
Modified: core/branches/flat/src/test/java/org/horizon/loader/BaseCacheLoaderTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/loader/BaseCacheLoaderTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/loader/BaseCacheLoaderTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -19,7 +19,7 @@
import java.util.List;
import java.util.Set;
-@Test(groups = "unit", sequential = true)
+@Test(groups = "unit")
@SuppressWarnings("unchecked")
public abstract class BaseCacheLoaderTest {
@@ -67,7 +67,7 @@
lifespan = 1;
se = new StoredEntry("k", "v", now, now + lifespan);
cs.store(se);
- Thread.sleep(2);
+ Thread.sleep(100);
assert se.isExpired();
assert cs.load("k") == null;
assert !cs.containsKey("k");
Modified: core/branches/flat/src/test/java/org/horizon/loader/CacheLoaderFunctionalTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/loader/CacheLoaderFunctionalTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/loader/CacheLoaderFunctionalTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -8,8 +8,8 @@
import org.horizon.loader.dummy.DummyInMemoryCacheLoader;
import org.horizon.manager.CacheManager;
import org.horizon.manager.DefaultCacheManager;
+import org.horizon.test.TestingUtil;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
@@ -25,7 +25,7 @@
*
* @author Manik Surtani
*/
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "loader.CacheLoaderFunctionalTest")
public class CacheLoaderFunctionalTest {
Cache cache;
CacheStore store;
Modified: core/branches/flat/src/test/java/org/horizon/loader/decorators/AsyncTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/loader/decorators/AsyncTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/loader/decorators/AsyncTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -3,7 +3,7 @@
import org.horizon.CacheException;
import org.horizon.loader.StoredEntry;
import org.horizon.loader.dummy.DummyInMemoryCacheLoader;
-import org.horizon.util.TestingUtil;
+import org.horizon.test.TestingUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
@@ -11,7 +11,7 @@
import java.util.concurrent.ExecutorService;
-@Test(groups = "unit", sequential = true)
+@Test(groups = "unit", testName = "loader.decorators.AsyncTest")
public class AsyncTest {
AsyncStore store;
Modified: core/branches/flat/src/test/java/org/horizon/loader/decorators/ReadOnlyCacheStoreTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/loader/decorators/ReadOnlyCacheStoreTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/loader/decorators/ReadOnlyCacheStoreTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -7,7 +7,7 @@
import java.io.InputStream;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "loader.decorators.ReadOnlyCacheStoreTest")
public class ReadOnlyCacheStoreTest {
public void testWriteMethods() {
CacheStore mock = createMock(CacheStore.class);
Modified: core/branches/flat/src/test/java/org/horizon/loader/decorators/SingletonStoreTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/loader/decorators/SingletonStoreTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/loader/decorators/SingletonStoreTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -2,7 +2,6 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.config.CacheLoaderManagerConfig;
import org.horizon.config.Configuration;
@@ -11,10 +10,11 @@
import org.horizon.loader.StoredEntry;
import org.horizon.loader.dummy.DummyInMemoryCacheLoader;
import org.horizon.manager.CacheManager;
-import org.horizon.util.TestingUtil;
+import org.horizon.test.TestingUtil;
import org.horizon.util.internals.ViewChangeListener;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.fail;
+import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -30,17 +30,17 @@
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
-@Test(groups = "functional", sequential = true)
-public class SingletonStoreTest extends BaseClusteredTest {
+@Test(groups = "functional", testName = "loader.decorators.SingletonStoreTest")
+public class SingletonStoreTest {
private static final Log log = LogFactory.getLog(SingletonStoreTest.class);
private static final AtomicInteger storeCounter = new AtomicInteger(0);
private CacheManager cm0, cm1, cm2;
@BeforeMethod
- public void setUp() {
- cm0 = addClusterEnabledCacheManager();
- cm1 = addClusterEnabledCacheManager();
- cm2 = addClusterEnabledCacheManager();
+ protected void setUp() throws Throwable {
+ cm0 = TestingUtil.createClusteredCacheManager();
+ cm1 = TestingUtil.createClusteredCacheManager();
+ cm2 = TestingUtil.createClusteredCacheManager();
Configuration conf = new Configuration();
conf.setCacheMode(Configuration.CacheMode.REPL_SYNC);
@@ -81,9 +81,18 @@
cm2.defineCache("nonPushing", conf);
}
+ @AfterMethod
+ public void tearDown() {
+ TestingUtil.killCacheManagers(cm0, cm1, cm2);
+ }
+
private Cache[] getCaches(String name) {
+ Cache cache = cm0.getCache(name);
+ Cache cache1 = cm1.getCache(name);
+ Cache cache2 = cm2.getCache(name);
+ TestingUtil.blockUntilViewsReceived(10000, cm0, cm1, cm2);
return new Cache[]{
- cm0.getCache(name), cm1.getCache(name), cm2.getCache(name)
+ cache, cache1, cache2
};
}
@@ -127,7 +136,7 @@
}
cm0.stop();
- TestingUtil.blockUntilViewsReceived(60000, cm1, cm2);
+ TestingUtil.blockForMemberToFail(60000, cm1, cm2);
caches[1].put("key4", "value4");
caches[2].put("key5", "value5");
@@ -139,7 +148,7 @@
assert load(stores[2], "key5") == null;
cm1.stop();
- TestingUtil.blockUntilViewsReceived(60000, cm2);
+ TestingUtil.blockForMemberToFail(10000, cm2);
caches[2].put("key6", "value6");
assert load(stores[2], "key6").equals("value6");
Modified: core/branches/flat/src/test/java/org/horizon/loader/dummy/DummyInMemoryCacheLoaderTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/loader/dummy/DummyInMemoryCacheLoaderTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/loader/dummy/DummyInMemoryCacheLoaderTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -4,7 +4,7 @@
import org.horizon.loader.CacheStore;
import org.testng.annotations.Test;
-@Test(groups = "unit", sequential = true)
+@Test(groups = "unit", testName = "loader.dummy.DummyInMemoryCacheLoaderTest")
public class DummyInMemoryCacheLoaderTest extends BaseCacheLoaderTest {
protected CacheStore createCacheStore() {
Modified: core/branches/flat/src/test/java/org/horizon/lock/LockContainerHashingTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/lock/LockContainerHashingTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/lock/LockContainerHashingTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -33,7 +33,7 @@
import java.util.Random;
import java.util.concurrent.locks.Lock;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "lock.LockContainerHashingTest")
public class LockContainerHashingTest {
private LockContainer<String> stripedLock;
Modified: core/branches/flat/src/test/java/org/horizon/manager/CacheManagerComponentRegistryTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/manager/CacheManagerComponentRegistryTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/manager/CacheManagerComponentRegistryTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,6 +1,7 @@
package org.horizon.manager;
import org.horizon.Cache;
+import org.horizon.test.TestingUtil;
import org.horizon.config.Configuration;
import org.horizon.config.EvictionConfig;
import org.horizon.config.GlobalConfiguration;
@@ -11,7 +12,6 @@
import org.horizon.remoting.RPCManager;
import org.horizon.transaction.DummyTransactionManager;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
@@ -21,7 +21,7 @@
* @author Manik Surtani
* @since 1.0
*/
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "manager.CacheManagerComponentRegistryTest")
public class CacheManagerComponentRegistryTest {
DefaultCacheManager cm;
Modified: core/branches/flat/src/test/java/org/horizon/manager/CacheManagerTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/manager/CacheManagerTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/manager/CacheManagerTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,17 +1,17 @@
package org.horizon.manager;
import org.horizon.Cache;
+import org.horizon.test.TestingUtil;
import org.horizon.config.Configuration;
import org.horizon.config.DuplicateCacheNameException;
import org.horizon.lifecycle.ComponentStatus;
-import org.horizon.util.TestingUtil;
import org.testng.annotations.Test;
/**
* @author Manik Surtani
* @since 1.0
*/
-@Test(groups = "functional")
+@Test(groups = "functional", testName = "manager.CacheManagerTest")
public class CacheManagerTest {
public void testDefaultCache() {
CacheManager cm = new DefaultCacheManager();
Modified: core/branches/flat/src/test/java/org/horizon/manager/CacheManagerXmlConfigurationTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/manager/CacheManagerXmlConfigurationTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/manager/CacheManagerXmlConfigurationTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,10 +1,10 @@
package org.horizon.manager;
import org.horizon.Cache;
+import org.horizon.test.TestingUtil;
import org.horizon.config.Configuration;
import org.horizon.config.DuplicateCacheNameException;
import org.horizon.remoting.RPCManager;
-import org.horizon.util.TestingUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
@@ -16,7 +16,7 @@
* @author Manik Surtani
* @since 1.0
*/
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "manager.CacheManagerXmlConfigurationTest")
public class CacheManagerXmlConfigurationTest {
DefaultCacheManager cm;
Modified: core/branches/flat/src/test/java/org/horizon/marshall/MarshalledValueTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/marshall/MarshalledValueTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/marshall/MarshalledValueTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,9 +1,8 @@
package org.horizon.marshall;
-import org.horizon.AdvancedCache;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.CacheException;
+import org.horizon.AdvancedCache;
import org.horizon.commands.write.PutKeyValueCommand;
import org.horizon.config.CacheLoaderManagerConfig;
import org.horizon.config.Configuration;
@@ -14,11 +13,11 @@
import org.horizon.interceptors.base.CommandInterceptor;
import org.horizon.loader.CacheLoaderConfig;
import org.horizon.loader.dummy.DummyInMemoryCacheLoader;
-import org.horizon.manager.CacheManager;
import org.horizon.notifications.Listener;
import org.horizon.notifications.cachelistener.annotation.CacheEntryModified;
import org.horizon.notifications.cachelistener.event.CacheEntryModifiedEvent;
-import org.horizon.util.TestingUtil;
+import org.horizon.test.MultipleCacheManagersTest;
+import org.horizon.test.TestingUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -41,32 +40,23 @@
* @since 1.0
*/
@Test(groups = "functional", testName = "marshall.MarshalledValueTest")
-public class MarshalledValueTest extends BaseClusteredTest {
+public class MarshalledValueTest extends MultipleCacheManagersTest {
private Cache cache1, cache2;
private MarshalledValueListenerInterceptor mvli;
String k = "key", v = "value";
- @BeforeMethod(alwaysRun = true)
- public void setUp() {
- CacheManager cm1 = addClusterEnabledCacheManager();
- CacheManager cm2 = addClusterEnabledCacheManager();
-
+ protected void createCaches() throws Throwable {
Configuration replSync = new Configuration();
replSync.setCacheMode(Configuration.CacheMode.REPL_SYNC);
replSync.setUseLazyDeserialization(true);
- defineCacheOnAllManagers("replSync", replSync);
+ createClusteredCaches(2, "replSync", replSync);
- cache1 = cm1.getCache("replSync");
- cache2 = cm2.getCache("replSync");
+ cache1 = cache(0, "replSync");
+ cache2 = cache(1, "replSync");
assertMarshalledValueInterceptorPresent(cache1);
assertMarshalledValueInterceptorPresent(cache2);
-
- mvli = new MarshalledValueListenerInterceptor();
- ((AdvancedCache)cache1).addInterceptorAfter(mvli, MarshalledValueInterceptor.class);
-
- TestingUtil.blockUntilViewsReceived(60000, true, cm1, cm2);
}
private void assertMarshalledValueInterceptorPresent(Cache c) {
@@ -74,9 +64,14 @@
assert ic1.containsInterceptorType(MarshalledValueInterceptor.class);
}
+ @BeforeMethod
+ public void addMarshalledValueInterceptor() {
+ mvli = new MarshalledValueListenerInterceptor();
+ ((AdvancedCache)cache1).addInterceptorAfter(mvli, MarshalledValueInterceptor.class);
+ }
+
@AfterMethod
public void tearDown() {
- TestingUtil.killCaches(cache1, cache2);
Pojo.serializationCount = 0;
Pojo.deserializationCount = 0;
}
@@ -266,11 +261,9 @@
cacheCofig.setCacheLoaderConfig(clmc);
defineCacheOnAllManagers("replSync2", cacheCofig);
- cache1 = getCacheManagers().get(0).getCache("replSync2");
- cache2 = getCacheManagers().get(1).getCache("replSync2");
+ cache1 = cache(0, "replSync2");
+ cache2 = cache(1, "replSync2");
- TestingUtil.blockUntilViewsReceived(60000, cache1, cache2);
-
Pojo pojo = new Pojo();
cache1.put("key", pojo);
Modified: core/branches/flat/src/test/java/org/horizon/notifications/AsyncNotificationTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/notifications/AsyncNotificationTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/notifications/AsyncNotificationTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -5,14 +5,14 @@
import org.horizon.manager.DefaultCacheManager;
import org.horizon.notifications.cachelistener.annotation.CacheEntryCreated;
import org.horizon.notifications.cachelistener.event.CacheEntryCreatedEvent;
-import org.horizon.util.TestingUtil;
+import org.horizon.test.TestingUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.concurrent.CountDownLatch;
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "notifications.AsyncNotificationTest")
public class AsyncNotificationTest {
Cache<String, String> c;
CacheManager cm;
Modified: core/branches/flat/src/test/java/org/horizon/notifications/CacheListenerCacheLoaderTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/notifications/CacheListenerCacheLoaderTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/notifications/CacheListenerCacheLoaderTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -2,7 +2,7 @@
import org.testng.annotations.Test;
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "notifications.CacheListenerCacheLoaderTest")
public class CacheListenerCacheLoaderTest {
// TODO implement me!
// private Cache<Object, Object> cache;
@@ -24,7 +24,7 @@
// clc.setPassivation(true);
//
// c.setCacheLoaderConfig(clc);
-// cache = new UnitTestCacheFactory<Object, Object>().createCache(c, getClass());
+// cache = new UnitTestCacheFactory<Object, Object>().createCacheManager(c, getClass());
// eventLog.events.clear();
// cache.addCacheListener(eventLog);
// tm = cache.getConfiguration().getRuntimeConfig().getTransactionManager();
@@ -181,4 +181,4 @@
// assert cache.get(fqn, "key").equals("value");
// assert cache.get(fqn, "key2").equals("value2");
// }
-}
\ No newline at end of file
+}
Modified: core/branches/flat/src/test/java/org/horizon/notifications/CacheListenerPassivationTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/notifications/CacheListenerPassivationTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/notifications/CacheListenerPassivationTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -2,7 +2,7 @@
import org.testng.annotations.Test;
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "notifications.CacheListenerPassivationTest")
public class CacheListenerPassivationTest {
// TODO implement me!
// private Cache<Object, Object> cache;
@@ -24,7 +24,7 @@
// clc.setPassivation(true);
//
// c.setCacheLoaderConfig(clc);
-// cache = new UnitTestCacheFactory<Object, Object>().createCache(c, getClass());
+// cache = new UnitTestCacheFactory<Object, Object>().createCacheManager(c, getClass());
// eventLog.events.clear();
// cache.addCacheListener(eventLog);
// tm = cache.getConfiguration().getRuntimeConfig().getTransactionManager();
Modified: core/branches/flat/src/test/java/org/horizon/notifications/CacheListenerRemovalTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/notifications/CacheListenerRemovalTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/notifications/CacheListenerRemovalTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -5,7 +5,7 @@
import org.horizon.manager.DefaultCacheManager;
import org.horizon.notifications.cachelistener.annotation.CacheEntryVisited;
import org.horizon.notifications.cachelistener.event.Event;
-import org.horizon.util.TestingUtil;
+import org.horizon.test.TestingUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -15,7 +15,7 @@
/**
* @author Manik Surtani
*/
-@Test(groups = "functional")
+@Test(groups = "functional", testName = "notifications.CacheListenerRemovalTest")
public class CacheListenerRemovalTest {
Cache<String, String> cache;
CacheManager cm;
@@ -43,7 +43,7 @@
cache.get("x");
assert 1 == i.get();
- // remove the listener
+ // remove the replListener
cache.removeListener(l);
assert 0 == cache.getListeners().size();
i.set(0);
Modified: core/branches/flat/src/test/java/org/horizon/notifications/ConcurrentNotificationTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/notifications/ConcurrentNotificationTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/notifications/ConcurrentNotificationTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,6 +1,7 @@
package org.horizon.notifications;
import org.horizon.Cache;
+import org.horizon.test.TestingUtil;
import org.horizon.logging.Log;
import org.horizon.logging.LogFactory;
import org.horizon.manager.CacheManager;
@@ -10,7 +11,6 @@
import org.horizon.notifications.cachelistener.annotation.CacheEntryRemoved;
import org.horizon.notifications.cachelistener.annotation.CacheEntryVisited;
import org.horizon.notifications.cachelistener.event.Event;
-import org.horizon.util.TestingUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -20,7 +20,7 @@
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
-@Test(groups = "functional", sequential = true, testName = "notifications.ConcurrentNotificationTest")
+@Test(groups = "functional", testName = "notifications.ConcurrentNotificationTest")
public class ConcurrentNotificationTest {
Cache<String, String> cache;
CacheManager cm;
@@ -91,7 +91,7 @@
for (Exception e : exceptions)
throw e;
- // we cannot ascertain the exact number of invocations on the listener since some removes would mean that other
+ // we cannot ascertain the exact number of invocations on the replListener since some removes would mean that other
// gets would miss. And this would cause no notification to fire for that get. And we cannot be sure of the
// timing between removes and gets, so we just make sure *some* of these have got through, and no exceptions
// were thrown due to concurrent access.
Modified: core/branches/flat/src/test/java/org/horizon/notifications/cachelistener/CacheNotifierImplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/notifications/cachelistener/CacheNotifierImplTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/notifications/cachelistener/CacheNotifierImplTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -18,7 +18,7 @@
import javax.transaction.Transaction;
-@Test(groups = "unit", sequential = true)
+@Test(groups = "unit", testName = "notifications.cachelistener.CacheNotifierImplTest")
public class CacheNotifierImplTest {
CacheNotifierImpl n;
Cache mockCache;
Modified: core/branches/flat/src/test/java/org/horizon/notifications/cachelistener/CacheNotifierTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/notifications/cachelistener/CacheNotifierTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/notifications/cachelistener/CacheNotifierTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -2,13 +2,13 @@
import static org.easymock.EasyMock.*;
import org.horizon.Cache;
+import org.horizon.test.TestingUtil;
import org.horizon.config.Configuration;
import org.horizon.context.InvocationContext;
import org.horizon.lock.IsolationLevel;
import org.horizon.manager.CacheManager;
import org.horizon.manager.DefaultCacheManager;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -19,7 +19,7 @@
import java.util.HashMap;
import java.util.Map;
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "notifications.cachelistener.CacheNotifierTest")
public class CacheNotifierTest {
private Cache<Object, Object> cache;
private TransactionManager tm;
Modified: core/branches/flat/src/test/java/org/horizon/notifications/cachelistener/ListenerRegistrationTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/notifications/cachelistener/ListenerRegistrationTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/notifications/cachelistener/ListenerRegistrationTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -11,7 +11,7 @@
import java.util.List;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "notifications.cachelistener.ListenerRegistrationTest")
public class ListenerRegistrationTest {
public void testControl() {
Object l = new TestControlListener();
Modified: core/branches/flat/src/test/java/org/horizon/notifications/cachemanagerlistener/CacheManagerNotifierImplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/notifications/cachemanagerlistener/CacheManagerNotifierImplTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/notifications/cachemanagerlistener/CacheManagerNotifierImplTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -12,7 +12,7 @@
import java.util.Collections;
import java.util.List;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "notifications.cachemanagerlistener.CacheManagerNotifierImplTest")
public class CacheManagerNotifierImplTest {
CacheManagerNotifierImpl n;
CacheManagerListener cl;
Modified: core/branches/flat/src/test/java/org/horizon/notifications/cachemanagerlistener/CacheManagerNotifierTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/notifications/cachemanagerlistener/CacheManagerNotifierTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/notifications/cachemanagerlistener/CacheManagerNotifierTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,27 +1,38 @@
package org.horizon.notifications.cachemanagerlistener;
import static org.easymock.EasyMock.*;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.config.Configuration;
import org.horizon.config.GlobalConfiguration;
import org.horizon.manager.CacheManager;
+import org.horizon.manager.DefaultCacheManager;
import org.horizon.remoting.transport.Address;
-import org.horizon.util.TestingUtil;
+import org.horizon.test.TestingUtil;
+import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import java.util.List;
-@Test(groups = "unit", sequential = true, testName = "notifications.CacheManagerNotifierTest")
-public class CacheManagerNotifierTest extends BaseClusteredTest {
+@Test(groups = "unit", testName = "notifications.cachemanagerlistener.CacheManagerNotifierTest")
+public class CacheManagerNotifierTest {
+ CacheManager cm1;
+ CacheManager cm2;
+
+ @AfterMethod
+ public void tearDown()
+ {
+ TestingUtil.killCacheManagers(cm1, cm2);
+ }
+
public void testViewChange() {
- CacheManager cm1 = addClusterEnabledCacheManager();
- CacheManager cm2 = addClusterEnabledCacheManager();
+ cm1 = TestingUtil.createClusteredCacheManager();
+ cm2 = TestingUtil.createClusteredCacheManager();
Configuration c = new Configuration();
c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
- defineCacheOnAllManagers("cache", c);
+ cm1.defineCache("cache", c);
+ cm2.defineCache("cache", c);
- Cache c1 = cm1.getCache("cache");
+ cm1.getCache("cache");
// this will mean only 1 cache in the cluster so far
assert cm1.getMembers().size() == 1;
@@ -45,8 +56,8 @@
}
public void testCacheStartedAndStopped() {
- CacheManager cm1 = addCacheManager(GlobalConfiguration.getNonClusteredDefault());
- Cache defCache = cm1.getCache();
+ cm1 = new DefaultCacheManager(GlobalConfiguration.getNonClusteredDefault());
+ cm1.getCache();
CacheManagerNotifier mockNotifier = createMock(CacheManagerNotifier.class);
CacheManagerNotifier origNotifier = TestingUtil.replaceComponent(cm1, CacheManagerNotifier.class, mockNotifier, true);
try {
Modified: core/branches/flat/src/test/java/org/horizon/profiling/AbstractProfileTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/AbstractProfileTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/profiling/AbstractProfileTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,28 +1,18 @@
package org.horizon.profiling;
-import org.horizon.Cache;
-import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
-import org.horizon.util.TestingUtil;
-import org.testng.annotations.AfterTest;
-import org.testng.annotations.BeforeTest;
+import org.horizon.manager.CacheManager;
+import org.horizon.manager.DefaultCacheManager;
+import org.horizon.test.SingleCacheManagerTest;
import org.testng.annotations.Test;
-import java.util.Map;
+@Test(groups = "profiling", enabled = false, testName = "profiling.SingleCacheManagerTest")
+public abstract class AbstractProfileTest extends SingleCacheManagerTest {
-@Test(groups = "profiling")
-public abstract class AbstractProfileTest {
- protected Map cache;
-
- @BeforeTest
- public void setUp() {
+ protected CacheManager createCacheManager() throws Exception {
Configuration cfg = new Configuration();
- cache = new UnitTestCacheFactory().createCache(cfg, false);
+ cacheManager = new DefaultCacheManager(cfg);
+ cache = cacheManager.getCache();
+ return cacheManager;
}
-
- @AfterTest
- public void tearDown() {
- TestingUtil.killCaches((Cache) cache);
- cache = null;
- }
}
Modified: core/branches/flat/src/test/java/org/horizon/profiling/MemConsumptionTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/MemConsumptionTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/profiling/MemConsumptionTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -24,7 +24,7 @@
import org.horizon.Cache;
import org.horizon.CacheException;
import org.horizon.manager.DefaultCacheManager;
-import org.horizon.util.TestingUtil;
+import org.horizon.test.TestingUtil;
import org.testng.annotations.Test;
import java.io.IOException;
@@ -32,7 +32,7 @@
import java.util.Arrays;
import java.util.Random;
-@Test(groups = "profiling", enabled = false)
+@Test(groups = "profiling", enabled = false, testName = "profiling.MemConsumptionTest")
public class MemConsumptionTest {
// adjust the next 4 values
int numEntries = 1000000;
Modified: core/branches/flat/src/test/java/org/horizon/profiling/ProfileTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/ProfileTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/profiling/ProfileTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,13 +1,13 @@
package org.horizon.profiling;
import org.horizon.Cache;
+import org.horizon.test.TestingUtil;
import org.horizon.config.Configuration;
import org.horizon.lock.IsolationLevel;
import org.horizon.logging.Log;
import org.horizon.logging.LogFactory;
import org.horizon.profiling.testinternals.Generator;
import org.horizon.profiling.testinternals.TaskRunner;
-import org.horizon.util.TestingUtil;
import org.testng.annotations.Test;
import java.util.ArrayList;
@@ -26,7 +26,7 @@
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
*/
-@Test(groups = "profiling", sequential = true, enabled = false)
+@Test(groups = "profiling", enabled = false, testName = "profiling.ProfileTest")
public class ProfileTest extends AbstractProfileTest {
/*
Test configuration options
@@ -42,7 +42,7 @@
Log log = LogFactory.getLog(ProfileTest.class);
- @Test(enabled = true)
+ @Test(enabled = false)
public void testLocalMode() throws Exception {
Cache c = (Cache) cache;
c.getConfiguration().setCacheMode(Configuration.CacheMode.LOCAL);
Modified: core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,20 +1,21 @@
package org.horizon.profiling;
import org.horizon.Cache;
-import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
import org.horizon.lock.IsolationLevel;
import org.horizon.logging.Log;
import org.horizon.logging.LogFactory;
+import org.horizon.manager.CacheManager;
+import org.horizon.manager.DefaultCacheManager;
import org.horizon.profiling.testinternals.Generator;
import org.horizon.profiling.testinternals.TaskRunner;
+import org.horizon.test.TestingUtil;
import org.horizon.transaction.DummyTransactionManager;
import org.horizon.tree.Fqn;
import org.horizon.tree.TreeCache;
import org.horizon.tree.TreeCacheImpl;
-import org.horizon.util.TestingUtil;
-import org.testng.annotations.AfterTest;
-import org.testng.annotations.BeforeTest;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
@@ -33,9 +34,11 @@
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
*/
-@Test(groups = "profiling", sequential = true, enabled = false)
+@Test(groups = "profiling", testName = "profiling.TreeProfileTest", enabled = false)
public class TreeProfileTest {
- /*
+ Log log = LogFactory.getLog(TreeProfileTest.class);
+
+ /**
Test configuration options
*/
protected static final long NUM_OPERATIONS = 1000000; // DURATION is replaced with a fixed number of operations instead.
@@ -44,11 +47,14 @@
protected static final int MAX_DEPTH = 3;
protected static final int MAX_OVERALL_NODES = 2000;
protected static final int WARMUP_LOOPS = 20000;
+
protected static final boolean USE_SLEEP = false; // throttle generation a bit
+ private CacheManager cacheManager;
+
protected TreeCache cache;
- @BeforeTest
+ @BeforeMethod
public void setUp() {
Configuration cfg = new Configuration();
cfg.setInvocationBatchingEnabled(true);
@@ -56,20 +62,19 @@
cfg.setConcurrencyLevel(2000);
cfg.setLockAcquisitionTimeout(120000);
cfg.setIsolationLevel(IsolationLevel.READ_COMMITTED);
- Cache c = new UnitTestCacheFactory().createCache(cfg);
+ cacheManager = new DefaultCacheManager(cfg);
+ Cache c = cacheManager.getCache();
cache = new TreeCacheImpl(c);
}
- @AfterTest
+ @AfterMethod
public void tearDown() {
TestingUtil.killTreeCaches(cache);
- cache = null;
+ TestingUtil.killCacheManagers(cacheManager);
}
private List<Fqn> fqns = new ArrayList<Fqn>(MAX_OVERALL_NODES);
- Log log = LogFactory.getLog(TreeProfileTest.class);
-
public void testLocalMode() throws Exception {
runCompleteTest();
}
Modified: core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -8,13 +8,12 @@
package org.horizon.replication;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.config.Configuration;
+import org.horizon.test.MultipleCacheManagersTest;
+import org.horizon.test.TestingUtil;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
import static org.testng.AssertJUnit.assertEquals;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.transaction.TransactionManager;
@@ -24,70 +23,63 @@
/**
* Unit test for replicated async CacheSPI. Use locking and multiple threads to test concurrent access to the tree.
*/
-@Test(groups = "functional", sequential = true)
-public class AsyncReplTest extends BaseClusteredTest {
+@Test(groups = "functional", testName = "replication.AsyncReplTest")
+public class AsyncReplTest extends MultipleCacheManagersTest {
Cache cache1, cache2;
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception {
+ protected void createCaches() throws Throwable {
Configuration asyncConfiguration = new Configuration();
asyncConfiguration.setCacheMode(Configuration.CacheMode.REPL_ASYNC);
asyncConfiguration.setSyncCommitPhase(true);
asyncConfiguration.setSyncRollbackPhase(true);
asyncConfiguration.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
-
List<Cache> caches = createClusteredCaches(2, "asyncRepl", asyncConfiguration);
-
cache1 = caches.get(0);
cache2 = caches.get(1);
}
public void testWithNoTx() throws Exception {
- ReplListener replListener2 = attachReplicationListener(cache2);
String key = "key";
- replListener2.expectAny();
+ replListener(cache2).expectAny();
cache1.put(key, "value1");
// allow for replication
- replListener2.waitForRPC(60, TimeUnit.SECONDS);
+ replListener(cache2).waitForRPC(60, TimeUnit.SECONDS);
assertEquals("value1", cache1.get(key));
assertEquals("value1", cache2.get(key));
- replListener2.expectAny();
+ replListener(cache2).expectAny();
cache1.put(key, "value2");
assertEquals("value2", cache1.get(key));
- replListener2.waitForRPC(60, TimeUnit.SECONDS);
+ replListener(cache2).waitForRPC(60, TimeUnit.SECONDS);
assertEquals("value2", cache1.get(key));
assertEquals("value2", cache2.get(key));
}
public void testWithTx() throws Exception {
- ReplListener replListener2 = attachReplicationListener(cache2);
-
String key = "key";
-
- replListener2.expectAny();
+ replListener(cache2).expectAny();
cache1.put(key, "value1");
// allow for replication
- replListener2.waitForRPC(60, TimeUnit.SECONDS);
+ replListener(cache2).waitForRPC(60, TimeUnit.SECONDS);
assertEquals("value1", cache1.get(key));
assertEquals("value1", cache2.get(key));
TransactionManager mgr = TestingUtil.getTransactionManager(cache1);
mgr.begin();
- replListener2.expectAnyWithTx();
+ replListener(cache2).expectAnyWithTx();
cache1.put(key, "value2");
assertEquals("value2", cache1.get(key));
assertEquals("value1", cache2.get(key));
mgr.commit();
- replListener2.waitForRPC(60, TimeUnit.SECONDS);
+ replListener(cache2).waitForRPC(60, TimeUnit.SECONDS);
assertEquals("value2", cache1.get(key));
assertEquals("value2", cache2.get(key));
Modified: core/branches/flat/src/test/java/org/horizon/replication/AsyncReplicatedAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/AsyncReplicatedAPITest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/replication/AsyncReplicatedAPITest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -2,7 +2,7 @@
import org.testng.annotations.Test;
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "replication.AsyncReplicatedAPITest")
public class AsyncReplicatedAPITest extends BaseReplicatedAPITest {
public AsyncReplicatedAPITest() {
isSync = false;
Modified: core/branches/flat/src/test/java/org/horizon/replication/BaseReplicatedAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/BaseReplicatedAPITest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/replication/BaseReplicatedAPITest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,7 +1,6 @@
package org.horizon.replication;
import org.horizon.AdvancedCache;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.commands.write.ClearCommand;
import org.horizon.commands.write.PutKeyValueCommand;
@@ -10,23 +9,19 @@
import org.horizon.commands.write.ReplaceCommand;
import org.horizon.config.Configuration;
import org.horizon.invocation.Options;
+import org.horizon.test.MultipleCacheManagersTest;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-@Test(groups = "functional", sequential = true)
-public abstract class BaseReplicatedAPITest extends BaseClusteredTest {
+public class BaseReplicatedAPITest extends MultipleCacheManagersTest {
AdvancedCache cache1, cache2;
protected boolean isSync;
- @BeforeMethod
- public void setUp() {
+ protected void createCaches() throws Throwable {
Configuration c = new Configuration();
c.setStateRetrievalTimeout(1000);
c.setFetchInMemoryState(false);
@@ -35,7 +30,6 @@
List<Cache> caches = createClusteredCaches(2, "replication", c);
cache1 = caches.get(0).getAdvancedCache();
cache2 = caches.get(1).getAdvancedCache();
- TestingUtil.blockUntilViewsReceived(10000, cache1, cache2);
}
public void put() {
@@ -43,10 +37,9 @@
assert cache1.get("key") == null;
assert cache2.get("key") == null;
- ReplListener r = attachReplicationListener(cache2);
- r.expect(PutKeyValueCommand.class);
+ replListener(cache2).expect(PutKeyValueCommand.class);
cache1.put("key", "value");
- r.waitForRPC();
+ replListener(cache2).waitForRPC();
assert cache1.get("key").equals("value");
assert cache2.get("key").equals("value");
@@ -55,9 +48,9 @@
map.put("key2", "value2");
map.put("key3", "value3");
- r.expect(PutMapCommand.class);
+ replListener(cache2).expect(PutMapCommand.class);
cache1.putAll(map);
- r.waitForRPC();
+ replListener(cache2).waitForRPC();
assert cache1.get("key").equals("value");
assert cache2.get("key").equals("value");
@@ -72,10 +65,9 @@
assert cache2.get("key").equals("value");
assert cache1.get("key") == null;
- ReplListener r = attachReplicationListener(cache2);
- r.expect(RemoveCommand.class);
+ replListener(cache2).expect(RemoveCommand.class);
cache1.remove("key");
- r.waitForRPC();
+ replListener(cache2).waitForRPC();
assert cache1.get("key") == null;
assert cache2.get("key") == null;
@@ -85,9 +77,9 @@
assert cache1.get("key").equals("value");
assert cache2.get("key").equals("value");
- r.expect(RemoveCommand.class);
+ replListener(cache2).expect(RemoveCommand.class);
cache1.remove("key");
- r.waitForRPC();
+ replListener(cache2).waitForRPC();
assert cache1.get("key") == null;
assert cache2.get("key") == null;
@@ -98,10 +90,9 @@
assert cache2.get("key").equals("valueOld");
assert cache1.get("key") == null;
- BaseClusteredTest.ReplListener r = attachReplicationListener(cache2);
- r.expect(PutKeyValueCommand.class);
+ replListener(cache2).expect(PutKeyValueCommand.class);
cache1.putIfAbsent("key", "value");
- r.waitForRPC();
+ replListener(cache2).waitForRPC();
assert cache1.get("key").equals("value");
assert cache2.get("key").equals("value");
@@ -128,10 +119,9 @@
assert cache1.get("key").equals("value1") : "Should not remove";
assert cache2.get("key").equals("value2") : "Should not remove";
- BaseClusteredTest.ReplListener r = attachReplicationListener(cache2);
- r.expect(RemoveCommand.class);
+ replListener(cache2).expect(RemoveCommand.class);
cache1.remove("key", "value1");
- r.waitForRPC();
+ replListener(cache2).waitForRPC();
assert cache1.get("key") == null;
assert cache2.get("key") == null;
@@ -143,10 +133,9 @@
assert cache1.get("key").equals("value1");
assert cache2.get("key").equals("value2");
- BaseClusteredTest.ReplListener r = attachReplicationListener(cache2);
- r.expect(ClearCommand.class);
+ replListener(cache2).expect(ClearCommand.class);
cache1.clear();
- r.waitForRPC();
+ replListener(cache2).waitForRPC();
assert cache1.get("key") == null;
assert cache2.get("key") == null;
@@ -164,10 +153,9 @@
cache1.put("key", "valueN", Options.CACHE_MODE_LOCAL);
- BaseClusteredTest.ReplListener r = attachReplicationListener(cache2);
- r.expect(ReplaceCommand.class);
+ replListener(cache2).expect(ReplaceCommand.class);
cache1.replace("key", "value1");
- r.waitForRPC();
+ replListener(cache2).waitForRPC();
assert cache1.get("key").equals("value1");
assert cache2.get("key").equals("value1");
@@ -190,10 +178,9 @@
assert cache1.get("key").equals("valueN");
assert cache2.get("key").equals("value2");
- BaseClusteredTest.ReplListener r = attachReplicationListener(cache2);
- r.expect(ReplaceCommand.class);
+ replListener(cache2).expect(ReplaceCommand.class);
cache1.replace("key", "valueN", "value1");
- r.waitForRPC();
+ replListener(cache2).waitForRPC();
assert cache1.get("key").equals("value1");
assert cache2.get("key").equals("value1");
Modified: core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -8,7 +8,6 @@
package org.horizon.replication;
import org.horizon.AdvancedCache;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.commands.VisitableCommand;
import org.horizon.config.Configuration;
@@ -16,11 +15,11 @@
import org.horizon.interceptors.base.CommandInterceptor;
import org.horizon.lock.IsolationLevel;
import org.horizon.lock.TimeoutException;
+import org.horizon.test.MultipleCacheManagersTest;
+import org.horizon.test.TestingUtil;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.fail;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.transaction.NotSupportedException;
@@ -31,12 +30,11 @@
import java.io.Serializable;
import java.util.List;
-@Test(groups = "functional", sequential = true)
-public class ReplicationExceptionTest extends BaseClusteredTest {
+@Test(groups = "functional", testName = "replication.ReplicationExceptionTest")
+public class ReplicationExceptionTest extends MultipleCacheManagersTest {
private AdvancedCache cache1, cache2;
- @BeforeMethod
- public void setUp() {
+ protected void createCaches() throws Throwable {
Configuration configuration = new Configuration();
configuration.setCacheMode(Configuration.CacheMode.REPL_SYNC);
Modified: core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -7,7 +7,6 @@
*/
package org.horizon.replication;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.CacheException;
import org.horizon.config.Configuration;
@@ -19,10 +18,10 @@
import org.horizon.notifications.cachelistener.annotation.CacheEntryRemoved;
import org.horizon.notifications.cachelistener.event.Event;
import org.horizon.notifications.cachelistener.event.TransactionalEvent;
+import org.horizon.test.MultipleCacheManagersTest;
+import org.horizon.test.TestingUtil;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
import static org.testng.AssertJUnit.*;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.transaction.Transaction;
@@ -33,13 +32,12 @@
/**
* Test out the CacheListener
*/
-@Test(groups = "functional", sequential = true)
-public class SyncCacheListenerTest extends BaseClusteredTest {
+@Test(groups = "functional", testName = "replication.SyncCacheListenerTest")
+public class SyncCacheListenerTest extends MultipleCacheManagersTest {
private Cache<Object, Object> cache1, cache2;
private final static Log log = LogFactory.getLog(SyncCacheListenerTest.class);
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception {
+ protected void createCaches() throws Throwable {
Configuration conf = new Configuration();
conf.setSyncCommitPhase(true);
conf.setCacheMode(Configuration.CacheMode.REPL_SYNC);
@@ -51,7 +49,6 @@
cache1 = caches.get(0);
cache2 = caches.get(1);
- TestingUtil.blockUntilViewsReceived(10000, cache1, cache2);
}
public void testSyncTxRepl() throws Exception {
Modified: core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -7,21 +7,19 @@
package org.horizon.replication;
import static org.easymock.EasyMock.*;
-import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.commands.RPCCommand;
import org.horizon.config.Configuration;
-import org.horizon.manager.CacheManager;
import org.horizon.remoting.RPCManager;
import org.horizon.remoting.RPCManagerImpl;
import org.horizon.remoting.ResponseFilter;
import org.horizon.remoting.ResponseMode;
import org.horizon.remoting.transport.Address;
import org.horizon.remoting.transport.Transport;
-import org.horizon.util.TestingUtil;
+import org.horizon.test.MultipleCacheManagersTest;
+import org.horizon.test.TestingUtil;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Collections;
@@ -31,25 +29,18 @@
/**
* @author <a href="mailto:manik@jboss.org">Manik Surtani (manik(a)jboss.org)</a>
*/
-@Test(groups = "functional", sequential = true)
-public class SyncReplTest extends BaseClusteredTest {
+@Test(groups = "functional", testName = "replication.SyncReplTest")
+public class SyncReplTest extends MultipleCacheManagersTest {
Cache cache1, cache2;
String k = "key", v = "value";
- @BeforeMethod(alwaysRun = true)
- public void setUp() {
- CacheManager cm1 = addClusterEnabledCacheManager();
- CacheManager cm2 = addClusterEnabledCacheManager();
-
+ protected void createCaches() throws Throwable {
Configuration replSync = new Configuration();
replSync.setCacheMode(Configuration.CacheMode.REPL_SYNC);
+ createClusteredCaches(2, "replSync", replSync);
- defineCacheOnAllManagers("replSync", replSync);
-
- cache1 = cm1.getCache("replSync");
- cache2 = cm2.getCache("replSync");
-
- TestingUtil.blockUntilViewsReceived(60000, true, cm1, cm2);
+ cache1 = manager(0).getCache("replSync");
+ cache2 = manager(1).getCache("replSync");
}
public void testBasicOperation() {
@@ -73,27 +64,30 @@
assert cache1.isEmpty();
assert cache2.isEmpty();
- List<CacheManager> managers = getCacheManagers();
Configuration newConf = new Configuration();
newConf.setCacheMode(Configuration.CacheMode.REPL_SYNC);
defineCacheOnAllManagers("newCache", newConf);
- Cache altCache1 = managers.get(0).getCache("newCache");
- Cache altCache2 = managers.get(1).getCache("newCache");
+ Cache altCache1 = manager(0).getCache("newCache");
+ Cache altCache2 = manager(1).getCache("newCache");
- assert altCache1.isEmpty();
- assert altCache2.isEmpty();
+ try {
+ assert altCache1.isEmpty();
+ assert altCache2.isEmpty();
- cache1.put(k, v);
- assert cache1.get(k).equals(v);
- assert cache2.get(k).equals(v);
- assert altCache1.isEmpty();
- assert altCache2.isEmpty();
+ cache1.put(k, v);
+ assert cache1.get(k).equals(v);
+ assert cache2.get(k).equals(v);
+ assert altCache1.isEmpty();
+ assert altCache2.isEmpty();
- altCache1.put(k, "value2");
- assert altCache1.get(k).equals("value2");
- assert altCache2.get(k).equals("value2");
- assert cache1.get(k).equals(v);
- assert cache2.get(k).equals(v);
+ altCache1.put(k, "value2");
+ assert altCache1.get(k).equals("value2");
+ assert altCache2.get(k).equals("value2");
+ assert cache1.get(k).equals(v);
+ assert cache2.get(k).equals(v);
+ } finally {
+ removeCacheFromCluster("newCache");
+ }
}
public void testReplicateToNonExistentCache() {
@@ -101,36 +95,38 @@
assert cache1.isEmpty();
assert cache2.isEmpty();
- List<CacheManager> managers = getCacheManagers();
Configuration newConf = new Configuration();
newConf.setCacheMode(Configuration.CacheMode.REPL_SYNC);
- defineCacheOnAllManagers("newCache", newConf);
- Cache altCache1 = managers.get(0).getCache("newCache");
+ defineCacheOnAllManagers("newCache2", newConf);
+ Cache altCache1 = manager(0).getCache("newCache2");
- assert altCache1.isEmpty();
+ try {
+ assert altCache1.isEmpty();
- cache1.put(k, v);
- assert cache1.get(k).equals(v);
- assert cache2.get(k).equals(v);
- assert altCache1.isEmpty();
+ cache1.put(k, v);
+ assert cache1.get(k).equals(v);
+ assert cache2.get(k).equals(v);
+ assert altCache1.isEmpty();
- altCache1.put(k, "value2");
- assert altCache1.get(k).equals("value2");
- assert cache1.get(k).equals(v);
- assert cache2.get(k).equals(v);
+ altCache1.put(k, "value2");
+ assert altCache1.get(k).equals("value2");
+ assert cache1.get(k).equals(v);
+ assert cache2.get(k).equals(v);
- managers.get(0).getCache("newCache").get(k).equals("value2");
+ assert manager(0).getCache("newCache2").get(k).equals("value2");
+ } finally {
+ removeCacheFromCluster("newCache2");
+ }
}
public void testMixingSyncAndAsyncOnSameTransport() throws Exception {
- List<CacheManager> managers = getCacheManagers();
Transport originalTransport = null;
RPCManagerImpl rpcManager = null;
try {
Configuration asyncCache = new Configuration();
asyncCache.setCacheMode(Configuration.CacheMode.REPL_ASYNC);
defineCacheOnAllManagers("asyncCache", asyncCache);
- Cache asyncCache1 = managers.get(0).getCache("asyncCache");
+ Cache asyncCache1 = manager(0).getCache("asyncCache");
// replace the transport with a mock object
Transport mockTransport = createMock(Transport.class);
Modified: core/branches/flat/src/test/java/org/horizon/replication/SyncReplicatedAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/SyncReplicatedAPITest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/replication/SyncReplicatedAPITest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -2,7 +2,7 @@
import org.testng.annotations.Test;
-@Test(groups = "functional", sequential = true)
+@Test(groups = "functional", testName = "replication.SyncReplicatedAPITest")
public class SyncReplicatedAPITest extends BaseReplicatedAPITest {
public SyncReplicatedAPITest() {
isSync = true;
Added: core/branches/flat/src/test/java/org/horizon/test/AbstractCacheTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/test/AbstractCacheTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/test/AbstractCacheTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -0,0 +1,83 @@
+package org.horizon.test;
+
+import org.horizon.AdvancedCache;
+import org.horizon.Cache;
+import org.horizon.context.InvocationContext;
+import org.horizon.container.DataContainer;
+import org.horizon.lifecycle.ComponentStatus;
+import org.horizon.loader.CacheLoaderManager;
+import org.horizon.manager.CacheManager;
+import org.horizon.manager.DefaultCacheManager;
+
+import javax.transaction.TransactionManager;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.ConcurrentMap;
+
+/**
+ * Base class for {@link org.horizon.test.SingleCacheManagerTest} and {@link org.horizon.test.MultipleCacheManagersTest}.
+ *
+ * @author Mircea.Markus(a)jboss.com
+ */
+public class AbstractCacheTest {
+ /**
+ * Importnat: do not reset RegionManager (rm.reset()) here, as this woulfd cause eviction region to be clered. If
+ * that is needed, do it in @BeforeMethods
+ */
+ public void clearContent(CacheManager cacheManager) {
+ Set<Cache> runningCaches = getRunningCaches(cacheManager);
+ for (Cache cache : runningCaches) {
+ clearRunningTx(cache);
+ }
+ if (!cacheManager.getStatus().allowInvocations()) return;
+ for (Cache cache : runningCaches) {
+ removeInMemoryData(cache);
+ clearCacheLoader(cache);
+ InvocationContext invocationContext = ((AdvancedCache) cache).getInvocationContextContainer().get();
+ if (invocationContext != null) invocationContext.reset();
+ }
+ }
+
+ @SuppressWarnings(value = "unchecked")
+ private Set<Cache> getRunningCaches(CacheManager cacheManager) {
+ ConcurrentMap<String, Cache> caches = (ConcurrentMap<String, Cache>) TestingUtil.extractField(DefaultCacheManager.class, cacheManager, "caches");
+ Set<Cache> result = new HashSet<Cache>();
+ for (Cache cache : caches.values()) {
+ if (cache.getStatus() == ComponentStatus.RUNNING)
+ result.add(cache);
+ }
+ return result;
+ }
+
+ private void clearCacheLoader(Cache cache) {
+ CacheLoaderManager cacheLoaderManager = TestingUtil.extractComponent(cache, CacheLoaderManager.class);
+ if (cacheLoaderManager != null && cacheLoaderManager.getCacheStore() != null) {
+ try {
+ cacheLoaderManager.getCacheStore().clear();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ private void removeInMemoryData(Cache cache) {
+ System.out.println("Cleaning data for cache: " + cache.getName());
+ DataContainer dataContainer = TestingUtil.extractComponent(cache, DataContainer.class);
+ System.out.println("AbstractCacheTest.removeInMemoryData--> dataContainerBefore==" + dataContainer);
+ dataContainer.clear();
+ System.out.println("AbstractCacheTest.removeInMemoryData--> dataContainerAfter==" + dataContainer);
+ }
+
+ private void clearRunningTx(Cache cache) {
+ if (cache != null) {
+ TransactionManager txm = TestingUtil.getTransactionManager(cache);
+ if (txm == null) return;
+ try {
+ txm.rollback();
+ }
+ catch (Exception e) {
+ // don't care
+ }
+ }
+ }
+}
Property changes on: core/branches/flat/src/test/java/org/horizon/test/AbstractCacheTest.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Added: core/branches/flat/src/test/java/org/horizon/test/JGroupsConfigBuilder.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/test/JGroupsConfigBuilder.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/test/JGroupsConfigBuilder.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -0,0 +1,165 @@
+package org.horizon.test;
+
+import org.horizon.config.parsing.JGroupsStackParser;
+import org.horizon.config.parsing.XmlConfigHelper;
+import org.w3c.dom.Element;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * This class owns the logic of associating network resources(i.e. ports) with threads, in order to make sure that there
+ * won't be any clashes between multiple clusters running in parallel on same host. Used for parallel test suite.
+ *
+ * @author Mircea.Markus(a)jboss.com
+ */
+public class JGroupsConfigBuilder {
+
+ public static final String JGROUPS_STACK;
+
+ private static String tcpConfig;
+ private static String udpConfig;
+
+ private static final ThreadLocal<String> threadTcpStartPort = new ThreadLocal<String>() {
+ private final AtomicInteger uniqueAddr = new AtomicInteger(7900);
+
+ @Override
+ protected String initialValue() {
+ return uniqueAddr.getAndAdd(50) + "";
+ }
+ };
+
+ /**
+ * Holds unique mcast_addr for each thread used for JGroups channel construction.
+ */
+ private static final ThreadLocal<String> threadMcastIP = new ThreadLocal<String>() {
+ private final AtomicInteger uniqueAddr = new AtomicInteger(11);
+
+ @Override
+ protected String initialValue() {
+ return "228.10.10." + uniqueAddr.getAndIncrement();
+ }
+ };
+
+ /**
+ * Holds unique mcast_port for each thread used for JGroups channel construction.
+ */
+ private static final ThreadLocal<Integer> threadMcastPort = new ThreadLocal<Integer>() {
+ private final AtomicInteger uniquePort = new AtomicInteger(45589);
+
+ @Override
+ protected Integer initialValue() {
+ return uniquePort.getAndIncrement();
+ }
+ };
+
+ private static final Pattern TCP_START_PORT = Pattern.compile("bind_port=[^;]*");
+ private static final Pattern TCP_INITIAL_HOST = Pattern.compile("initial_hosts=[^;]*");
+ private static final Pattern UDP_MCAST_ADDRESS = Pattern.compile("mcast_addr=[^;]*");
+ private static final Pattern UDP_MCAST_PORT = Pattern.compile("mcast_port=[^;]*");
+
+ static {
+ JGROUPS_STACK = System.getProperties().getProperty("jgroups.stack", "tcp");
+ System.out.println("IN USE JGROUPS STACK = " + JGROUPS_STACK);
+ }
+
+ public static String getJGroupsConfig() {
+ if (JGROUPS_STACK.equalsIgnoreCase("tcp")) return getTcpConfig();
+ if (JGROUPS_STACK.equalsIgnoreCase("udp")) return getUdpConfig();
+ throw new IllegalStateException("Unknown protocol stack : " + JGROUPS_STACK);
+ }
+
+ public static String getTcpConfig() {
+ loadTcp();
+ // replace mcast_addr
+ Matcher m = TCP_START_PORT.matcher(tcpConfig);
+ String result;
+ String newStartPort;
+ if (m.find()) {
+ newStartPort = threadTcpStartPort.get();
+ result = m.replaceFirst("start_port=" + newStartPort);
+ } else {
+ System.out.println("Config is:" + tcpConfig);
+ Thread.dumpStack();
+ throw new IllegalStateException();
+ }
+
+ if (result.indexOf("TCPGOSSIP") < 0) //onluy adjust for TCPPING
+ {
+ m = TCP_INITIAL_HOST.matcher(result);
+ if (m.find()) {
+ result = m.replaceFirst("initial_hosts=" + "127.0.0.1[" + newStartPort + "]");
+ }
+ }
+ return result;
+ }
+
+ public static String getUdpConfig() {
+ loadUdp();
+ // replace mcast_addr
+ Matcher m = UDP_MCAST_ADDRESS.matcher(udpConfig);
+ String result;
+ if (m.find()) {
+ String newAddr = threadMcastIP.get();
+ result = m.replaceFirst("mcast_addr=" + newAddr);
+ } else {
+ Thread.dumpStack();
+ throw new IllegalStateException();
+ }
+
+ // replace mcast_port
+ m = UDP_MCAST_PORT.matcher(result);
+ if (m.find()) {
+ String newPort = threadMcastPort.get().toString();
+ result = m.replaceFirst("mcast_port=" + newPort);
+ }
+ return result;
+ }
+
+ private static void loadTcp() {
+ if (tcpConfig != null) return;
+ String xmlString = readFile("stacks/tcp.xml");
+ tcpConfig = getJgroupsConfig(xmlString);
+ }
+
+ private static void loadUdp() {
+ if (udpConfig != null) return;
+ String xmlString = readFile("stacks/udp.xml");
+ udpConfig = getJgroupsConfig(xmlString);
+ }
+
+ private static String getJgroupsConfig(String xmlString) {
+ try {
+ Element e = XmlConfigHelper.stringToElement(xmlString);
+ JGroupsStackParser parser = new JGroupsStackParser();
+ return parser.parseClusterConfigXml(e);
+ } catch (Exception ex) {
+ throw new RuntimeException("Unexpected!", ex);
+ }
+ }
+
+ private static String readFile(String fileName) {
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ InputStream is = cl.getResourceAsStream(fileName);
+ BufferedReader bf = new BufferedReader(new InputStreamReader(is));
+ StringBuilder result = new StringBuilder();
+ String line;
+ try {
+ while ((line = bf.readLine()) != null) result.append(line);
+ } catch (IOException e) {
+ throw new RuntimeException("Unexpected!", e);
+ } finally {
+ try {
+ bf.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ return result.toString();
+ }
+}
Property changes on: core/branches/flat/src/test/java/org/horizon/test/JGroupsConfigBuilder.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Added: core/branches/flat/src/test/java/org/horizon/test/MultipleCacheManagersTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/test/MultipleCacheManagersTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/test/MultipleCacheManagersTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -0,0 +1,117 @@
+package org.horizon.test;
+
+import org.horizon.Cache;
+import org.horizon.config.Configuration;
+import org.horizon.manager.CacheManager;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.IdentityHashMap;
+import java.util.List;
+
+/**
+ * Base class for tests that operates on clusters of caches. The way tests extending this class operates is:
+ * <pre>
+ * 1) created cache managers before tests start. The cache managers are only created once
+ * 2) after each test method runs, the cache managers are being cleared
+ * 3) next test method will run on same cacheManager instance. This way the test is much faster, as CacheManagers
+ * are expensive to create.
+ * </pre>
+ *
+ * @author Mircea.Markus(a)jboss.com
+ */
+@Test(groups = {"functional", "unit"})
+public abstract class MultipleCacheManagersTest extends AbstractCacheTest {
+
+ private List<CacheManager> cacheManagers = new ArrayList<CacheManager>();
+
+ private IdentityHashMap<Cache, ReplListener> listeners = new IdentityHashMap<Cache, ReplListener>();
+
+ @BeforeClass
+ public void create() throws Throwable {
+ createCaches();
+ }
+
+ @AfterClass
+ protected void destroy() {
+ TestingUtil.killCacheManagers(cacheManagers);
+ }
+
+ @AfterMethod
+ protected void clearContent() throws Throwable {
+ System.out.println("MultipleCacheManagersTest.clearContent");
+ if (cacheManagers.isEmpty())
+ throw new IllegalStateException("No caches registered! Use registerCacheManager(Cache... caches) do that!");
+ for (CacheManager cacheManager : cacheManagers) {
+ super.clearContent(cacheManager);
+ }
+ }
+
+ final protected void registerCaches(CacheManager... cacheManagers) {
+ this.cacheManagers.addAll(Arrays.asList(cacheManagers));
+ }
+
+ /**
+ * Creates a new cache manager, starts it, and adds it to the list of known cache managers on the current thread.
+ * Uses a default clustered cache manager global config.
+ *
+ * @return the new CacheManager
+ */
+ protected CacheManager addClusterEnabledCacheManager() {
+ CacheManager cm = TestingUtil.createClusteredCacheManager();
+ cacheManagers.add(cm);
+ return cm;
+ }
+
+ protected void defineCacheOnAllManagers(String cacheName, Configuration c) {
+ for (CacheManager cm : cacheManagers) {
+ cm.defineCache(cacheName, c);
+ }
+ }
+
+ protected List<Cache> createClusteredCaches(int numMembersInCluster, String cacheName, Configuration c) {
+ List<Cache> caches = new ArrayList<Cache>(numMembersInCluster);
+ for (int i = 0; i < numMembersInCluster; i++) {
+ CacheManager cm = addClusterEnabledCacheManager();
+ cm.defineCache(cacheName, c);
+ caches.add(cm.getCache(cacheName));
+ }
+ TestingUtil.blockUntilViewsReceived(10000, caches);
+ return caches;
+ }
+
+ public ReplListener replListener(Cache cache) {
+ ReplListener listener = listeners.get(cache);
+ if (listener == null) {
+ listener = new ReplListener(cache);
+ listeners.put(cache, listener);
+ }
+ return listener;
+ }
+
+ public CacheManager manager(int i) {
+ return cacheManagers.get(i);
+ }
+
+ protected Cache cache(int managerIndex, String cacheName) {
+ return manager(managerIndex).getCache(cacheName);
+ }
+
+ protected void assertClusterSize(String message, int size) {
+ for (CacheManager cm : cacheManagers) {
+ assert cm.getMembers() != null && cm.getMembers().size() == size : message;
+ }
+ }
+
+ protected void removeCacheFromCluster(String cacheName) {
+ for (CacheManager cm : cacheManagers) {
+ TestingUtil.killCaches(cm.getCache(cacheName));
+ }
+ }
+
+ protected abstract void createCaches() throws Throwable;
+}
Property changes on: core/branches/flat/src/test/java/org/horizon/test/MultipleCacheManagersTest.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Added: core/branches/flat/src/test/java/org/horizon/test/ReplListener.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/test/ReplListener.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/test/ReplListener.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -0,0 +1,127 @@
+package org.horizon.test;
+
+import org.horizon.Cache;
+import org.horizon.context.InvocationContext;
+import org.horizon.interceptors.base.CommandInterceptor;
+import org.horizon.commands.VisitableCommand;
+import org.horizon.commands.DataCommand;
+import org.horizon.commands.tx.PrepareCommand;
+import org.horizon.commands.tx.CommitCommand;
+
+import java.util.Set;
+import java.util.HashSet;
+import java.util.Arrays;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * A listener that listens for replication events on a cache it is watching. Typical usage: <code> ReplListener r =
+ * attachReplicationListener(cache); r.expect(RemoveCommand.class); // ... r.waitForRPC(); </code>
+ */
+public class ReplListener {
+ Cache c;
+ Set<Class<? extends VisitableCommand>> expectedCommands;
+ CountDownLatch latch = new CountDownLatch(1);
+
+ public ReplListener(Cache c) {
+ this.c = c;
+ this.c.getAdvancedCache().addInterceptor(new ReplListenerInterceptor(), 0);
+ }
+
+ /**
+ * Expects any commands. The moment a single command is detected, the {@link #waitForRPC()} command will be
+ * unblocked.
+ */
+ public void expectAny() {
+ expect();
+ }
+
+ /**
+ * Expects a specific set of commands, within transactional scope (i.e., as a payload to a PrepareCommand). If the
+ * cache mode is synchronous, a CommitCommand is expected as well.
+ *
+ * @param commands commands to expect (not counting transaction boundary commands like PrepareCommand and
+ * CommitCommand)
+ */
+ public void expectWithTx(Class<? extends VisitableCommand>... commands) {
+ expect(PrepareCommand.class);
+ expect(commands);
+ //this is because for async replication we have an 1pc transaction
+ if (c.getConfiguration().getCacheMode().isSynchronous()) expect(CommitCommand.class);
+ }
+
+ /**
+ * Expects any commands, within transactional scope (i.e., as a payload to a PrepareCommand). If the cache mode is
+ * synchronous, a CommitCommand is expected as well.
+ */
+ public void expectAnyWithTx() {
+ expect(PrepareCommand.class);
+ //this is because for async replication we have an 1pc transaction
+ if (c.getConfiguration().getCacheMode().isSynchronous()) expect(CommitCommand.class);
+ }
+
+ /**
+ * Expects a specific set of commands. {@link #waitForRPC()} will block until all of these commands are detected.
+ *
+ * @param expectedCommands commands to expect
+ */
+ public void expect(Class<? extends VisitableCommand>... expectedCommands) {
+ if (this.expectedCommands == null) {
+ this.expectedCommands = new HashSet<Class<? extends VisitableCommand>>();
+ }
+ this.expectedCommands.addAll(Arrays.asList(expectedCommands));
+ }
+
+ /**
+ * Blocks for a predefined amount of time (120 Seconds) until commands defined in any of the expect*() methods have
+ * been detected. If the commands have not been detected by this time, an exception is thrown.
+ */
+ public void waitForRPC() {
+ waitForRPC(120, TimeUnit.SECONDS);
+ }
+
+ /**
+ * The same as {@link #waitForRPC()} except that you are allowed to specify the max wait time.
+ */
+ public void waitForRPC(long time, TimeUnit unit) {
+ assert expectedCommands != null : "there are no replication expectations; please use ReplListener.expect() before calling this method";
+ try {
+ if (!latch.await(time, unit)) {
+ assert false : "Waiting for more than " + time + " " + unit + " and following commands did not replicate: " + expectedCommands;
+ }
+ }
+ catch (InterruptedException e) {
+ throw new IllegalStateException("unexpected", e);
+ }
+ finally {
+ expectedCommands = null;
+ latch = new CountDownLatch(1);
+ }
+ }
+
+ protected class ReplListenerInterceptor extends CommandInterceptor {
+ @Override
+ protected Object handleDefault(InvocationContext ctx, VisitableCommand cmd) throws Throwable {
+ // first pass up chain
+ Object o = invokeNextInterceptor(ctx, cmd);
+ markAsVisited(cmd);
+ return o;
+ }
+
+ @Override
+ public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand cmd) throws Throwable {
+ // first pass up chain
+ Object o = invokeNextInterceptor(ctx, cmd);
+ markAsVisited(cmd);
+ for (DataCommand mod : cmd.getModifications()) markAsVisited(mod);
+ return o;
+ }
+
+ private void markAsVisited(VisitableCommand cmd) {
+ if (expectedCommands != null) {
+ expectedCommands.remove(cmd.getClass());
+ if (expectedCommands.isEmpty()) latch.countDown();
+ }
+ }
+ }
+}
Property changes on: core/branches/flat/src/test/java/org/horizon/test/ReplListener.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Added: core/branches/flat/src/test/java/org/horizon/test/SingleCacheManagerTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/test/SingleCacheManagerTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/test/SingleCacheManagerTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -0,0 +1,51 @@
+package org.horizon.test;
+
+import org.horizon.Cache;
+import org.horizon.manager.CacheManager;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+
+/**
+ * Base class for tests that operate on a single (most likely local) cache instance.
+ * This operates similar to {@link org.horizon.test.MultipleCacheManagersTest}, but on only once CacheManager.
+ *
+ * @author Mircea.Markus(a)jboss.com
+ * @see org.horizon.test.MultipleCacheManagersTest
+ */
+public abstract class SingleCacheManagerTest extends AbstractCacheTest {
+ protected CacheManager cacheManager;
+ protected Cache cache;
+
+ /**
+ * This method will always be called before {@link #create()}. If you override this, make sure you annotate the
+ * overridden method with {@link org.testng.annotations.BeforeClass}.
+ *
+ * @throws Exception Just in case
+ */
+ @BeforeClass
+ public void preCreate() throws Exception {
+ // no op, made for overriding.
+ }
+
+ // Due to some weirdness with TestNG, it always appends the package and class name to the method names
+ // provided on dependsOnMethods unless it thinks there already is a package. This does accept regular expressions
+ // though so .*. works. Otherwise it won't detect overridden methods in subclasses.
+ @BeforeClass(dependsOnMethods = "org.horizon.*.preCreate")
+ protected void create() throws Exception {
+ cacheManager = createCacheManager();
+ }
+
+ @AfterClass
+ protected void destroy() {
+ TestingUtil.killCacheManagers(cacheManager);
+ }
+
+ @AfterMethod
+ protected void clearContent() {
+ super.clearContent(cacheManager);
+ }
+
+ protected abstract CacheManager createCacheManager() throws Exception;
+
+}
Property changes on: core/branches/flat/src/test/java/org/horizon/test/SingleCacheManagerTest.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Added: core/branches/flat/src/test/java/org/horizon/test/TestNameVerifier.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/test/TestNameVerifier.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/test/TestNameVerifier.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -0,0 +1,209 @@
+package org.horizon.test;
+
+import org.testng.annotations.Test;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileFilter;
+import java.io.FileReader;
+import java.io.FilenameFilter;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Class that tests that test names are correclty set for each test.
+ *
+ * @author Mircea.Markus(a)jboss.com
+ */
+@Test(groups = "functional", testName = "test.TestNameVerifier")
+public class TestNameVerifier {
+ String dir = "src/test/java/org/horizon";
+
+ Pattern packageLinePattern = Pattern.compile("package org.horizon[^;]*");
+ Pattern classLinePattern = Pattern.compile("(abstract\\s*)??(public\\s*)(abstract\\s*)??class [^\\s]*");
+ Pattern atAnnotationPattern = Pattern.compile("@Test[^)]*");
+ Pattern testNamePattern = Pattern.compile("testName\\s*=\\s*\"[^\"]*\"");
+
+ String fileCache;
+
+ FilenameFilter javaFilter = new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ if (dir.getAbsolutePath().contains("testng")) return false;
+ return name.endsWith(".java");
+ }
+ };
+
+ FileFilter onlyDirs = new FileFilter() {
+ public boolean accept(File pathname) {
+ return pathname.isDirectory();
+ }
+ };
+
+ @Test(enabled = false, description = "Do not enable this unless you want your files to be updated with test names!!!")
+ public void process() throws Exception {
+ File[] javaFiles = getJavaFiles();
+ for (File file : javaFiles) {
+ if (needsUpdate(file)) {
+ System.out.println("Updating file: " + file.getAbsolutePath());
+ updateFile(file);
+ }
+ }
+ }
+
+ private void updateFile(File file) throws Exception {
+ String javaString = fileCache;
+ String testName = getTestName(javaString, file.getName());
+ String testNameStr = ", testName = \"" + testName + "\"";
+ javaString = replaceAtTestAnnotation(javaString, testNameStr);
+ persistNewFile(file, javaString);
+ }
+
+ private void persistNewFile(File file, String javaString) throws Exception {
+ if (file.delete()) {
+ System.out.println("!!!!!!!!!! error porcessing file " + file.getName());
+ return;
+ }
+ file.createNewFile();
+ PrintWriter writter = new PrintWriter(file);
+ writter.append(javaString);
+ writter.close();
+ }
+
+ private String replaceAtTestAnnotation(String javaString, String testNameStr) {
+ Matcher matcher = atAnnotationPattern.matcher(javaString);
+ boolean found = matcher.find();
+ assert found;
+ String theMatch = matcher.group();
+ return matcher.replaceFirst(theMatch + testNameStr);
+ }
+
+ private String getTestName(String javaString, String filename) {
+ String classNamePart = getClassNamePart(javaString, filename);
+
+ //abstract classes do not require test names
+ if (classNamePart.indexOf("abstract") >= 0) return null;
+
+ classNamePart = classNamePart.substring("public class ".length());
+ String packagePart = getPackagePart(javaString, filename);
+ //if the test is in org.horizon package then make sure no . is prepanded
+ String packagePrepend = ((packagePart != null) && (packagePart.length() > 0)) ? packagePart + "." : "";
+ return packagePrepend + classNamePart;
+ }
+
+ private String getClassNamePart(String javaString, String filename) {
+ Matcher matcher = classLinePattern.matcher(javaString);
+ boolean found = matcher.find();
+ assert found : "could not determine class name for file: " + filename;
+ return matcher.group();
+ }
+
+ private String getPackagePart(String javaString, String filename) {
+ Matcher matcher = packageLinePattern.matcher(javaString);
+ boolean found = matcher.find();
+ assert found : "Could not determine package name for file: " + filename;
+ String theMatch = matcher.group();
+ String partial = theMatch.substring("package org.horizon".length());
+ if (partial.trim().length() == 0) return partial.trim();
+ return partial.substring(1);//drop the leading dot.
+ }
+
+
+ private boolean needsUpdate(File file) throws Exception {
+ String javaFileStr = getFileAsString(file);
+ if (javaFileStr.indexOf(" testName = \"") > 0) return false;
+ int atTestIndex = javaFileStr.indexOf("@Test");
+ int classDeclarationIndex = javaFileStr.indexOf("public class");
+ return atTestIndex > 0 && atTestIndex < classDeclarationIndex;
+ }
+
+ private String getFileAsString(File file) throws Exception {
+ StringBuilder builder = new StringBuilder();
+ BufferedReader fileReader = new BufferedReader(new FileReader(file));
+ String line;
+ while ((line = fileReader.readLine()) != null) {
+ builder.append(line + "\n");
+ }
+ this.fileCache = builder.toString();
+// fileReader.close();
+ return fileCache;
+ }
+
+ private File[] getJavaFiles() {
+ File file = new File(dir);
+ assert file.isDirectory();
+ ArrayList<File> result = new ArrayList<File>();
+ addJavaFiles(file, result);
+ return result.toArray(new File[0]);
+ }
+
+ private void addJavaFiles(File file, ArrayList<File> result) {
+ assert file.isDirectory();
+ File[] javaFiles = file.listFiles(javaFilter);
+// printFiles(javaFiles);
+ result.addAll(Arrays.asList(javaFiles));
+ for (File dir : file.listFiles(onlyDirs)) {
+ addJavaFiles(dir, result);
+ }
+ }
+
+ private void printFiles(File[] javaFiles) {
+ for (File f : javaFiles) {
+ System.out.println(f.getAbsolutePath());
+ }
+ }
+
+ public void verifyTestName() throws Exception {
+ File[] javaFiles = getJavaFiles();
+ StringBuilder errorMessage = new StringBuilder("Following test class(es) do not have an appropriate test name: \n");
+ boolean hasErrors = false;
+ for (File file : javaFiles) {
+ String expectedName = incorrectTestName(file);
+ if (expectedName != null) {
+ errorMessage.append(file.getAbsoluteFile()).append(" expected test name is: '").append(expectedName).append("' \n");
+ hasErrors = true;
+ }
+ }
+ assert !hasErrors : errorMessage.append("The rules for writting UTs are being descibed here: https://www.jboss.org/community/docs/DOC-13315");
+ }
+
+ private String incorrectTestName(File file) throws Exception {
+ String fileAsStr = getFileAsString(file);
+
+ boolean containsTestAnnotation = atAnnotationPattern.matcher(fileAsStr).find();
+ if (!containsTestAnnotation) return null;
+
+ String expectedTestName = getTestName(fileAsStr, file.getName());
+ if (expectedTestName == null) return null; //this happens when the class is abstract
+ Matcher matcher = this.testNamePattern.matcher(fileAsStr);
+ if (!matcher.find()) return expectedTestName;
+ String name = matcher.group().trim();
+ int firstIndexOfQuote = name.indexOf('"');
+ String existingTestName = name.substring(firstIndexOfQuote + 1, name.length() - 1); //to ignore last quote
+ if (!existingTestName.equals(expectedTestName)) return expectedTestName;
+ return null;
+ }
+
+
+// @Test(enabled = false)
+// public static void main(String[] args) throws Exception {
+// File file = new File("C:\\jboss\\brainstoriming\\horizon\\src\\test\\java\\org\\horizon\\api\\tree\\NodeMoveAPITest.java");
+// String incorrectName = new TestNameVerifier().incorrectTestName(file);
+// System.out.println("incorrectName = " + incorrectName);
+
+
+// new TestNameVerifier().process();
+// Pattern classLinePattern = Pattern.compile("@Test[^)]*");
+// String totest = "aaaa\n" + "@Test(groups = {\"functional\", \"pessimistic\"})\n" + "{ dsadsadsa";
+// Matcher matcher = classLinePattern.matcher(totest);
+// boolean found = matcher.find();
+// System.out.println("found = " + found);
+// String theMatch = matcher.group();
+// String result = matcher.replaceFirst(theMatch + ", testName=\"alaBala\"");
+// System.out.println("theMatch = " + theMatch);
+// System.out.println("result = " + result);
+
+// }
+}
\ No newline at end of file
Property changes on: core/branches/flat/src/test/java/org/horizon/test/TestNameVerifier.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Added: core/branches/flat/src/test/java/org/horizon/test/TestingUtil.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/test/TestingUtil.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/test/TestingUtil.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -0,0 +1,639 @@
+/*
+ * JBoss, the OpenSource J2EE webOS
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+
+package org.horizon.test;
+
+import org.horizon.AdvancedCache;
+import org.horizon.Cache;
+import org.horizon.CacheDelegate;
+import org.horizon.config.GlobalConfiguration;
+import org.horizon.commands.CommandsFactory;
+import org.horizon.commands.VisitableCommand;
+import org.horizon.factories.ComponentRegistry;
+import org.horizon.factories.GlobalComponentRegistry;
+import org.horizon.interceptors.InterceptorChain;
+import org.horizon.interceptors.base.CommandInterceptor;
+import org.horizon.lifecycle.ComponentStatus;
+import org.horizon.lock.LockManager;
+import org.horizon.manager.CacheManager;
+import org.horizon.manager.DefaultCacheManager;
+import org.horizon.remoting.transport.Address;
+import org.horizon.remoting.transport.jgroups.JGroupsTransport;
+import org.horizon.tree.TreeCache;
+
+import javax.transaction.TransactionManager;
+import java.io.File;
+import java.lang.reflect.Field;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Random;
+import java.util.Properties;
+
+/**
+ * Utilities for unit testing JBossCache.
+ *
+ * @author <a href="mailto://brian.stansberry@jboss.com">Brian Stansberry</a>
+ * @since 1.0
+ */
+public class TestingUtil {
+ private static Random random = new Random();
+ public static final String TEST_FILES = "testFiles";
+
+ /**
+ * Extracts the value of a field in a given target instance using reflection, able to extract private fields as
+ * well.
+ *
+ * @param target object to extract field from
+ * @param fieldName name of field to extract
+ * @return field value
+ */
+ public static Object extractField(Object target, String fieldName) {
+ return extractField(target.getClass(), target, fieldName);
+ }
+
+ public static void replaceField(Object newValue, String fieldName, Object owner, Class baseType) {
+ Field field;
+ try {
+ field = baseType.getDeclaredField(fieldName);
+ field.setAccessible(true);
+ field.set(owner, newValue);
+ }
+ catch (Exception e) {
+ throw new RuntimeException(e);//just to simplify exception handeling
+ }
+ }
+
+
+ public static Object extractField(Class type, Object target, String fieldName) {
+ Field field;
+ try {
+ field = type.getDeclaredField(fieldName);
+ field.setAccessible(true);
+ return field.get(target);
+ }
+ catch (Exception e) {
+ if (type.equals(Object.class)) {
+ e.printStackTrace();
+ return null;
+ } else {
+ // try with superclass!!
+ return extractField(type.getSuperclass(), target, fieldName);
+ }
+ }
+ }
+
+ public static <T extends CommandInterceptor> T findInterceptor(Cache<?, ?> cache, Class<T> interceptorToFind) {
+ for (CommandInterceptor i : cache.getAdvancedCache().getInterceptorChain()) {
+ if (interceptorToFind.isInstance(i)) return interceptorToFind.cast(i);
+ }
+ return null;
+ }
+
+ /**
+ * Loops, continually calling {@link #areCacheViewsComplete(Cache[])} until it either returns true or
+ * <code>timeout</code> ms have elapsed.
+ *
+ * @param caches caches which must all have consistent views
+ * @param timeout max number of ms to loop
+ * @throws RuntimeException if <code>timeout</code> ms have elapse without all caches having the same number of
+ * members.
+ */
+ public static void blockUntilViewsReceived(Cache[] caches, long timeout) {
+ long failTime = System.currentTimeMillis() + timeout;
+
+ while (System.currentTimeMillis() < failTime) {
+ sleepThread(100);
+ if (areCacheViewsComplete(caches)) {
+ return;
+ }
+ }
+
+ throw new RuntimeException("timed out before caches had complete views");
+ }
+
+ /**
+ * Version of blockUntilViewsReceived that uses varargs
+ */
+ public static void blockUntilViewsReceived(long timeout, Cache... caches) {
+ blockUntilViewsReceived(caches, timeout);
+ }
+
+ /**
+ * Version of blockUntilViewsReceived that uses varargsa and cache managers
+ */
+ public static void blockUntilViewsReceived(long timeout, CacheManager... cacheManagers) {
+ blockUntilViewsReceived(timeout, true, cacheManagers);
+ }
+
+ /**
+ * Waits for the given memebrs to be removed from the cluster. The difference between this and
+ * {@link #blockUntilViewsReceived(long, org.horizon.manager.CacheManager[])} methods(s) is that it does not barf if
+ * more than expected memebers is in the cluster - this is because we expect to start with a grater number fo memebers
+ * than we eventually expect. It will barf though, if the number of members is not the one expected but only after the
+ * timeout expieres.
+ */
+ public static void blockForMemberToFail(long timeout, CacheManager... cacheManagers) {
+ blockUntilViewsReceived(timeout, false, cacheManagers);
+ areCacheViewsComplete(true, cacheManagers);
+ }
+
+ public static void blockUntilViewsReceived(long timeout, boolean barfIfTooManyMembers, CacheManager... cacheManagers) {
+ long failTime = System.currentTimeMillis() + timeout;
+
+ while (System.currentTimeMillis() < failTime) {
+ sleepThread(100);
+ if (areCacheViewsComplete(barfIfTooManyMembers, cacheManagers)) {
+ return;
+ }
+ }
+
+ throw new RuntimeException("timed out before caches had complete views");
+ }
+
+ /**
+ * Loops, continually calling {@link #areCacheViewsComplete(CacheSPI[])} until it either returns true or
+ * <code>timeout</code> ms have elapsed.
+ *
+ * @param caches caches which must all have consistent views
+ * @param timeout max number of ms to loop
+ * @throws RuntimeException if <code>timeout</code> ms have elapse without all caches having the same number of
+ * members.
+ */
+// public static void blockUntilViewsReceived(Cache[] caches, long timeout) {
+// long failTime = System.currentTimeMillis() + timeout;
+//
+// while (System.currentTimeMillis() < failTime) {
+// sleepThread(100);
+// if (areCacheViewsComplete(caches)) {
+// return;
+// }
+// }
+//
+// throw new RuntimeException("timed out before caches had complete views");
+// }
+
+
+ /**
+ * An overloaded version of {@link #blockUntilViewsReceived(long,Cache[])} that allows for 'shrinking' clusters.
+ * I.e., the usual method barfs if there are more members than expected. This one takes a param
+ * (barfIfTooManyMembers) which, if false, will NOT barf but will wait until the cluster 'shrinks' to the desired
+ * size. Useful if in tests, you kill a member and want to wait until this fact is known across the cluster.
+ *
+ * @param timeout
+ * @param barfIfTooManyMembers
+ * @param caches
+ */
+ public static void blockUntilViewsReceived(long timeout, boolean barfIfTooManyMembers, Cache... caches) {
+ long failTime = System.currentTimeMillis() + timeout;
+
+ while (System.currentTimeMillis() < failTime) {
+ sleepThread(100);
+ if (areCacheViewsComplete(caches, barfIfTooManyMembers)) {
+ return;
+ }
+ }
+
+ throw new RuntimeException("timed out before caches had complete views");
+ }
+
+ /**
+ * Loops, continually calling {@link #areCacheViewsComplete(Cache[])} until it either returns true or
+ * <code>timeout</code> ms have elapsed.
+ *
+ * @param groupSize number of caches expected in the group
+ * @param timeout max number of ms to loop
+ * @throws RuntimeException if <code>timeout</code> ms have elapse without all caches having the same number of
+ * members.
+ */
+ public static void blockUntilViewReceived(Cache cache, int groupSize, long timeout) {
+ blockUntilViewReceived(cache, groupSize, timeout, true);
+ }
+
+ public static void blockUntilViewReceived(Cache cache, int groupSize, long timeout, boolean barfIfTooManyMembersInView) {
+ long failTime = System.currentTimeMillis() + timeout;
+
+ while (System.currentTimeMillis() < failTime) {
+ sleepThread(100);
+ if (isCacheViewComplete(cache.getCacheManager().getMembers(), cache.getCacheManager().getAddress(), groupSize, barfIfTooManyMembersInView)) {
+ return;
+ }
+ }
+
+ throw new RuntimeException("timed out before caches had complete views");
+ }
+
+ /**
+ * Checks each cache to see if the number of elements in the array returned by {@link CacheManager#getMembers()}
+ * matches the size of the <code>caches</code> parameter.
+ *
+ * @param caches caches that should form a View
+ * @return <code>true</code> if all caches have <code>caches.length</code> members; false otherwise
+ * @throws IllegalStateException if any of the caches have MORE view members than caches.length
+ */
+ public static boolean areCacheViewsComplete(Cache[] caches) {
+ return areCacheViewsComplete(caches, true);
+ }
+
+ public static boolean areCacheViewsComplete(Cache[] caches, boolean barfIfTooManyMembers) {
+ int memberCount = caches.length;
+
+ for (int i = 0; i < memberCount; i++) {
+ if (!isCacheViewComplete(caches[i].getCacheManager().getMembers(), caches[i].getCacheManager().getAddress(), memberCount, barfIfTooManyMembers)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public static boolean areCacheViewsComplete(boolean barfIfTooManyMembers, CacheManager... cacheManagers) {
+ if (cacheManagers == null) throw new NullPointerException("Cache Manager array is null");
+ int memberCount = cacheManagers.length;
+
+ for (int i = 0; i < memberCount; i++) {
+ if (!isCacheViewComplete(cacheManagers[i].getMembers(), cacheManagers[i].getAddress(), memberCount, barfIfTooManyMembers)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+// /**
+// * @param cache
+// * @param memberCount
+// */
+// public static boolean isCacheViewComplete(Cache cache, int memberCount) {
+// List members = cache.getCacheManager().getMembers();
+// if (members == null || memberCount > members.size()) {
+// return false;
+// } else if (memberCount < members.size()) {
+// // This is an exceptional condition
+// StringBuilder sb = new StringBuilder("Cache at address ");
+// sb.append(cache.getCacheManager().getAddress());
+// sb.append(" had ");
+// sb.append(members.size());
+// sb.append(" members; expecting ");
+// sb.append(memberCount);
+// sb.append(". Members were (");
+// for (int j = 0; j < members.size(); j++) {
+// if (j > 0) {
+// sb.append(", ");
+// }
+// sb.append(members.get(j));
+// }
+// sb.append(')');
+//
+// throw new IllegalStateException(sb.toString());
+// }
+//
+// return true;
+// }
+
+ /**
+ * @param c
+ * @param memberCount
+ */
+ public static boolean isCacheViewComplete(Cache c, int memberCount) {
+ return isCacheViewComplete(c.getCacheManager().getMembers(), c.getCacheManager().getAddress(), memberCount, true);
+ }
+
+ public static boolean isCacheViewComplete(List members, Address address, int memberCount, boolean barfIfTooManyMembers) {
+ if (members == null || memberCount > members.size()) {
+ return false;
+ } else if (memberCount < members.size()) {
+ if (barfIfTooManyMembers) {
+ // This is an exceptional condition
+ StringBuilder sb = new StringBuilder("Cache at address ");
+ sb.append(address);
+ sb.append(" had ");
+ sb.append(members.size());
+ sb.append(" members; expecting ");
+ sb.append(memberCount);
+ sb.append(". Members were (");
+ for (int j = 0; j < members.size(); j++) {
+ if (j > 0) {
+ sb.append(", ");
+ }
+ sb.append(members.get(j));
+ }
+ sb.append(')');
+
+ throw new IllegalStateException(sb.toString());
+ } else return false;
+ }
+
+ return true;
+ }
+
+
+ /**
+ * Puts the current thread to sleep for the desired number of ms, suppressing any exceptions.
+ *
+ * @param sleeptime number of ms to sleep
+ */
+ public static void sleepThread(long sleeptime) {
+ try {
+ Thread.sleep(sleeptime);
+ }
+ catch (InterruptedException ie) {
+ }
+ }
+
+ public static void sleepRandom(int maxTime) {
+ sleepThread(random.nextInt(maxTime));
+ }
+
+ public static void recursiveFileRemove(String directoryName) {
+ File file = new File(directoryName);
+ recursiveFileRemove(file);
+ }
+
+ public static void recursiveFileRemove(File file) {
+ if (file.exists()) {
+ System.out.println("Deleting file " + file);
+ recursivedelete(file);
+ }
+ }
+
+ private static void recursivedelete(File f) {
+ if (f.isDirectory()) {
+ File[] files = f.listFiles();
+ for (File file : files) {
+ recursivedelete(file);
+ }
+ }
+ //System.out.println("File " + f.toURI() + " deleted = " + f.delete());
+ f.delete();
+ }
+
+ public static void killTreeCaches(Collection treeCaches) {
+ if (treeCaches != null) killTreeCaches((TreeCache[]) treeCaches.toArray(new TreeCache[]{}));
+ }
+
+ public static void killCaches(Collection caches) {
+ if (caches != null) killCaches((Cache[]) caches.toArray(new Cache[]{}));
+ }
+
+ public static void killTreeCaches(TreeCache... treeCaches) {
+ for (TreeCache tc : treeCaches) {
+ if (tc != null) killCaches(tc.getCache());
+ }
+ }
+
+ public static void killCacheManagers(CacheManager... cacheManagers) {
+ if (cacheManagers != null) {
+ for (CacheManager cm : cacheManagers) {
+ if (cm != null) cm.stop();
+ }
+ }
+ }
+
+ public static void killCacheManagers(Collection<CacheManager> cacheManagers) {
+ killCacheManagers(cacheManagers.toArray(new CacheManager[cacheManagers.size()]));
+ }
+
+ /**
+ * Kills a cache - stops it, clears any data in any cache loaders, and rolls back any associated txs
+ */
+ public static void killCaches(Cache... caches) {
+ for (Cache c : caches) {
+ try {
+ if (c != null && c.getStatus() == ComponentStatus.RUNNING) {
+ TransactionManager tm = getTransactionManager(c);
+ if (tm != null) {
+ try {
+ tm.rollback();
+ }
+ catch (Exception e) {
+ // don't care
+ }
+ }
+ c.stop();
+ }
+ }
+ catch (Throwable t) {
+
+ }
+ }
+ }
+
+ /**
+ * Clears transaction with the current thread in the given transaction manager.
+ *
+ * @param txManager a TransactionManager to be cleared
+ */
+ public static void killTransaction(TransactionManager txManager) {
+ if (txManager != null) {
+ try {
+ txManager.rollback();
+ }
+ catch (Exception e) {
+ // don't care
+ }
+ }
+ }
+
+
+ /**
+ * Clears any associated transactions with the current thread in the caches' transaction managers.
+ */
+ public static void killTransactions(Cache... caches) {
+ for (Cache c : caches) {
+ if (c != null && c.getStatus() == ComponentStatus.RUNNING) {
+ TransactionManager tm = getTransactionManager(c);
+ if (tm != null) {
+ try {
+ tm.rollback();
+ }
+ catch (Exception e) {
+ // don't care
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * For testing only - introspects a cache and extracts the ComponentRegistry
+ *
+ * @param cache cache to introspect
+ * @return component registry
+ */
+ public static ComponentRegistry extractComponentRegistry(Cache cache) {
+ return (ComponentRegistry) extractField(cache, "componentRegistry");
+ }
+
+ public static GlobalComponentRegistry extractGlobalComponentRegistry(CacheManager cacheManager) {
+ return (GlobalComponentRegistry) extractField(cacheManager, "globalComponentRegistry");
+ }
+
+ public static LockManager extractLockManager(Cache cache) {
+ return extractComponentRegistry(cache).getComponent(LockManager.class);
+ }
+
+ /**
+ * For testing only - introspects a cache and extracts the ComponentRegistry
+ *
+ * @param ci interceptor chain to introspect
+ * @return component registry
+ */
+ public static ComponentRegistry extractComponentRegistry(InterceptorChain ci) {
+ return (ComponentRegistry) extractField(ci, "componentRegistry");
+ }
+
+
+ /**
+ * Replaces the existing interceptor chain in the cache wih one represented by the interceptor passed in. This
+ * utility updates dependencies on all components that rely on the interceptor chain as well.
+ *
+ * @param cache cache that needs to be altered
+ * @param interceptor the first interceptor in the new chain.
+ */
+ public static void replaceInterceptorChain(Cache<?, ?> cache, CommandInterceptor interceptor) {
+ ComponentRegistry cr = extractComponentRegistry(cache);
+ // make sure all interceptors here are wired.
+ CommandInterceptor i = interceptor;
+ do {
+ cr.wireDependencies(i);
+ }
+ while ((i = i.getNext()) != null);
+
+ InterceptorChain inch = cr.getComponent(InterceptorChain.class);
+ inch.setFirstInChain(interceptor);
+ }
+
+ /**
+ * Retrieves the remote delegate for a given cache. It is on this remote delegate that the JGroups RPCDispatcher
+ * invokes remote methods.
+ *
+ * @param cache cache instance for which a remote delegate is to be retrieved
+ * @return remote delegate, or null if the cacge is not configured for replication.
+ */
+ public static CacheDelegate getInvocationDelegate(Cache cache) {
+ return (CacheDelegate) cache;
+ }
+
+ /**
+ * Blocks until the cache has reached a specified state.
+ *
+ * @param cache cache to watch
+ * @param cacheStatus status to wait for
+ * @param timeout timeout to wait for
+ */
+ public static void blockUntilCacheStatusAchieved(Cache cache, ComponentStatus cacheStatus, long timeout) {
+ AdvancedCache spi = cache.getAdvancedCache();
+ long killTime = System.currentTimeMillis() + timeout;
+ while (System.currentTimeMillis() < killTime) {
+ if (spi.getStatus() == cacheStatus) return;
+ sleepThread(50);
+ }
+ throw new RuntimeException("Timed out waiting for condition");
+ }
+
+ public static void replicateCommand(Cache cache, VisitableCommand command) throws Throwable {
+ ComponentRegistry cr = extractComponentRegistry(cache);
+ InterceptorChain ic = cr.getComponent(InterceptorChain.class);
+ ic.invoke(command);
+ }
+
+ public static void blockUntilViewsReceived(int timeout, List caches) {
+ blockUntilViewsReceived((Cache[]) caches.toArray(new Cache[]{}), timeout);
+ }
+
+
+ public static CommandsFactory extractCommandsFactory(Cache<Object, Object> cache) {
+ return (CommandsFactory) extractField(cache, "commandsFactory");
+ }
+
+ public static void dumpCacheContents(List caches) {
+ System.out.println("**** START: Cache Contents ****");
+ int count = 1;
+ for (Object o : caches) {
+ Cache c = (Cache) o;
+ if (c == null) {
+ System.out.println(" ** Cache " + count + " is null!");
+ } else {
+ System.out.println(" ** Cache " + count + " is " + c.getCacheManager().getAddress());
+ }
+ count++;
+ }
+ System.out.println("**** END: Cache Contents ****");
+ }
+
+ public static void dumpCacheContents(Cache... caches) {
+ dumpCacheContents(Arrays.asList(caches));
+ }
+
+ /**
+ * Extracts a component of a given type from the cache's internal component registry
+ *
+ * @param cache
+ * @param componentType
+ * @param <T>
+ * @return
+ */
+ public static <T> T extractComponent(Cache cache, Class<T> componentType) {
+ ComponentRegistry cr = extractComponentRegistry(cache);
+ return cr.getComponent(componentType);
+ }
+
+ public static TransactionManager getTransactionManager(Cache cache) {
+ return cache == null ? null : extractComponent(cache, TransactionManager.class);
+ }
+
+ /**
+ * Replaces a component in a running cache
+ *
+ * @param cache cache in which to replace component
+ * @param componentType component type of which to replace
+ * @param replacementComponent new instance
+ * @param rewire if true, ComponentRegistry.rewire() is called after replacing.
+ * @return the original component that was replaced
+ */
+ public static <T> T replaceComponent(Cache<?, ?> cache, Class<T> componentType, T replacementComponent, boolean rewire) {
+ ComponentRegistry cr = extractComponentRegistry(cache);
+ T old = cr.getComponent(componentType);
+ cr.registerComponent(replacementComponent, componentType);
+ if (rewire) cr.rewire();
+ return old;
+ }
+
+ /**
+ * Replaces a component in a running cache manager (global component registry)
+ *
+ * @param cacheManager cache in which to replace component
+ * @param componentType component type of which to replace
+ * @param replacementComponent new instance
+ * @param rewire if true, ComponentRegistry.rewire() is called after replacing.
+ * @return the original component that was replaced
+ */
+ public static <T> T replaceComponent(CacheManager cacheManager, Class<T> componentType, T replacementComponent, boolean rewire) {
+ GlobalComponentRegistry cr = extractGlobalComponentRegistry(cacheManager);
+ T old = cr.getComponent(componentType);
+ cr.registerComponent(replacementComponent, componentType);
+ if (rewire) {
+ cr.rewire();
+ cr.rewireNamedRegistries();
+ }
+ return old;
+ }
+
+ public static CacheManager createClusteredCacheManager() {
+ GlobalConfiguration globalConfiguration = GlobalConfiguration.getClusteredDefault();
+ Properties newTransportProps = new Properties();
+ newTransportProps.put(JGroupsTransport.CONFIGURATION_STRING, JGroupsConfigBuilder.getJGroupsConfig());
+ globalConfiguration.setTransportProperties(newTransportProps);
+ return new DefaultCacheManager(globalConfiguration);
+ }
+
+ public static CacheManager createLocalCacheManager() {
+ GlobalConfiguration globalConfiguration = GlobalConfiguration.getNonClusteredDefault();
+ return new DefaultCacheManager(globalConfiguration);
+ }
+}
Property changes on: core/branches/flat/src/test/java/org/horizon/test/TestingUtil.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Added: core/branches/flat/src/test/java/org/horizon/test/testng/SuiteResourcesAndLogTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/test/testng/SuiteResourcesAndLogTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/test/testng/SuiteResourcesAndLogTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -0,0 +1,58 @@
+package org.horizon.test.testng;
+
+import org.horizon.test.TestingUtil;
+import org.testng.annotations.AfterSuite;
+import org.testng.annotations.BeforeSuite;
+import org.testng.annotations.Test;
+
+import java.io.File;
+
+/**
+ * This class makes sure that all files are being deleted after each test run. It also logs testsuite information.
+ *
+ * @author Mircea.Markus(a)jboss.com
+ */
+@Test (groups = "functional", testName = "test.testng.SuiteResourcesAndLogTest")
+public class SuiteResourcesAndLogTest {
+
+ @BeforeSuite
+ public void removeTempDir()
+ {
+ TestingUtil.recursiveFileRemove(TestingUtil.TEST_FILES);
+ System.out.println("Removing all the files from " + TestingUtil.TEST_FILES);
+ File file = new File(TestingUtil.TEST_FILES);
+ if (file.exists())
+ {
+ System.err.println("!!!!!!!!!!!!! Directory '" + TestingUtil.TEST_FILES + "' should have been deleted!!!");
+ }
+ else
+ {
+ System.out.println("Successfully removed folder: '" + TestingUtil.TEST_FILES + "'");
+ }
+ }
+
+ @BeforeSuite
+ @AfterSuite
+ public void printEnvInformation()
+ {
+ System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~ ENVIRONMENT INFO ~~~~~~~~~~~~~~~~~~~~~~~~~~");
+ String bindAddress = System.getProperty("bind.address");
+ System.out.println("bind.address = " + bindAddress);
+// //todo for some funny reasons MVN ignores bind.address passed in. This is a hack..
+// if (bindAddress == null)
+// {
+// System.out.println("Setting bind.address to 127.0.0.1 as it is missing!!!");
+// System.setProperty("bind.address","127.0.0.1");
+// }
+ System.out.println("java.runtime.version = " + System.getProperty("java.runtime.version"));
+ System.out.println("java.runtime.name =" + System.getProperty("java.runtime.name"));
+ System.out.println("java.vm.version = " + System.getProperty("java.vm.version"));
+ System.out.println("java.vm.vendor = " + System.getProperty("java.vm.vendor"));
+ System.out.println("os.name = " + System.getProperty("os.name"));
+ System.out.println("os.version = " + System.getProperty("os.version"));
+ System.out.println("sun.arch.data.model = " + System.getProperty("sun.arch.data.model"));
+ System.out.println("sun.cpu.endian = " + System.getProperty("sun.cpu.endian"));
+ System.out.println("jgroups.stack = " + System.getProperty("jgroups.stack"));
+ System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~ ENVIRONMENT INFO ~~~~~~~~~~~~~~~~~~~~~~~~~~");
+ }
+}
Property changes on: core/branches/flat/src/test/java/org/horizon/test/testng/SuiteResourcesAndLogTest.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Added: core/branches/flat/src/test/java/org/horizon/test/testng/UnitTestTestNGListener.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/test/testng/UnitTestTestNGListener.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/test/testng/UnitTestTestNGListener.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -0,0 +1,73 @@
+package org.horizon.test.testng;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.testng.IClass;
+import org.testng.ITestContext;
+import org.testng.ITestListener;
+import org.testng.ITestResult;
+
+/**
+ * @author dpospisi(a)redhat.com
+ * @author Mircea.Markus(a)jboss.com
+ */
+public class UnitTestTestNGListener implements ITestListener {
+
+ /**
+ * Holds test classes actually running in all threads.
+ */
+ private ThreadLocal<IClass> threadTestClass = new ThreadLocal<IClass>();
+ Log log = LogFactory.getLog(UnitTestTestNGListener.class);
+
+ private int failed = 0;
+ private int succeded = 0;
+ private int skipped = 0;
+
+ public void onTestStart(ITestResult res) {
+ log.info("Starting test " + getTestDesc(res));
+ threadTestClass.set(res.getTestClass());
+ }
+
+ synchronized public void onTestSuccess(ITestResult arg0) {
+ System.out.println(getThreadId() + " Test " + getTestDesc(arg0) + " succeded.");
+ log.info("Test succeded " + getTestDesc(arg0) + ".");
+ succeded++;
+ printStatus();
+ }
+
+ synchronized public void onTestFailure(ITestResult arg0) {
+ System.out.println(getThreadId() + " Test " + getTestDesc(arg0) + " failed.");
+ if (arg0.getThrowable() != null) log.error("Test failed " + getTestDesc(arg0), arg0.getThrowable());
+ failed++;
+ printStatus();
+ }
+
+ synchronized public void onTestSkipped(ITestResult arg0) {
+ System.out.println(getThreadId() + " Test " + getTestDesc(arg0) + " skipped.");
+ log.info(" Test " + getTestDesc(arg0) + " skipped.");
+ if (arg0.getThrowable() != null) log.error("Test skipped : " + arg0.getThrowable(), arg0.getThrowable());
+ skipped++;
+ printStatus();
+ }
+
+ public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
+ }
+
+ public void onStart(ITestContext arg0) {
+ }
+
+ public void onFinish(ITestContext arg0) {
+ }
+
+ private String getThreadId() {
+ return "[" + Thread.currentThread().getName() + "]";
+ }
+
+ private String getTestDesc(ITestResult res) {
+ return res.getMethod().getMethodName() + "(" + res.getTestClass().getName() + ")";
+ }
+
+ private void printStatus() {
+ System.out.println("Testsuite execution progress: tests succeded " + succeded + ", failed " + failed + ", skipped " + skipped + ".");
+ }
+}
Property changes on: core/branches/flat/src/test/java/org/horizon/test/testng/UnitTestTestNGListener.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Modified: core/branches/flat/src/test/java/org/horizon/tx/LocalModeTxTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/tx/LocalModeTxTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/tx/LocalModeTxTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -22,61 +22,53 @@
package org.horizon.tx;
import org.horizon.Cache;
-import org.horizon.UnitTestCacheManager;
import org.horizon.config.Configuration;
+import org.horizon.manager.CacheManager;
+import org.horizon.test.TestingUtil;
+import org.horizon.test.SingleCacheManagerTest;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
import org.testng.annotations.Test;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
-@Test(groups = "functional")
-public class LocalModeTxTest {
- private Cache<String, String> createCache() {
+@Test(groups = "functional", testName = "tx.LocalModeTxTest")
+public class LocalModeTxTest extends SingleCacheManagerTest {
+
+ Cache c;
+
+ protected CacheManager createCacheManager() {
Configuration cfg = new Configuration();
cfg.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- UnitTestCacheManager cm = new UnitTestCacheManager(cfg);
- return cm.createCache("test");
+ CacheManager cm = TestingUtil.createLocalCacheManager();
+ cm.defineCache("test", cfg);
+ c = cm.getCache("test");
+ return cm;
}
public void testTxCommit1() throws Exception {
- Cache c = null;
- try {
- c = createCache();
- TransactionManager tm = TestingUtil.getTransactionManager(c);
- tm.begin();
- c.put("key", "value");
- Transaction t = tm.suspend();
- assert c.isEmpty();
- tm.resume(t);
- tm.commit();
- assert !c.isEmpty();
- }
- finally {
- TestingUtil.killCaches(c);
- }
+ TransactionManager tm = TestingUtil.getTransactionManager(c);
+ tm.begin();
+ c.put("key", "value");
+ Transaction t = tm.suspend();
+ assert c.isEmpty();
+ tm.resume(t);
+ tm.commit();
+ assert !c.isEmpty();
}
public void testTxCommit2() throws Exception {
- Cache c = null;
- try {
- c = createCache();
- TransactionManager tm = TestingUtil.getTransactionManager(c);
- c.put("key", "old");
- tm.begin();
- assert c.get("key").equals("old");
- c.put("key", "value");
- assert c.get("key").equals("value");
- Transaction t = tm.suspend();
- assert c.get("key").equals("old");
- tm.resume(t);
- tm.commit();
- assert c.get("key").equals("value");
- assert !c.isEmpty();
- }
- finally {
- TestingUtil.killCaches(c);
- }
+ TransactionManager tm = TestingUtil.getTransactionManager(c);
+ c.put("key", "old");
+ tm.begin();
+ assert c.get("key").equals("old");
+ c.put("key", "value");
+ assert c.get("key").equals("value");
+ Transaction t = tm.suspend();
+ assert c.get("key").equals("old");
+ tm.resume(t);
+ tm.commit();
+ assert c.get("key").equals("value");
+ assert !c.isEmpty();
}
}
Modified: core/branches/flat/src/test/java/org/horizon/tx/MarkAsRollbackTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/tx/MarkAsRollbackTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/tx/MarkAsRollbackTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,77 +1,66 @@
package org.horizon.tx;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.horizon.Cache;
-import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
+import org.horizon.manager.CacheManager;
+import org.horizon.manager.DefaultCacheManager;
+import org.horizon.test.SingleCacheManagerTest;
+import org.horizon.test.TestingUtil;
import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
import org.testng.annotations.Test;
import javax.transaction.RollbackException;
import javax.transaction.TransactionManager;
-@Test(groups = "functional")
-public class MarkAsRollbackTest {
- private static final Log log = LogFactory.getLog(MarkAsRollbackTest.class);
+@Test(groups = "functional", testName = "tx.MarkAsRollbackTest")
+public class MarkAsRollbackTest extends SingleCacheManagerTest {
- public void testMarkAsRollbackAfterMods() throws Exception {
+ protected CacheManager createCacheManager() throws Exception {
Configuration c = new Configuration();
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- Cache<String, String> cache = new UnitTestCacheFactory<String, String>().createCache(c);
- try {
- TransactionManager tm = TestingUtil.getTransactionManager(cache);
- assert tm != null;
- tm.begin();
- cache.put("k", "v");
- assert cache.get("k").equals("v");
- tm.setRollbackOnly();
- try {
- tm.commit();
- assert false : "Should have rolled back";
- }
- catch (RollbackException expected) {
- }
+ CacheManager cm = new DefaultCacheManager(c);
+ cache = cm.getCache();
+ return cm;
+ }
- assert tm.getTransaction() == null : "There should be no transaction in scope anymore!";
- assert cache.get("k") == null : "Expected a null but was " + cache.get("k");
+ public void testMarkAsRollbackAfterMods() throws Exception {
+
+ TransactionManager tm = TestingUtil.getTransactionManager(cache);
+ assert tm != null;
+ tm.begin();
+ cache.put("k", "v");
+ assert cache.get("k").equals("v");
+ tm.setRollbackOnly();
+ try {
+ tm.commit();
+ assert false : "Should have rolled back";
}
- finally {
- log.warn("Cleaning up");
- TestingUtil.killCaches(cache);
+ catch (RollbackException expected) {
}
+
+ assert tm.getTransaction() == null : "There should be no transaction in scope anymore!";
+ assert cache.get("k") == null : "Expected a null but was " + cache.get("k");
}
public void testMarkAsRollbackBeforeMods() throws Exception {
- Configuration c = new Configuration();
- c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- Cache<String, String> cache = new UnitTestCacheFactory<String, String>().createCache(c);
+ TransactionManager tm = TestingUtil.getTransactionManager(cache);
+ assert tm != null;
+ tm.begin();
+ tm.setRollbackOnly();
try {
- TransactionManager tm = TestingUtil.getTransactionManager(cache);
- assert tm != null;
- tm.begin();
- tm.setRollbackOnly();
- try {
- cache.put("k", "v");
- assert false : "Should have throw an illegal state exception";
- } catch (IllegalStateException expected) {
+ cache.put("k", "v");
+ assert false : "Should have throw an illegal state exception";
+ } catch (IllegalStateException expected) {
- }
- try {
- tm.commit();
- assert false : "Should have rolled back";
- }
- catch (RollbackException expected) {
-
- }
-
- assert tm.getTransaction() == null : "There should be no transaction in scope anymore!";
- assert cache.get("k") == null : "Expected a null but was " + cache.get("k");
}
- finally {
- log.warn("Cleaning up");
- TestingUtil.killCaches(cache);
+ try {
+ tm.commit();
+ assert false : "Should have rolled back";
}
+ catch (RollbackException expected) {
+
+ }
+
+ assert tm.getTransaction() == null : "There should be no transaction in scope anymore!";
+ assert cache.get("k") == null : "Expected a null but was " + cache.get("k");
}
}
Modified: core/branches/flat/src/test/java/org/horizon/util/BidirectionalLinkedHashMapTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/util/BidirectionalLinkedHashMapTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/util/BidirectionalLinkedHashMapTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -5,7 +5,7 @@
import java.util.Iterator;
import java.util.Map;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "util.BidirectionalLinkedHashMapTest")
public class BidirectionalLinkedHashMapTest {
public void testIterators() {
BidirectionalLinkedHashMap<Integer, Object> map = new BidirectionalLinkedHashMap<Integer, Object>();
Deleted: core/branches/flat/src/test/java/org/horizon/util/UnitTestTestNGListener.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/util/UnitTestTestNGListener.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/util/UnitTestTestNGListener.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -1,93 +0,0 @@
-/*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
-
-package org.horizon.util;
-
-import org.testng.IClass;
-import org.testng.ITestContext;
-import org.testng.ITestListener;
-import org.testng.ITestResult;
-
-/**
- * @author dpospisi
- * @since 1.0
- */
-public class UnitTestTestNGListener implements ITestListener {
-
- /**
- * Holds test classes actually running in all threads.
- */
- private ThreadLocal<IClass> threadTestClass = new ThreadLocal<IClass>();
-
- private int failed = 0;
- private int succeded = 0;
- private int skipped = 0;
-
- public void onTestStart(ITestResult res) {
- System.out.println(getThreadId() + " Starting test " + getTestDesc(res));
-
- /*
- IClass testClass = threadTestClass.get();
- if ((testClass != null) && (! res.getTestClass().equals(testClass))) {
-
- System.out.println(getThreadId() + " New test class" + res.getTestClass() + ", was " + testClass);
-
- // the thread has started testing a new test class
-
- // clean all possibly running caches created in current thread
- boolean cleaned = new UnitTestCacheFactory().cleanUp();
- if (cleaned) {
- // previous test left a cache
- System.out.println(getThreadId() +" WARNING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
- System.out.println(getThreadId() +" A test method in " + testClass.getName() + " did not clean all cache instances properly.");
- System.out.println(getThreadId() +" Use UnitTestCacheFactory.cleanUp() or TestngUtil.killCaches(...) ");
- System.out.println(getThreadId() +" WARNING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
- }
- }
- */
-
- threadTestClass.set(res.getTestClass());
- }
-
- synchronized public void onTestSuccess(ITestResult arg0) {
- System.out.println(getThreadId() + " Test " + getTestDesc(arg0) + " succeded.");
- succeded++;
- printStatus();
- }
-
- synchronized public void onTestFailure(ITestResult arg0) {
- System.out.println(getThreadId() + " Test " + getTestDesc(arg0) + " failed.");
- failed++;
- printStatus();
- }
-
- synchronized public void onTestSkipped(ITestResult arg0) {
- System.out.println(getThreadId() + " Test " + getTestDesc(arg0) + " skipped.");
- skipped++;
- printStatus();
- }
-
- public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
- }
-
- public void onStart(ITestContext arg0) {
- }
-
- public void onFinish(ITestContext arg0) {
- }
-
- private String getThreadId() {
- return "[" + Thread.currentThread().getName() + "]";
- }
-
- private String getTestDesc(ITestResult res) {
- return res.getMethod().getMethodName() + "(" + res.getTestClass().getName() + ")";
- }
-
- private void printStatus() {
- System.out.println("Testsuite execution progress: tests succeded " + succeded + ", failed " + failed + ", skipped " + skipped + ".");
- }
-
-}
Modified: core/branches/flat/src/test/java/org/horizon/util/VisitableLinkedHashSetTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/util/VisitableLinkedHashSetTest.java 2009-02-17 14:31:02 UTC (rev 7698)
+++ core/branches/flat/src/test/java/org/horizon/util/VisitableLinkedHashSetTest.java 2009-02-17 14:38:40 UTC (rev 7699)
@@ -5,7 +5,7 @@
import java.util.Iterator;
import java.util.Set;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "util.VisitableLinkedHashSetTest")
public class VisitableLinkedHashSetTest {
public void testVisitableSet() {
@@ -66,4 +66,4 @@
}
assert index == -1 : "Was " + index + ", instead of -1";
}
-}
\ No newline at end of file
+}
Added: core/branches/flat/src/test/resources/stacks/tcp.xml
===================================================================
--- core/branches/flat/src/test/resources/stacks/tcp.xml (rev 0)
+++ core/branches/flat/src/test/resources/stacks/tcp.xml 2009-02-17 14:38:40 UTC (rev 7699)
@@ -0,0 +1,59 @@
+<config>
+ <TCP bind_port="7800"
+ port_range="10"
+ loopback="true"
+ recv_buf_size="20000000"
+ send_buf_size="640000"
+ discard_incompatible_packets="true"
+ max_bundle_size="64000"
+ max_bundle_timeout="30"
+ enable_bundling="false"
+ use_send_queues="false"
+ sock_conn_timeout="300"
+ skip_suspected_members="true"
+ thread_pool.enabled="true"
+ thread_pool.min_threads="1"
+ thread_pool.max_threads="25"
+ thread_pool.keep_alive_time="5000"
+ thread_pool.queue_enabled="false"
+ thread_pool.queue_max_size="100"
+ thread_pool.rejection_policy="run"
+
+ oob_thread_pool.enabled="true"
+ oob_thread_pool.min_threads="1"
+ oob_thread_pool.max_threads="8"
+ oob_thread_pool.keep_alive_time="5000"
+ oob_thread_pool.queue_enabled="false"
+ oob_thread_pool.queue_max_size="100"
+ oob_thread_pool.rejection_policy="run"/>
+
+ <TCPPING timeout="3000"
+ initial_hosts="127.0.0.1[7800]"
+ port_range="1"
+ num_initial_members="1"/>
+ <MERGE2 max_interval="100000"
+ min_interval="20000"/>
+ <FD_SOCK/>
+ <!--
+ Note that this is an atypically short timeout and a small number of retries
+ configured this way to speed up unit testing, since we know all nodes run in the same JVM
+ and hence failure detections will be very quick.
+ -->
+ <FD timeout="1000" max_tries="5" shun="true"/>
+ <VERIFY_SUSPECT timeout="1500"/>
+ <BARRIER/>
+ <pbcast.NAKACK use_mcast_xmit="false" gc_lag="0"
+ retransmit_timeout="300,600,1200,2400,4800"
+ discard_delivered_msgs="true"/>
+ <pbcast.STABLE stability_delay="1000" desired_avg_gossip="50000"
+ max_bytes="400000"/>
+ <VIEW_SYNC avg_send_interval="60000"/>
+ <pbcast.GMS print_local_addr="false" join_timeout="3000" shun="true"
+ view_bundling="true"/>
+ <FC max_credits="2000000"
+ min_threshold="0.10"/>
+ <FRAG2 frag_size="60000"/>
+ <pbcast.STREAMING_STATE_TRANSFER/>
+ <!-- <pbcast.STATE_TRANSFER/> -->
+ <pbcast.FLUSH timeout="0"/>
+</config>
Property changes on: core/branches/flat/src/test/resources/stacks/tcp.xml
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Added: core/branches/flat/src/test/resources/stacks/udp.xml
===================================================================
--- core/branches/flat/src/test/resources/stacks/udp.xml (rev 0)
+++ core/branches/flat/src/test/resources/stacks/udp.xml 2009-02-17 14:38:40 UTC (rev 7699)
@@ -0,0 +1,63 @@
+<config>
+ <UDP mcast_addr="228.10.10.10"
+ mcast_port="45588"
+ tos="8"
+ ucast_recv_buf_size="20000000"
+ ucast_send_buf_size="640000"
+ mcast_recv_buf_size="25000000"
+ mcast_send_buf_size="640000"
+ loopback="false"
+ discard_incompatible_packets="true"
+ max_bundle_size="64000"
+ max_bundle_timeout="30"
+ use_incoming_packet_handler="true"
+ ip_ttl="2"
+ enable_bundling="false"
+ enable_diagnostics="true"
+
+ use_concurrent_stack="true"
+
+ thread_naming_pattern="pl"
+
+ thread_pool.enabled="true"
+ thread_pool.min_threads="1"
+ thread_pool.max_threads="25"
+ thread_pool.keep_alive_time="30000"
+ thread_pool.queue_enabled="false"
+ thread_pool.queue_max_size="100"
+ thread_pool.rejection_policy="Run"
+
+ oob_thread_pool.enabled="true"
+ oob_thread_pool.min_threads="1"
+ oob_thread_pool.max_threads="4"
+ oob_thread_pool.keep_alive_time="10000"
+ oob_thread_pool.queue_enabled="false"
+ oob_thread_pool.queue_max_size="10"
+ oob_thread_pool.rejection_policy="Run"/>
+
+ <PING timeout="2000" num_initial_members="3"/>
+ <MERGE2 max_interval="30000" min_interval="10000"/>
+ <FD_SOCK/>
+ <!--
+ Note that this is an atypically short timeout and a small number of retries
+ configured this way to speed up unit testing, since we know all nodes run in the same JVM
+ and hence failure detections will be very quick.
+ -->
+ <FD timeout="1000" max_tries="2" shun="true"/>
+ <VERIFY_SUSPECT timeout="250"/>
+ <!-- this is a more typical configuration of FD and VERIFY_SUSPECT-->
+ <!--<FD timeout="10000" max_tries="5" shun="true"/>-->
+ <!--<VERIFY_SUSPECT timeout="1500"/>-->
+ <pbcast.NAKACK use_mcast_xmit="false" gc_lag="0"
+ retransmit_timeout="300,600,900,1200"
+ discard_delivered_msgs="true"/>
+ <UNICAST timeout="300,600,900,1200"/>
+ <pbcast.STABLE stability_delay="1000" desired_avg_gossip="50000"
+ max_bytes="400000"/>
+ <pbcast.GMS print_local_addr="false" join_timeout="1000" shun="false"
+ view_bundling="true" view_ack_collection_timeout="1000"/>
+ <FRAG2 frag_size="60000"/>
+ <pbcast.STREAMING_STATE_TRANSFER/>
+ <!-- <pbcast.STATE_TRANSFER/> -->
+ <pbcast.FLUSH timeout="0"/>
+</config>
Property changes on: core/branches/flat/src/test/resources/stacks/udp.xml
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
15 years, 10 months
JBoss Cache SVN: r7698 - core/trunk/src/test/java/org/jboss/cache.
by jbosscache-commits@lists.jboss.org
Author: mircea.markus
Date: 2009-02-17 09:31:02 -0500 (Tue, 17 Feb 2009)
New Revision: 7698
Modified:
core/trunk/src/test/java/org/jboss/cache/TestNameVerifier.java
Log:
fix for linux
Modified: core/trunk/src/test/java/org/jboss/cache/TestNameVerifier.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/TestNameVerifier.java 2009-02-17 01:07:15 UTC (rev 7697)
+++ core/trunk/src/test/java/org/jboss/cache/TestNameVerifier.java 2009-02-17 14:31:02 UTC (rev 7698)
@@ -20,7 +20,7 @@
*/
@Test(groups = "functional", testName = "TestNameVerifier")
public class TestNameVerifier {
- String dir = "src\\test\\java\\org\\jboss\\cache";
+ String dir = "src/test/java/org/jboss/cache";
Pattern packageLinePattern = Pattern.compile("package org.jboss.cache[^;]*");
Pattern classLinePattern = Pattern.compile("(abstract\\s*)??(public\\s*)(abstract\\s*)??class [^\\s]*");
15 years, 10 months
JBoss Cache SVN: r7697 - in core/branches/flat/src: main/java/org/horizon/commands/write and 10 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2009-02-16 20:07:15 -0500 (Mon, 16 Feb 2009)
New Revision: 7697
Added:
core/branches/flat/src/test/java/org/horizon/loader/CacheLoaderFunctionalTest.java
core/branches/flat/src/test/java/org/horizon/loader/decorators/
core/branches/flat/src/test/java/org/horizon/loader/decorators/AsyncTest.java
core/branches/flat/src/test/java/org/horizon/loader/decorators/ReadOnlyCacheStoreTest.java
core/branches/flat/src/test/java/org/horizon/loader/decorators/SingletonStoreTest.java
core/branches/flat/src/test/java/org/horizon/util/internals/ViewChangeListener.java
Removed:
core/branches/flat/src/test/java/org/horizon/loader/AsyncTest.java
Modified:
core/branches/flat/src/main/java/org/horizon/AdvancedCache.java
core/branches/flat/src/main/java/org/horizon/CacheDelegate.java
core/branches/flat/src/main/java/org/horizon/commands/write/PutKeyValueCommand.java
core/branches/flat/src/main/java/org/horizon/commands/write/PutMapCommand.java
core/branches/flat/src/main/java/org/horizon/commands/write/RemoveCommand.java
core/branches/flat/src/main/java/org/horizon/commands/write/ReplaceCommand.java
core/branches/flat/src/main/java/org/horizon/container/MVCCEntry.java
core/branches/flat/src/main/java/org/horizon/container/ReadCommittedEntry.java
core/branches/flat/src/main/java/org/horizon/container/UnsortedDataContainer.java
core/branches/flat/src/main/java/org/horizon/factories/EntryFactory.java
core/branches/flat/src/main/java/org/horizon/factories/EntryFactoryImpl.java
core/branches/flat/src/main/java/org/horizon/interceptors/CacheLoaderInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/CacheStoreInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/LockingInterceptor.java
core/branches/flat/src/main/java/org/horizon/loader/AbstractCacheLoaderConfig.java
core/branches/flat/src/main/java/org/horizon/loader/AbstractCacheStore.java
core/branches/flat/src/main/java/org/horizon/loader/CacheLoaderManagerImpl.java
core/branches/flat/src/main/java/org/horizon/loader/CacheStore.java
core/branches/flat/src/main/java/org/horizon/loader/StoredEntry.java
core/branches/flat/src/main/java/org/horizon/loader/decorators/AbstractDelegatingStore.java
core/branches/flat/src/main/java/org/horizon/loader/decorators/AsyncStoreConfig.java
core/branches/flat/src/main/java/org/horizon/loader/decorators/ReadOnlyStore.java
core/branches/flat/src/main/java/org/horizon/loader/decorators/SingletonStore.java
core/branches/flat/src/main/java/org/horizon/loader/decorators/SingletonStoreConfig.java
core/branches/flat/src/test/java/org/horizon/expiry/ExpiryTest.java
core/branches/flat/src/test/java/org/horizon/loader/dummy/DummyInMemoryCacheLoader.java
Log:
Loader tests and interceptor code
Modified: core/branches/flat/src/main/java/org/horizon/AdvancedCache.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/AdvancedCache.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/AdvancedCache.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -1,6 +1,7 @@
package org.horizon;
import org.horizon.batch.BatchContainer;
+import org.horizon.container.DataContainer;
import org.horizon.eviction.EvictionManager;
import org.horizon.factories.ComponentRegistry;
import org.horizon.interceptors.base.CommandInterceptor;
@@ -82,6 +83,8 @@
InvocationContextContainer getInvocationContextContainer();
+ DataContainer getDataContainer();
+
void putForExternalRead(K key, V value, Options... options);
V put(K key, V value, Options... options);
Modified: core/branches/flat/src/main/java/org/horizon/CacheDelegate.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/CacheDelegate.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/CacheDelegate.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -397,6 +397,10 @@
return invocationContextContainer;
}
+ public DataContainer getDataContainer() {
+ return dataContainer;
+ }
+
public CacheManager getCacheManager() {
return cacheManager;
}
@@ -435,19 +439,16 @@
}
public void compact() {
- for (Object key : dataContainer.keySet())
- {
+ for (Object key : dataContainer.keySet()) {
// get the key first, before attempting to serialize stuff since data.get() may deserialize the key if doing
// a hashcode() or equals().
Object value = dataContainer.get(key);
- if (key instanceof MarshalledValue)
- {
+ if (key instanceof MarshalledValue) {
((MarshalledValue) key).compact(true, true);
}
- if (value instanceof MarshalledValue)
- {
+ if (value instanceof MarshalledValue) {
((MarshalledValue) value).compact(true, true);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/commands/write/PutKeyValueCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/write/PutKeyValueCommand.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/commands/write/PutKeyValueCommand.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -95,8 +95,10 @@
if (existing instanceof DeltaAware) toMergeWith = (DeltaAware) existing;
e.setValue(dv.merge(toMergeWith));
o = existing;
+ e.setLifespan(lifespanMillis);
} else {
o = e.setValue(value);
+ e.setLifespan(lifespanMillis);
}
notifier.notifyCacheEntryModified(key, e.getValue(), false, ctx);
}
@@ -161,9 +163,10 @@
@Override
public String toString() {
return "PutKeyValueCommand{" +
- "lifespanMillis=" + lifespanMillis +
+ "key=" + key +
+ ", value=" + value +
+ ", lifespanMillis=" + lifespanMillis +
", putIfAbsent=" + putIfAbsent +
- ", value=" + value +
'}';
}
Modified: core/branches/flat/src/main/java/org/horizon/commands/write/PutMapCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/write/PutMapCommand.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/commands/write/PutMapCommand.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -68,6 +68,7 @@
MVCCEntry me = ctx.lookupEntry(key);
notifier.notifyCacheEntryModified(key, me.getValue(), true, ctx);
me.setValue(e.getValue());
+ me.setLifespan(lifespanMillis);
notifier.notifyCacheEntryModified(key, me.getValue(), false, ctx);
}
return null;
Modified: core/branches/flat/src/main/java/org/horizon/commands/write/RemoveCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/write/RemoveCommand.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/commands/write/RemoveCommand.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -25,6 +25,8 @@
import org.horizon.commands.read.AbstractDataCommand;
import org.horizon.container.MVCCEntry;
import org.horizon.context.InvocationContext;
+import org.horizon.logging.Log;
+import org.horizon.logging.LogFactory;
import org.horizon.notifications.cachelistener.CacheNotifier;
@@ -33,6 +35,8 @@
* @since 1.0
*/
public class RemoveCommand extends AbstractDataCommand implements DataWriteCommand {
+ private static final Log log = LogFactory.getLog(RemoveCommand.class);
+ private static final boolean trace = log.isTraceEnabled();
public static final byte METHOD_ID = 6;
protected CacheNotifier notifier;
boolean successful = true;
@@ -59,6 +63,7 @@
public Object perform(InvocationContext ctx) throws Throwable {
MVCCEntry e = ctx.lookupEntry(key);
if (e == null || e.isNullEntry()) {
+ log.trace("Nothing to remove since the entry is null or we have a null entry");
if (value == null) {
return null;
} else {
Modified: core/branches/flat/src/main/java/org/horizon/commands/write/ReplaceCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/write/ReplaceCommand.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/commands/write/ReplaceCommand.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -67,12 +67,14 @@
if (oldValue == null || oldValue.equals(e.getValue())) {
Object old = e.setValue(newValue);
+ e.setLifespan(lifespanMillis);
return returnValue(old, true);
}
return returnValue(null, false);
} else {
// for remotely originating calls, this doesn't check the status of what is under the key at the moment
Object old = e.setValue(newValue);
+ e.setLifespan(lifespanMillis);
return returnValue(old, true);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/container/MVCCEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/container/MVCCEntry.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/container/MVCCEntry.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -51,4 +51,8 @@
boolean isValid();
void setValid(boolean valid);
+
+ long getLifespan();
+
+ void setLifespan(long lifespan);
}
Modified: core/branches/flat/src/main/java/org/horizon/container/ReadCommittedEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/container/ReadCommittedEntry.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/container/ReadCommittedEntry.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -39,7 +39,6 @@
protected byte flags = 0;
private long lifespan;
-
protected ReadCommittedEntry() {
setValid(true);
}
@@ -51,6 +50,14 @@
this.lifespan = lifespan;
}
+ public long getLifespan() {
+ return lifespan;
+ }
+
+ public void setLifespan(long lifespan) {
+ this.lifespan = lifespan;
+ }
+
public Object getKey() {
return key;
}
Modified: core/branches/flat/src/main/java/org/horizon/container/UnsortedDataContainer.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/container/UnsortedDataContainer.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/container/UnsortedDataContainer.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -22,6 +22,7 @@
package org.horizon.container;
import org.horizon.factories.annotations.Inject;
+import org.horizon.factories.annotations.Stop;
import org.horizon.loader.CacheLoaderManager;
import org.horizon.loader.CacheStore;
import org.horizon.loader.StoredEntry;
@@ -172,6 +173,7 @@
return immortalData.size() + expirableData.size();
}
+ @Stop(priority = 999)
public void clear() {
immortalData.clear();
expirableData.clear();
@@ -205,6 +207,10 @@
return new StoredEntry(key, immortal.getValue());
ExpirableCachedValue ecv = expirableData.get(key);
if (ecv == null) return null;
+ if (ecv.isExpired()) {
+ expirableData.remove(key);
+ return null;
+ }
return new StoredEntry(key, ecv.getValue(), ecv.getCreatedTime(), ecv.getExpiryTime());
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/EntryFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/EntryFactory.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/factories/EntryFactory.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -32,7 +32,7 @@
* @since 1.0
*/
public interface EntryFactory {
- void releaseLock(Object key);
+ void releaseLock(InvocationContext ctx, Object key);
/**
* Attempts to lock a node if the lock isn't already held in the current scope, and records the lock in the context.
@@ -47,11 +47,9 @@
*/
boolean acquireLock(InvocationContext ctx, Object key) throws InterruptedException, TimeoutException;
- MVCCEntry wrapEntryForWriting(InvocationContext ctx, Object key, boolean createIfAbsent, boolean forceLockIfAbsent, long lifespan) throws InterruptedException;
+ MVCCEntry wrapEntryForWriting(InvocationContext ctx, Object key, boolean createIfAbsent, boolean forceLockIfAbsent) throws InterruptedException;
MVCCEntry wrapEntryForReading(InvocationContext ctx, Object key, boolean putInContext, boolean forceWriteLock) throws InterruptedException;
MVCCEntry wrapEntryForReading(InvocationContext ctx, Object key, boolean putInContext) throws InterruptedException;
-
- MVCCEntry createWrappedEntry(Object key, Object value, boolean isForInsert, long lifespan);
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/EntryFactoryImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/EntryFactoryImpl.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/factories/EntryFactoryImpl.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -31,6 +31,7 @@
import org.horizon.factories.annotations.Inject;
import org.horizon.factories.annotations.Start;
import org.horizon.invocation.Options;
+import org.horizon.loader.StoredEntry;
import org.horizon.lock.IsolationLevel;
import org.horizon.lock.LockManager;
import org.horizon.lock.TimeoutException;
@@ -67,8 +68,7 @@
public MVCCEntry createWrappedEntry(Object key, Object value, boolean isForInsert, long lifespan) {
if (value == null && !isForInsert) return useRepeatableRead ? NULL_MARKER : null;
- MVCCEntry mvccEntry = useRepeatableRead ? new RepeatableReadEntry(key, value, lifespan) : new ReadCommittedEntry(key, value, lifespan);
- return mvccEntry;
+ return useRepeatableRead ? new RepeatableReadEntry(key, value, lifespan) : new ReadCommittedEntry(key, value, lifespan);
}
public MVCCEntry wrapEntryForReading(InvocationContext ctx, Object key, boolean putInContext) throws InterruptedException {
@@ -82,12 +82,14 @@
MVCCEntry mvccEntry;
if (forceWriteLock) {
if (trace) log.trace("Forcing lock on reading");
- return wrapEntryForWriting(ctx, key, false, false, -1);
+ return wrapEntryForWriting(ctx, key, false, false);
} else if ((mvccEntry = ctx.lookupEntry(key)) == null) {
if (trace) log.trace("Key " + key + " is not in context, fetching from container.");
// simple implementation. Peek the node, wrap it, put wrapped node in the context.
- Object value = container.get(key);
- mvccEntry = createWrappedEntry(key, value, false, -1);
+ StoredEntry se = container.createEntryForStorage(key);
+ mvccEntry = se == null ?
+ createWrappedEntry(key, null, false, -1) :
+ createWrappedEntry(key, se.getValue(), false, se.getLifespan());
if (mvccEntry != null && putInContext) ctx.putLookedUpEntry(key, mvccEntry);
return mvccEntry;
} else {
@@ -96,7 +98,7 @@
}
}
- public MVCCEntry wrapEntryForWriting(InvocationContext ctx, Object key, boolean createIfAbsent, boolean forceLockIfAbsent, long lifespan) throws InterruptedException {
+ public MVCCEntry wrapEntryForWriting(InvocationContext ctx, Object key, boolean createIfAbsent, boolean forceLockIfAbsent) throws InterruptedException {
MVCCEntry mvccEntry = ctx.lookupEntry(key);
if (createIfAbsent && mvccEntry != null && mvccEntry.isNullEntry()) mvccEntry = null;
if (mvccEntry != null) // exists in context! Just acquire lock if needed, and wrap.
@@ -114,14 +116,14 @@
}
} else {
// else, fetch from dataContainer.
- Object value = container.get(key);
- if (value != null) {
+ StoredEntry storedEntry = container.createEntryForStorage(key);
+ if (storedEntry != null) {
if (trace) log.trace("Retrieved from container.");
// exists in cache! Just acquire lock if needed, and wrap.
// do we need a lock?
boolean needToCopy = false;
if (acquireLock(ctx, key)) needToCopy = true;
- mvccEntry = createWrappedEntry(key, value, false, lifespan);
+ mvccEntry = createWrappedEntry(key, storedEntry.getValue(), false, storedEntry.getLifespan());
ctx.putLookedUpEntry(key, mvccEntry);
if (needToCopy) mvccEntry.copyForUpdate(container, writeSkewCheck);
} else if (createIfAbsent) {
@@ -130,7 +132,7 @@
// now to lock and create the node. Lock first to prevent concurrent creation!
acquireLock(ctx, key);
notifier.notifyCacheEntryCreated(key, true, ctx);
- mvccEntry = createWrappedEntry(key, value, true, lifespan);
+ mvccEntry = createWrappedEntry(key, null, true, -1);
mvccEntry.setCreated(true);
ctx.putLookedUpEntry(key, mvccEntry);
mvccEntry.copyForUpdate(container, writeSkewCheck);
@@ -166,7 +168,7 @@
ctx.addKeyLocked(key);
} else if (!lockManager.lockAndRecord(key, ctx)) {
Object owner = lockManager.getOwner(key);
- throw new TimeoutException("Unable to acquire lock on key [" + key + "] after [" + getLockAcquisitionTImeout(ctx)
+ throw new TimeoutException("Unable to acquire lock on key [" + key + "] after [" + getLockAcquisitionTimeout(ctx)
+ "] milliseconds for requestor [" + lockManager.getLockOwner(ctx) + "]! Lock held by [" + owner + "]");
}
return true;
@@ -174,12 +176,13 @@
return false;
}
- private long getLockAcquisitionTImeout(InvocationContext ctx) {
+ private long getLockAcquisitionTimeout(InvocationContext ctx) {
return ctx.hasOption(Options.ZERO_LOCK_ACQUISITION_TIMEOUT) ?
0 : configuration.getLockAcquisitionTimeout();
}
- public void releaseLock(Object key) {
+ public void releaseLock(InvocationContext ctx, Object key) {
lockManager.unlock(key, lockManager.getOwner(key));
+ ctx.removeKeyLocked(key);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/CacheLoaderInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/CacheLoaderInterceptor.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/CacheLoaderInterceptor.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -37,6 +37,7 @@
import org.horizon.interceptors.base.JmxStatsCommandInterceptor;
import org.horizon.loader.CacheLoader;
import org.horizon.loader.CacheLoaderManager;
+import org.horizon.loader.StoredEntry;
import org.horizon.notifications.cachelistener.CacheNotifier;
import org.horizon.transaction.TransactionTable;
@@ -86,97 +87,82 @@
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
- if (command.getKey() != null) {
- loadIfNeeded(ctx, command.getKey());
- }
+ if (command.getKey() != null) loadIfNeeded(ctx, command.getKey());
return invokeNextInterceptor(ctx, command);
}
@Override
public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable {
- if (command.getKey() != null) {
- loadIfNeeded(ctx, command.getKey());
- }
+ if (command.getKey() != null) loadIfNeeded(ctx, command.getKey());
return invokeNextInterceptor(ctx, command);
}
@Override
public Object visitInvalidateCommand(InvocationContext ctx, InvalidateCommand command) throws Throwable {
- if (command.getKeys() != null) {
+ if (command.getKeys() != null)
for (Object key : command.getKeys()) loadIfNeeded(ctx, key);
- }
return invokeNextInterceptor(ctx, command);
}
@Override
public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
- if (command.getKey() != null) {
- loadIfNeeded(ctx, command.getKey());
- }
+ if (command.getKey() != null) loadIfNeeded(ctx, command.getKey());
return invokeNextInterceptor(ctx, command);
}
@Override
public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable {
- if (command.getKey() != null) {
- loadIfNeeded(ctx, command.getKey());
- }
+ if (command.getKey() != null) loadIfNeeded(ctx, command.getKey());
return invokeNextInterceptor(ctx, command);
}
private void loadIfNeeded(InvocationContext ctx, Object key) throws Throwable {
- if (dataContainer.containsKey(key) || !loader.containsKey(key))
+ if (!loader.containsKey(key)) {
+ log.trace("No need to load. Key doesn't exist in the loader.");
return;
+ }
// Obtain a temporary lock to verify the key is not being concurrently added
boolean release = entryFactory.acquireLock(ctx, key);
if (dataContainer.containsKey(key)) {
- if (release)
- entryFactory.releaseLock(key);
+ if (release) entryFactory.releaseLock(ctx, key);
+ log.trace("No need to load. Key exists in the data container.");
return;
}
// Reuse the lock and create a new entry for loading
- MVCCEntry n = entryFactory.wrapEntryForWriting(ctx, key, true, false, -1); // TODO: handle expiry information from loaded data
+ MVCCEntry n = entryFactory.wrapEntryForWriting(ctx, key, true, false);
n = loadEntry(ctx, key, n);
}
/**
- * Loads a node from disk; if it exists creates parent TreeNodes. If it doesn't exist on disk but in memory, clears
- * the uninitialized flag, otherwise returns null.
+ * Loads a node from loader
*/
private MVCCEntry loadEntry(InvocationContext ctx, Object key, MVCCEntry entry) throws Exception {
- if (trace) log.trace("loading entry " + key + " entry is " + entry);
+ log.trace("Loading key {0}", key);
- Object value = loader.load(key);
- boolean nodeExists = (value != null);
- if (trace) log.trace("nodeExists " + nodeExists);
+ StoredEntry storedEntry = loader.load(key);
+ boolean entryExists = (storedEntry != null);
+ log.trace("Entry exists in loader? " + entryExists);
if (getStatisticsEnabled()) {
- if (nodeExists) {
+ if (entryExists) {
cacheLoads++;
} else {
cacheMisses++;
}
}
- if (value != null) {
- if (trace) log.trace("Entry is not null, loading");
-// notifier.notifyNodeLoaded(fqn, true, Collections.emptyMap(), ctx);
-// if (isActivation)
-// {
-// notifier.notifyNodeActivated(fqn, true, Collections.emptyMap(), ctx);
-// }
-
- entry.setValue(value);
+ if (entryExists) {
+ notifier.notifyCacheEntryLoaded(key, true, ctx);
+ if (isActivation) notifier.notifyCacheEntryActivated(key, true, ctx);
+ entry.setValue(storedEntry.getValue());
+ entry.setLifespan(storedEntry.getLifespan());
entry.setValid(true);
-// notifier.notifyNodeLoaded(fqn, false, nodeData, ctx);
-// if (isActivation)
-// {
-// notifier.notifyNodeActivated(fqn, false, nodeData, ctx);
-// }
+ notifier.notifyCacheEntryLoaded(key, false, ctx);
+ if (isActivation) notifier.notifyCacheEntryActivated(key, false, ctx);
}
return entry;
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/CacheStoreInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/CacheStoreInterceptor.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/CacheStoreInterceptor.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -30,8 +30,9 @@
import org.horizon.commands.write.PutKeyValueCommand;
import org.horizon.commands.write.PutMapCommand;
import org.horizon.commands.write.RemoveCommand;
+import org.horizon.commands.write.ReplaceCommand;
import org.horizon.config.CacheLoaderManagerConfig;
-import org.horizon.container.DataContainer;
+import org.horizon.container.MVCCEntry;
import org.horizon.context.InvocationContext;
import org.horizon.context.TransactionContext;
import org.horizon.factories.annotations.Inject;
@@ -51,6 +52,7 @@
import org.horizon.transaction.GlobalTransaction;
import javax.transaction.SystemException;
+import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import java.util.ArrayList;
import java.util.HashMap;
@@ -70,13 +72,12 @@
public class CacheStoreInterceptor extends JmxStatsCommandInterceptor {
private CacheLoaderManagerConfig loaderConfig = null;
private TransactionManager txMgr = null;
- private HashMap<GlobalTransaction, Integer> txStores = new HashMap<GlobalTransaction, Integer>();
- private Map<GlobalTransaction, Set<Object>> preparingTxs = new ConcurrentHashMap<GlobalTransaction, Set<Object>>();
+ private HashMap<Transaction, Integer> txStores = new HashMap<Transaction, Integer>();
+ private Map<Transaction, Set<Object>> preparingTxs = new ConcurrentHashMap<Transaction, Set<Object>>();
private long cacheStores = 0;
CacheStore store;
private CacheLoaderManager loaderManager;
private boolean statsEnabled;
- private DataContainer dataContainer;
public CacheStoreInterceptor() {
log = LogFactory.getLog(getClass());
@@ -84,26 +85,23 @@
}
@Inject
- protected void init(CacheLoaderManager loaderManager, TransactionManager txManager, CacheLoaderManagerConfig clConfig, DataContainer dataContainer) {
- // never inject a CacheLoaderOld at this stage - only a CacheLoaderManager, since the CacheLoaderManager only creates a CacheLoaderOld instance when it @Starts.
+ protected void init(CacheLoaderManager loaderManager, TransactionManager txManager) {
this.loaderManager = loaderManager;
- this.loaderConfig = clConfig;
txMgr = txManager;
- this.dataContainer = dataContainer;
}
@Start
protected void start() {
- // this should only happen after the CacheLoaderManager has started, since the CacheLoaderManager only creates the CacheLoaderOld instance in its @Start method.
store = loaderManager.getCacheStore();
this.setStatisticsEnabled(configuration.isExposeManagementStatistics());
+ loaderConfig = configuration.getCacheLoaderConfig();
}
/**
* if this is a shared cache loader and the call is of remote origin, pass up the chain
*/
public final boolean skip(InvocationContext ctx, VisitableCommand command) {
- if (store == null) return true;
+ if (store == null) return true; // could be because the cache loader oes not implement cache store
if ((!ctx.isOriginLocal() && loaderConfig.isShared()) || ctx.hasOption(Options.SKIP_CACHE_STORE)) {
if (trace)
log.trace("Passing up method call and bypassing this interceptor since the cache loader is shared and this call originated remotely.");
@@ -117,24 +115,21 @@
if (!skip(ctx, command) && inTransaction()) {
if (ctx.getTransactionContext().hasAnyModifications()) {
// this is a commit call.
- GlobalTransaction gtx = command.getGlobalTransaction();
- if (trace) log.trace("Calling loader.commit() for gtx " + gtx);
- // sync call (a write) on the loaderold
- // ignore modified FQNs
- // List fqnsModified = getFqnsFromModificationList(txTable.get(globalTransaction).getCacheLoaderModifications());
+ Transaction tx = ctx.getTransaction();
+ log.trace("Calling loader.commit() for transaction {0}", tx);
try {
-// store.commit(gtx);
+ store.commit(tx);
}
catch (Throwable t) {
- preparingTxs.remove(gtx);
+ preparingTxs.remove(tx);
throw t;
}
if (getStatisticsEnabled()) {
- Integer puts = (Integer) txStores.get(gtx);
+ Integer puts = txStores.get(tx);
if (puts != null) {
cacheStores = cacheStores + puts;
}
- txStores.remove(gtx);
+ txStores.remove(tx);
}
return invokeNextInterceptor(ctx, command);
} else {
@@ -149,13 +144,13 @@
if (!skip(ctx, command) && inTransaction()) {
if (trace) log.trace("transactional so don't put stuff in the cloader yet.");
if (ctx.getTransactionContext().hasAnyModifications()) {
- GlobalTransaction gtx = command.getGlobalTransaction();
+ Transaction tx = ctx.getTransaction();
// this is a rollback method
- if (preparingTxs.containsKey(gtx)) {
- preparingTxs.remove(gtx);
-// store.rollback(gtx);
+ if (preparingTxs.containsKey(tx)) {
+ preparingTxs.remove(tx);
+ store.rollback(tx);
}
- if (getStatisticsEnabled()) txStores.remove(gtx);
+ if (getStatisticsEnabled()) txStores.remove(tx);
} else {
if (trace) log.trace("Rollback called with no modifications; ignoring.");
}
@@ -167,17 +162,27 @@
public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable {
if (!skip(ctx, command) && inTransaction()) {
if (trace) log.trace("transactional so don't put stuff in the cloader yet.");
- prepareCacheLoader(command.getGlobalTransaction(), ctx.getTransactionContext(), command.isOnePhaseCommit());
+ prepareCacheLoader(ctx, command.getGlobalTransaction(), ctx.getTransactionContext(), command.isOnePhaseCommit());
}
return invokeNextInterceptor(ctx, command);
}
@Override
public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
+ Object retval = invokeNextInterceptor(ctx, command);
+ if (!skip(ctx, command) && !inTransaction() && command.isSuccessful()) {
+ Object key = command.getKey();
+ boolean resp = store.remove(key);
+ log.trace("Removed entry under key {0} and got response {1} from CacheStore", key, resp);
+ }
+ return retval;
+ }
+
+ @Override
+ public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable {
if (!skip(ctx, command) && !inTransaction()) {
- Object returnValue = store.remove(command.getKey());
- invokeNextInterceptor(ctx, command);
- return returnValue;
+ store.clear();
+ log.trace("Cleared cache store");
}
return invokeNextInterceptor(ctx, command);
}
@@ -185,66 +190,72 @@
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
Object returnValue = invokeNextInterceptor(ctx, command);
- if (skip(ctx, command) || inTransaction())
- return returnValue;
+ if (skip(ctx, command) || inTransaction() || !command.isSuccessful()) return returnValue;
- store.store((StoredEntry) null);//command.getKey(), command.getValue());
+ Object key = command.getKey();
+ StoredEntry se = getStoredEntry(key, ctx);
+ store.store(se);
+ log.trace("Stored entry {0} under key {1}", se, key);
if (getStatisticsEnabled()) cacheStores++;
return returnValue;
}
@Override
- public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
+ public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable {
Object returnValue = invokeNextInterceptor(ctx, command);
- if (skip(ctx, command) || inTransaction())
- return returnValue;
+ if (skip(ctx, command) || inTransaction() || !command.isSuccessful()) return returnValue;
- // Perhaps this should be optimized
- Map<Object, Object> map = command.getMap();
- List<Modification> modifications = toModifications(map);
-// store.put(modifications);
-
+ Object key = command.getKey();
+ StoredEntry se = getStoredEntry(key, ctx);
+ store.store(se);
+ log.trace("Stored entry {0} under key {1}", se, key);
if (getStatisticsEnabled()) cacheStores++;
return returnValue;
}
- private static List<Modification> toModifications(Map<Object, Object> map) {
- List<Modification> modifications = new ArrayList<Modification>(map.size());
- // TODO fix me
-// for (Map.Entry<Object, Object> entry : map.entrySet())
-// modifications.add(new Modification(ModificationType.PUT, entry.getKey(), entry.getValue()));
- return modifications;
+ @Override
+ public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
+ Object returnValue = invokeNextInterceptor(ctx, command);
+ if (skip(ctx, command) || inTransaction()) return returnValue;
+
+ Map<Object, Object> map = command.getMap();
+ for (Object key : map.keySet()) {
+ StoredEntry se = getStoredEntry(key, ctx);
+ store.store(se);
+ log.trace("Stored entry {0} under key {1}", se, key);
+ }
+ if (getStatisticsEnabled()) cacheStores += map.size();
+ return returnValue;
}
private boolean inTransaction() throws SystemException {
return txMgr != null && txMgr.getTransaction() != null;
}
- private void prepareCacheLoader(GlobalTransaction gtx, TransactionContext transactionContext, boolean onePhase) throws Throwable {
+ private void prepareCacheLoader(InvocationContext ctx, GlobalTransaction gtx, TransactionContext transactionContext, boolean onePhase) throws Throwable {
if (transactionContext == null) {
throw new Exception("transactionContext for transaction " + gtx + " not found in transaction table");
}
List<VisitableCommand> modifications = transactionContext.getModifications();
if (modifications.size() == 0) {
- if (trace) log.trace("Transaction has not logged any modifications!");
+ log.trace("Transaction has not logged any modifications!");
return;
}
- if (trace) log.trace("Cache loader modification list: " + modifications);
+ log.trace("Cache loader modification list: {0}", modifications);
StoreModificationsBuilder modsBuilder = new StoreModificationsBuilder(getStatisticsEnabled());
- for (VisitableCommand cacheCommand : modifications) {
- cacheCommand.acceptVisitor(null, modsBuilder);
- }
- if (trace) {
- log.trace("Converted method calls to cache loader modifications. List size: " + modsBuilder.modifications.size());
- }
- if (modsBuilder.modifications.size() > 0) {
-// loader.prepare(gtx, modsBuilder.modifications, onePhase);
+ for (VisitableCommand cacheCommand : modifications) cacheCommand.acceptVisitor(ctx, modsBuilder);
+ int numMods = modsBuilder.modifications.size();
+ log.trace("Converted method calls to cache loader modifications. List size: {0}", numMods);
- preparingTxs.put(gtx, modsBuilder.affectedKeys);
+ if (numMods > 0) {
+ Transaction tx = transactionContext.getTransaction();
+ store.prepare(modsBuilder.modifications, tx, onePhase);
+
+ preparingTxs.put(tx, modsBuilder.affectedKeys);
if (getStatisticsEnabled() && modsBuilder.putCount > 0) {
- txStores.put(gtx, modsBuilder.putCount);
+ txStores.put(tx, modsBuilder.putCount);
}
}
}
@@ -267,7 +278,7 @@
@SuppressWarnings("unchecked")
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
if (generateStatistics) putCount++;
- modifications.add(new Store(dataContainer.createEntryForStorage(command.getKey())));
+ modifications.add(new Store(getStoredEntry(command.getKey(), ctx)));
affectedKeys.add(command.getKey());
return null;
}
@@ -278,8 +289,7 @@
Map<Object, Object> map = command.getMap();
if (generateStatistics) putCount += map.size();
affectedKeys.addAll(map.keySet());
- Set<StoredEntry> entries = new HashSet<StoredEntry>();
- for (Object key : map.keySet()) modifications.add(new Store(dataContainer.createEntryForStorage(key)));
+ for (Object key : map.keySet()) modifications.add(new Store(getStoredEntry(key, ctx)));
return null;
}
@@ -326,4 +336,10 @@
return cacheStores;
}
+ private StoredEntry getStoredEntry(Object key, InvocationContext ctx) {
+ MVCCEntry entry = ctx.lookupEntry(key);
+ StoredEntry se = new StoredEntry(key, entry.getValue());
+ se.setLifespan(entry.getLifespan());
+ return se;
+ }
}
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/LockingInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/LockingInterceptor.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/LockingInterceptor.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -133,7 +133,7 @@
public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable {
try {
// get a snapshot of all keys in the data container
- for (Object key : dataContainer.keySet()) entryFactory.wrapEntryForWriting(ctx, key, false, false, -1);
+ for (Object key : dataContainer.keySet()) entryFactory.wrapEntryForWriting(ctx, key, false, false);
return invokeNextInterceptor(ctx, command);
}
@@ -152,7 +152,7 @@
public Object visitInvalidateCommand(InvocationContext ctx, InvalidateCommand command) throws Throwable {
try {
if (command.getKeys() != null) {
- for (Object key : command.getKeys()) entryFactory.wrapEntryForWriting(ctx, key, false, true, -1);
+ for (Object key : command.getKeys()) entryFactory.wrapEntryForWriting(ctx, key, false, true);
}
return invokeNextInterceptor(ctx, command);
}
@@ -164,7 +164,7 @@
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
try {
- entryFactory.wrapEntryForWriting(ctx, command.getKey(), true, false, command.getLifespanMillis());
+ entryFactory.wrapEntryForWriting(ctx, command.getKey(), true, false);
return invokeNextInterceptor(ctx, command);
}
finally {
@@ -176,7 +176,7 @@
public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
try {
for (Object key : command.getMap().keySet()) {
- entryFactory.wrapEntryForWriting(ctx, key, true, false, command.getLifespanMillis());
+ entryFactory.wrapEntryForWriting(ctx, key, true, false);
}
return invokeNextInterceptor(ctx, command);
}
@@ -188,7 +188,7 @@
@Override
public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
try {
- entryFactory.wrapEntryForWriting(ctx, command.getKey(), false, true, -1);
+ entryFactory.wrapEntryForWriting(ctx, command.getKey(), false, true);
return invokeNextInterceptor(ctx, command);
}
finally {
@@ -199,7 +199,7 @@
@Override
public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable {
try {
- entryFactory.wrapEntryForWriting(ctx, command.getKey(), false, true, command.getLifespanMillis());
+ entryFactory.wrapEntryForWriting(ctx, command.getKey(), false, true);
return invokeNextInterceptor(ctx, command);
}
finally {
Modified: core/branches/flat/src/main/java/org/horizon/loader/AbstractCacheLoaderConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/AbstractCacheLoaderConfig.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/loader/AbstractCacheLoaderConfig.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -9,8 +9,8 @@
private boolean ignoreModifications;
private boolean fetchPersistentState;
private boolean purgeOnStartup;
- private SingletonStoreConfig singletonStoreConfig;
- private AsyncStoreConfig asyncStoreConfig;
+ private SingletonStoreConfig singletonStoreConfig = new SingletonStoreConfig();
+ private AsyncStoreConfig asyncStoreConfig = new AsyncStoreConfig();
public boolean isPurgeOnStartup() {
return purgeOnStartup;
@@ -113,6 +113,7 @@
throw new RuntimeException("Should not happen!", e);
}
if (singletonStoreConfig != null) clone.setSingletonStoreConfig(singletonStoreConfig.clone());
+ if (asyncStoreConfig != null) clone.setAsyncStoreConfig((AsyncStoreConfig) asyncStoreConfig.clone());
return clone;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/AbstractCacheStore.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/AbstractCacheStore.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/loader/AbstractCacheStore.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -17,9 +17,9 @@
*/
public abstract class AbstractCacheStore extends AbstractCacheLoader implements CacheStore {
- private final Map<Transaction, List<Modification>> transactions = new ConcurrentHashMap<Transaction, List<Modification>>();
+ private final Map<Transaction, List<? extends Modification>> transactions = new ConcurrentHashMap<Transaction, List<? extends Modification>>();
- protected void applyModifications(List<Modification> mods) {
+ protected void applyModifications(List<? extends Modification> mods) {
for (Modification m : mods) {
switch (m.getType()) {
case STORE:
@@ -39,7 +39,7 @@
}
}
- public void prepare(List<Modification> mods, Transaction tx, boolean isOnePhase) {
+ public void prepare(List<? extends Modification> mods, Transaction tx, boolean isOnePhase) {
if (isOnePhase) {
applyModifications(mods);
} else {
@@ -52,7 +52,7 @@
}
public void commit(Transaction tx) {
- List<Modification> list = transactions.remove(tx);
+ List<? extends Modification> list = transactions.remove(tx);
if (list != null && !list.isEmpty()) applyModifications(list);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/CacheLoaderManagerImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/CacheLoaderManagerImpl.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/loader/CacheLoaderManagerImpl.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -181,7 +181,7 @@
// singleton?
SingletonStoreConfig ssc = cfg.getSingletonStoreConfig();
if (ssc != null && ssc.isSingletonStoreEnabled()) {
- tmpStore = new SingletonStore(tmpStore);
+ tmpStore = new SingletonStore(tmpStore, cache, ssc);
tmpLoader = tmpStore;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/CacheStore.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/CacheStore.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/loader/CacheStore.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -73,7 +73,7 @@
* @param isOnePhase if true, there will not be a commit or rollback phase and changes should be flushed
* immediately
*/
- void prepare(List<Modification> modifications, Transaction tx, boolean isOnePhase);
+ void prepare(List<? extends Modification> modifications, Transaction tx, boolean isOnePhase);
/**
* Commits a transaction that has been previously prepared
Modified: core/branches/flat/src/main/java/org/horizon/loader/StoredEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/StoredEntry.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/loader/StoredEntry.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -19,7 +19,7 @@
}
public StoredEntry(Object key, Object value) {
- super(value, -1, -1);
+ super(value, System.currentTimeMillis(), -1);
this.key = key;
}
@@ -58,6 +58,9 @@
public String toString() {
return "StoredEntry{" +
"key=" + key +
+ ", value=" + value +
+ ", createdTime=" + createdTime +
+ ", expiryTime=" + expiryTime +
'}';
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/decorators/AbstractDelegatingStore.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/decorators/AbstractDelegatingStore.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/loader/decorators/AbstractDelegatingStore.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -5,6 +5,7 @@
import org.horizon.loader.CacheLoaderConfig;
import org.horizon.loader.CacheStore;
import org.horizon.loader.StoredEntry;
+import org.horizon.loader.modifications.Modification;
import org.horizon.marshall.Marshaller;
import javax.transaction.Transaction;
@@ -69,7 +70,7 @@
delegate.rollback(tx);
}
- public void prepare(List list, Transaction tx, boolean isOnePhase) {
+ public void prepare(List<? extends Modification> list, Transaction tx, boolean isOnePhase) {
delegate.prepare(list, tx, isOnePhase);
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/decorators/AsyncStoreConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/decorators/AsyncStoreConfig.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/loader/decorators/AsyncStoreConfig.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -60,4 +60,13 @@
this.threadPoolSize = threadPoolSize;
}
+ @Override
+ public AsyncStoreConfig clone() {
+ try {
+ return (AsyncStoreConfig) super.clone();
+ } catch (CloneNotSupportedException e) {
+ throw new RuntimeException("Should not happen!", e);
+ }
+ }
+
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/decorators/ReadOnlyStore.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/decorators/ReadOnlyStore.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/loader/decorators/ReadOnlyStore.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -2,6 +2,7 @@
import org.horizon.loader.CacheStore;
import org.horizon.loader.StoredEntry;
+import org.horizon.loader.modifications.Modification;
import javax.transaction.Transaction;
import java.io.InputStream;
@@ -56,7 +57,7 @@
}
@Override
- public void prepare(List list, Transaction tx, boolean isOnePhase) {
+ public void prepare(List<? extends Modification> list, Transaction tx, boolean isOnePhase) {
// no-op
}
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/decorators/SingletonStore.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/decorators/SingletonStore.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/loader/decorators/SingletonStore.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -1,98 +1,356 @@
package org.horizon.loader.decorators;
import org.horizon.Cache;
-import org.horizon.loader.CacheLoaderConfig;
+import org.horizon.container.DataContainer;
import org.horizon.loader.CacheStore;
import org.horizon.loader.StoredEntry;
-import org.horizon.marshall.Marshaller;
+import org.horizon.loader.modifications.Modification;
+import org.horizon.logging.Log;
+import org.horizon.logging.LogFactory;
+import org.horizon.manager.CacheManager;
+import org.horizon.notifications.Listener;
+import org.horizon.notifications.cachemanagerlistener.annotation.CacheStarted;
+import org.horizon.notifications.cachemanagerlistener.annotation.ViewChanged;
+import org.horizon.notifications.cachemanagerlistener.event.Event;
+import org.horizon.notifications.cachemanagerlistener.event.ViewChangedEvent;
+import org.horizon.remoting.transport.Address;
import javax.transaction.Transaction;
import java.io.IOException;
import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Collection;
import java.util.List;
import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
/**
- * // TODO: Manik: Document this!
+ * SingletonStore is a delegating cache store used for situations when only one instance should interact with the
+ * underlying store. The coordinator of the cluster will be responsible for the underlying CacheStore.
+ * <p/>
+ * SingletonStore is a simply facade to a real CacheStore implementation. It always delegates reads to the real
+ * CacheStore.
+ * <p/>
+ * Writes are delegated <i>only if,/i> this SingletonStore is currently the cordinator. This avoids having all stores in
+ * a cluster writing the same data to the same underlying store. Although not incorrect (e.g. a DB will just discard
+ * additional INSERTs for the same key, and throw an exception), this will avoid a lot of redundant work.
+ * <p/>
+ * Whenever the current coordinator dies (or leaves), the second in line will take over. That SingletonStore will then
+ * pass writes through to its underlying CacheStore. Optionally, when a new coordinator takes over the Singleton, it can
+ * push the in-memory state to the cache cacheStore, within a time constraint.
*
+ * @author Bela Ban
+ * @author <a href="mailto:galder.zamarreno@jboss.com">Galder Zamarreno</a>
* @author Manik Surtani
+ * @since 1.0
*/
public class SingletonStore extends AbstractDelegatingStore {
- public SingletonStore(CacheStore delegate) {
+ private static final Log log = LogFactory.getLog(SingletonStore.class);
+ private static final boolean trace = log.isTraceEnabled();
+
+ CacheManager cacheManager;
+ Cache cache;
+ SingletonStoreConfig config;
+
+ /**
+ * Name of thread that should pushing in-memory state to cache loader.
+ */
+ private static final String THREAD_NAME = "SingletonStorePusherThread";
+
+ /**
+ * Executor service used to submit tasks to push in-memory state.
+ */
+ private final ExecutorService executor;
+
+ /**
+ * Future result of the in-memory push state task. This allows SingletonStore to check whether there's any push taks
+ * on going.
+ */
+ Future<?> pushStateFuture; /* FutureTask guarantess a safe publication of the result */
+
+ /**
+ * Address instance that allows SingletonStore to find out whether it became the coordinator of the cluster, or
+ * whether it stopped being it. This dictates whether the SingletonStore is active or not.
+ */
+ private Address localAddress;
+
+ /**
+ * Whether the the current node is the coordinator and therefore SingletonStore is active. Being active means
+ * delegating calls to the underlying cache loader.
+ */
+ private volatile boolean active;
+
+
+ public SingletonStore(CacheStore delegate, Cache cache, SingletonStoreConfig config) {
super(delegate);
- }
+ this.cacheManager = cache == null ? null : cache.getCacheManager();
+ this.cache = cache;
+ this.config = config;
- public void store(StoredEntry ed) {
- // TODO: Manik: Customise this generated block
- }
+ executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
+ public Thread newThread(Runnable r) {
+ return new Thread(r, THREAD_NAME);
+ }
+ });
- public void storeAll(Collection ed) {
- // TODO: Manik: Customise this generated block
}
- public void store(InputStream inputStream) {
- // TODO: Manik: Customise this generated block
+ // -------------- Basic write methods
+ // only delegate if the current instance is active
+
+ @Override
+ public void store(StoredEntry ed) {
+ if (active) {
+ if (trace) log.trace("Storing key {0}. Instance: {1}", ed.getKey(), this);
+ super.store(ed);
+ } else if (trace) log.trace("Not storing key {0}. Instance: {1}", ed.getKey(), this);
}
- public void load(OutputStream outputStream) throws IOException {
- // TODO: Manik: Customise this generated block
+ @Override
+ public void store(InputStream inputStream) throws IOException, ClassNotFoundException {
+ if (active) super.store(inputStream);
}
+ @Override
public void clear() {
- // TODO: Manik: Customise this generated block
+ if (active) super.clear();
}
+ @Override
public boolean remove(Object key) {
- return false; // TODO: Manik: Customise this generated block
+ return active && super.remove(key);
}
+ @Override
public void purgeExpired() {
- // TODO: Manik: Customise this generated block
+ if (active) super.purgeExpired();
}
+ @Override
public void commit(Transaction tx) {
- // TODO: Manik: Customise this generated block
+ if (active) super.commit(tx);
}
+ @Override
public void rollback(Transaction tx) {
- // TODO: Manik: Customise this generated block
+ if (active) super.rollback(tx);
}
- public void prepare(List list, Transaction tx, boolean isOnePhase) {
- // TODO: Manik: Customise this generated block
+ @Override
+ public void prepare(List<? extends Modification> list, Transaction tx, boolean isOnePhase) {
+ if (active) super.prepare(list, tx, isOnePhase);
}
- public void init(CacheLoaderConfig config, Cache cache, Marshaller m) {
- // TODO: Manik: Customise this generated block
+ @Override
+ public void start() {
+ cacheManager.addListener(new SingletonStoreListener());
+ super.start();
}
- public StoredEntry load(Object key) {
- return null; // TODO: Manik: Customise this generated block
+ /**
+ * Factory method for the creation of a Callable task in charge of pushing in-memory state to cache loader.
+ *
+ * @return new instance of Callable<?> whose call() method either throws an exception or returns null if the task was
+ * successfull.
+ */
+ protected Callable<?> createPushStateTask() {
+ return new Callable() {
+ public Object call() throws Exception {
+ final boolean debugEnabled = log.isDebugEnabled();
+
+ if (debugEnabled) log.debug("start pushing in-memory state to cache cacheLoader");
+ pushState(cache);
+ if (debugEnabled) log.debug("in-memory state passed to cache cacheLoader successfully");
+
+ return null;
+ }
+ };
}
- public Set loadAll(Collection keys) {
- return null; // TODO: Manik: Customise this generated block
+ /**
+ * Pushes the state of a specific node by reading the node's data from the cache and putting in the cache store via
+ * the cache loader. This method is call recursively so that it iterates through the whole cache.
+ *
+ * @throws Exception if there's any issues reading the data from the cache or pushing the node's data to the cache
+ * loader.
+ */
+ protected void pushState(final Cache cache) throws Exception {
+ DataContainer dc = cache.getAdvancedCache().getDataContainer();
+ Set keys = dc.keySet();
+ StoredEntry entry;
+ for (Object k : keys) if ((entry = dc.createEntryForStorage(k)) != null) store(entry);
}
- public Set loadAll() {
- return null; // TODO: Manik: Customise this generated block
+
+ /**
+ * Method that waits for the in-memory to cache loader state to finish. This method's called in case a push state is
+ * already in progress and we need to wait for it to finish.
+ *
+ * @param future instance of Future representing the on going push task
+ * @param timeout time to wait for the push task to finish
+ * @param unit instance of TimeUnit representing the unit of timeout
+ */
+ protected void awaitForPushToFinish(Future future, long timeout, TimeUnit unit) {
+ final boolean debugEnabled = log.isDebugEnabled();
+ try {
+ if (debugEnabled) log.debug("wait for state push to cache loader to finish");
+ future.get(timeout, unit);
+ }
+ catch (TimeoutException e) {
+ if (debugEnabled) log.debug("timed out waiting for state push to cache loader to finish");
+ }
+ catch (ExecutionException e) {
+ if (debugEnabled) log.debug("exception reported waiting for state push to cache loader to finish");
+ }
+ catch (InterruptedException ie) {
+ /* Re-assert the thread's interrupted status */
+ Thread.currentThread().interrupt();
+ if (trace) log.trace("wait for state push to cache loader to finish was interrupted");
+ }
}
- public boolean containsKey(Object key) {
- return false; // TODO: Manik: Customise this generated block
+
+ /**
+ * Method called when the node either becomes the coordinator or stops being the coordinator. If it becomes the
+ * coordinator, it can optionally start the in-memory state transfer to the underlying cache store.
+ *
+ * @param newActiveState true if the node just became the coordinator, false if the nodes stopped being the
+ * coordinator.
+ */
+ protected void activeStatusChanged(boolean newActiveState) throws PushStateException {
+ active = newActiveState;
+ log.debug("changed mode {0}", this);
+ if (active && config.isPushStateWhenCoordinator()) doPushState();
}
- public Class<? extends CacheLoaderConfig> getConfigurationClass() {
- return null;
+ /**
+ * Indicates whether the current nodes is the coordinator of the cluster. This implementation assumes that the
+ * coordinator is the first member in the list.
+ *
+ * @param newView View instance containing the new view of the cluster
+ * @return whether the current node is the coordinator or not.
+ */
+ private boolean isCoordinator(List<Address> newView, Address currentAddress) {
+ if (!currentAddress.equals(localAddress)) localAddress = currentAddress;
+ if (localAddress != null) {
+ return newView.size() > 0 && localAddress.equals(newView.get(0));
+ } else {
+ /* Invalid new view, so previous value returned */
+ return active;
+ }
}
- public void start() {
- // TODO: Manik: Customise this generated block
+ /**
+ * Called when the SingletonStore discovers that the node has become the coordinator and push in memory state has
+ * been enabled. It might not actually push the state if there's an ongoing push task running, in which case will
+ * wait for the push task to finish.
+ *
+ * @throws PushStateException when the push state task reports an issue.
+ */
+ private void doPushState() throws PushStateException {
+ if (pushStateFuture == null || pushStateFuture.isDone()) {
+ Callable<?> task = createPushStateTask();
+ pushStateFuture = executor.submit(task);
+ try {
+ waitForTaskToFinish(pushStateFuture, config.getPushStateTimeout(), TimeUnit.MILLISECONDS);
+ }
+ catch (Exception e) {
+ throw new PushStateException("unable to complete in memory state push to cache loader", e);
+ }
+ } else {
+ /* at the most, we wait for push state timeout value. if it push task finishes earlier, this call
+* will stop when the push task finishes, otherwise a timeout exception will be reported */
+ awaitForPushToFinish(pushStateFuture, config.getPushStateTimeout(), TimeUnit.MILLISECONDS);
+ }
}
- public void stop() {
- // TODO: Manik: Customise this generated block
+
+ /**
+ * Waits, within a time constraint, for a task to finish.
+ *
+ * @param future represents the task waiting to finish.
+ * @param timeout maximum time to wait for the time to finish.
+ * @param unit instance of TimeUnit representing the unit of timeout
+ * @throws Exception if any issues are reported while waiting for the task to finish
+ */
+ private void waitForTaskToFinish(Future future, long timeout, TimeUnit unit) throws Exception {
+ try {
+ future.get(timeout, unit);
+ }
+ catch (TimeoutException e) {
+ throw new Exception("task timed out", e);
+ }
+ catch (InterruptedException e) {
+ /* Re-assert the thread's interrupted status */
+ Thread.currentThread().interrupt();
+ if (trace) log.trace("task was interrupted");
+ }
+ finally {
+ /* no-op if task is completed */
+ future.cancel(true); /* interrupt if running */
+ }
}
+
+
+ /**
+ * Cache listener that reacts to cluster topology changes to find out whether a new coordinator is elected.
+ * SingletonStore reacts to these changes in order to decide which node should interact with the underlying cache
+ * store.
+ */
+ @Listener
+ public class SingletonStoreListener {
+ /**
+ * Cache started, check whether the node is the coordinator and set the singleton store's active status.
+ */
+ @CacheStarted
+ public void cacheStarted(Event e) {
+ localAddress = cacheManager.getAddress();
+ active = cacheManager.isCoordinator();
+ }
+
+ /**
+ * The cluster formation changed, so determine whether the current node stopped being the coordinator or became
+ * the coordinator. This method can lead to an optional in memory to cache loader state push, if the current node
+ * became the coordinator. This method will report any issues that could potentially arise from this push.
+ */
+ @ViewChanged
+ public void viewChange(ViewChangedEvent event) {
+ boolean tmp = isCoordinator(event.getNewMemberList(), event.getLocalAddress());
+
+ if (active != tmp) {
+ try {
+ activeStatusChanged(tmp);
+ }
+ catch (PushStateException e) {
+ log.error("exception reported changing nodes active status", e);
+ }
+
+ }
+ }
+ }
+
+ /**
+ * Exception representing any issues that arise from pushing the in-memory state to the cache loader.
+ */
+ public static class PushStateException extends Exception {
+ private static final long serialVersionUID = 5542893943730200886L;
+
+ public PushStateException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public PushStateException(Throwable cause) {
+ super(cause);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "SingletonStore: localAddress=" + localAddress + ", active=" + active;
+ }
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/decorators/SingletonStoreConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/decorators/SingletonStoreConfig.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/main/java/org/horizon/loader/decorators/SingletonStoreConfig.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -13,7 +13,7 @@
private static final long serialVersionUID = 824251894176131850L;
boolean singletonStoreEnabled;
- boolean pushStateWhenCoordinator;
+ boolean pushStateWhenCoordinator = true;
long pushStateTimeout = 10000;
public boolean isSingletonStoreEnabled() {
Modified: core/branches/flat/src/test/java/org/horizon/expiry/ExpiryTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/expiry/ExpiryTest.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/test/java/org/horizon/expiry/ExpiryTest.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -1,6 +1,8 @@
package org.horizon.expiry;
import org.horizon.Cache;
+import org.horizon.container.DataContainer;
+import org.horizon.loader.StoredEntry;
import org.horizon.manager.CacheManager;
import org.horizon.manager.DefaultCacheManager;
import org.horizon.util.TestingUtil;
@@ -29,17 +31,19 @@
public void testExpiryInPut() throws InterruptedException {
Cache cache = cm.getCache();
- long startTime = System.currentTimeMillis();
long lifespan = 1000;
cache.put("k", "v", lifespan, TimeUnit.MILLISECONDS);
- while (System.currentTimeMillis() < startTime + lifespan + 100) {
- if (System.currentTimeMillis() < startTime + lifespan) {
- assert cache.get("k").equals("v");
- } else {
- assert cache.get("k") == null;
- }
- Thread.sleep(50);
- }
+
+ DataContainer dc = cache.getAdvancedCache().getDataContainer();
+ StoredEntry se = dc.createEntryForStorage("k");
+ assert se.getKey().equals("k");
+ assert se.getValue().equals("v");
+ assert se.getLifespan() == lifespan;
+ assert !se.isExpired();
+ assert cache.get("k").equals("v");
+ Thread.sleep(1100);
+ assert se.isExpired();
+ assert cache.get("k") == null;
}
public void testExpiryInPutAll() throws InterruptedException {
Deleted: core/branches/flat/src/test/java/org/horizon/loader/AsyncTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/loader/AsyncTest.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/test/java/org/horizon/loader/AsyncTest.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -1,62 +0,0 @@
-package org.horizon.loader;
-
-import org.horizon.CacheException;
-import org.horizon.loader.decorators.AsyncStore;
-import org.horizon.loader.decorators.AsyncStoreConfig;
-import org.horizon.loader.dummy.DummyInMemoryCacheLoader;
-import org.horizon.util.TestingUtil;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.AfterTest;
-import org.testng.annotations.BeforeTest;
-import org.testng.annotations.Test;
-
-import java.util.concurrent.ExecutorService;
-
-@Test(groups = "unit", sequential = true)
-public class AsyncTest {
-
- AsyncStore store;
- ExecutorService asyncExecutor;
-
-
- @BeforeTest
- public void setUp() {
- store = new AsyncStore(new DummyInMemoryCacheLoader(), new AsyncStoreConfig());
- DummyInMemoryCacheLoader.Cfg cfg = new DummyInMemoryCacheLoader.Cfg();
- cfg.setStore(AsyncTest.class.getName());
- store.init(cfg, null, null);
- store.start();
- asyncExecutor = (ExecutorService) TestingUtil.extractField(store, "executor");
- }
-
- @AfterTest
- public void tearDown() {
- if (store != null) store.stop();
- }
-
- @AfterMethod
- public void clearStore() {
- if (store != null) store.clear();
- }
-
- public void testRestrictionOnAddingToAsyncQueue() throws Exception {
- store.remove("blah");
-
- store.store(new StoredEntry("one", "value"));
- store.store(new StoredEntry("two", "value"));
- store.store(new StoredEntry("three", "value"));
- store.store(new StoredEntry("four", "value"));
-
- // stop the cache store
- store.stop();
- try {
- store.remove("blah");
- assert false : "Should have restricted this entry from being made";
- }
- catch (CacheException expected) {
- }
-
- // clean up
- store.start();
- }
-}
Added: core/branches/flat/src/test/java/org/horizon/loader/CacheLoaderFunctionalTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/loader/CacheLoaderFunctionalTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/loader/CacheLoaderFunctionalTest.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -0,0 +1,340 @@
+package org.horizon.loader;
+
+import org.horizon.Cache;
+import org.horizon.config.CacheLoaderManagerConfig;
+import org.horizon.config.Configuration;
+import org.horizon.container.DataContainer;
+import org.horizon.lifecycle.ComponentStatus;
+import org.horizon.loader.dummy.DummyInMemoryCacheLoader;
+import org.horizon.manager.CacheManager;
+import org.horizon.manager.DefaultCacheManager;
+import org.horizon.transaction.DummyTransactionManagerLookup;
+import org.horizon.util.TestingUtil;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.AfterTest;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Test;
+
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
+import java.util.Collections;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+
+/**
+ * Tests the interceptor chain and surrounding logic
+ *
+ * @author Manik Surtani
+ */
+@Test(groups = "functional", sequential = true)
+public class CacheLoaderFunctionalTest {
+ Cache cache;
+ CacheStore store;
+ TransactionManager tm;
+ Configuration cfg;
+ CacheManager cm;
+ long lifespan = 6000000; // very large lifespan so nothing actually expires
+
+ @BeforeTest
+ public void setUp() {
+ cfg = new Configuration();
+ cfg.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ CacheLoaderManagerConfig clmc = new CacheLoaderManagerConfig();
+ clmc.addIndividualCacheLoaderConfig(new DummyInMemoryCacheLoader.Cfg());
+ cfg.setCacheLoaderConfig(clmc);
+ cm = new DefaultCacheManager(cfg);
+ cache = cm.getCache();
+ store = TestingUtil.extractComponent(cache, CacheLoaderManager.class).getCacheStore();
+ tm = TestingUtil.getTransactionManager(cache);
+ }
+
+ @AfterTest
+ public void tearDown() {
+ TestingUtil.killCacheManagers(cm);
+ }
+
+ @AfterMethod
+ public void afterMethod() {
+ if (cache != null) cache.clear();
+ if (store != null) store.clear();
+ }
+
+ private void assertInCacheAndStore(Object key, Object value) {
+ assertInCacheAndStore(key, value, -1);
+ }
+
+ private void assertInCacheAndStore(Object key, Object value, long lifespanMillis) {
+ assertInCacheAndStore(cache, store, key, value, lifespanMillis);
+ }
+
+
+ private void assertInCacheAndStore(Cache cache, CacheStore store, Object key, Object value) {
+ assertInCacheAndStore(cache, store, key, value, -1);
+ }
+
+ private void assertInCacheAndStore(Cache cache, CacheStore store, Object key, Object value, long lifespanMillis) {
+ StoredEntry se = cache.getAdvancedCache().getDataContainer().createEntryForStorage(key);
+ testStoredEntry(se, value, lifespanMillis, "Cache", key);
+ se = store.load(key);
+ testStoredEntry(se, value, lifespanMillis, "Store", key);
+ }
+
+ private void testStoredEntry(StoredEntry entry, Object expectedValue, long expectedLifespan, String src, Object key) {
+ assert entry != null : src + " entry for key " + key + " should NOT be null";
+ assert entry.getValue().equals(expectedValue) : src + " should contain value " + expectedValue + " under key " + entry.getKey() + " but was " + entry.getValue() + ". Entry is " + entry;
+ assert entry.getLifespan() == expectedLifespan : src + " expected lifespan for key " + key + " to be " + expectedLifespan + " but was " + entry.getLifespan() + ". Entry is " + entry;
+ }
+
+ private void assertNotInCacheAndStore(Cache cache, CacheStore store, Object... keys) {
+ for (Object key : keys) {
+ assert !cache.getAdvancedCache().getDataContainer().containsKey(key) : "Cache should not contain key " + key;
+ assert !store.containsKey(key) : "Store should not contain key " + key;
+ }
+ }
+
+ private void assertNotInCacheAndStore(Object... keys) {
+ assertNotInCacheAndStore(cache, store, keys);
+ }
+
+ public void testStoreAndRetrieve() {
+ assertNotInCacheAndStore("k1", "k2", "k3", "k4", "k5", "k6", "k7");
+
+ cache.put("k1", "v1");
+ cache.put("k2", "v2", lifespan, MILLISECONDS);
+ cache.putAll(Collections.singletonMap("k3", "v3"));
+ cache.putAll(Collections.singletonMap("k4", "v4"), lifespan, MILLISECONDS);
+ cache.putIfAbsent("k5", "v5");
+ cache.putIfAbsent("k6", "v6", lifespan, MILLISECONDS);
+ cache.putIfAbsent("k5", "v5-SHOULD-NOT-PUT");
+ cache.putIfAbsent("k6", "v6-SHOULD-NOT-PUT", lifespan, MILLISECONDS);
+ cache.putForExternalRead("k7", "v7");
+ cache.putForExternalRead("k7", "v7-SHOULD-NOT-PUT");
+
+ for (int i = 1; i < 8; i++) {
+ // even numbers have lifespans
+ if (i % 2 == 1)
+ assertInCacheAndStore("k" + i, "v" + i);
+ else
+ assertInCacheAndStore("k" + i, "v" + i, lifespan);
+ }
+
+ cache.remove("k1", "some rubbish");
+
+ for (int i = 1; i < 8; i++) {
+ // even numbers have lifespans
+ if (i % 2 == 1)
+ assertInCacheAndStore("k" + i, "v" + i);
+ else
+ assertInCacheAndStore("k" + i, "v" + i, lifespan);
+ }
+
+ assert cache.remove("k1", "v1");
+ assert cache.remove("k2").equals("v2");
+
+ assertNotInCacheAndStore("k1", "k2");
+
+ for (int i = 3; i < 8; i++) {
+ // even numbers have lifespans
+ if (i % 2 == 1)
+ assertInCacheAndStore("k" + i, "v" + i);
+ else
+ assertInCacheAndStore("k" + i, "v" + i, lifespan);
+ }
+
+ cache.clear();
+ assertNotInCacheAndStore("k1", "k2", "k3", "k4", "k5", "k6", "k7");
+ }
+
+ public void testReplaceMethods() {
+ assertNotInCacheAndStore("k1", "k2", "k3", "k4");
+
+ cache.replace("k1", "v1-SHOULD-NOT-STORE");
+ cache.replace("k2", "v2-SHOULD-NOT-STORE", lifespan, MILLISECONDS);
+
+ assertNotInCacheAndStore("k1", "k2", "k3", "k4");
+
+ cache.put("k1", "v1");
+ cache.put("k2", "v2");
+ cache.put("k3", "v3");
+ cache.put("k4", "v4");
+
+ for (int i = 1; i < 5; i++) assertInCacheAndStore("k" + i, "v" + i);
+
+ cache.replace("k1", "v1-SHOULD-NOT-STORE", "v1-STILL-SHOULD-NOT-STORE");
+ cache.replace("k2", "v2-SHOULD-NOT-STORE", "v2-STILL-SHOULD-NOT-STORE", lifespan, MILLISECONDS);
+
+ for (int i = 1; i < 5; i++) assertInCacheAndStore("k" + i, "v" + i);
+
+ cache.replace("k1", "v1-REPLACED");
+ cache.replace("k2", "v2-REPLACED", lifespan, MILLISECONDS);
+ cache.replace("k3", "v3", "v3-REPLACED");
+ cache.replace("k4", "v4", "v4-REPLACED", lifespan, MILLISECONDS);
+
+ for (int i = 1; i < 5; i++) {
+ // even numbers have lifespans
+ if (i % 2 == 1)
+ assertInCacheAndStore("k" + i, "v" + i + "-REPLACED");
+ else
+ assertInCacheAndStore("k" + i, "v" + i + "-REPLACED", lifespan);
+ }
+
+ }
+
+ public void testLoading() {
+ assertNotInCacheAndStore("k1", "k2", "k3", "k4");
+ store.store(new StoredEntry("k1", "v1"));
+ store.store(new StoredEntry("k2", "v2"));
+ store.store(new StoredEntry("k3", "v3"));
+ store.store(new StoredEntry("k4", "v4"));
+
+ for (int i = 1; i < 5; i++) assert cache.get("k" + i).equals("v" + i);
+
+ for (int i = 1; i < 5; i++) cache.evict("k" + i);
+
+ assert cache.putIfAbsent("k1", "v1-SHOULD-NOT-STORE").equals("v1");
+ assert cache.remove("k2").equals("v2");
+ assert cache.replace("k3", "v3-REPLACED").equals("v3");
+ assert cache.replace("k4", "v4", "v4-REPLACED");
+
+ assert cache.size() == 3 : "Expected the cache to contain 3 elements but contained " + cache.size();
+
+ for (int i = 1; i < 5; i++) cache.evict("k" + i);
+ assert cache.size() == 0; // cache size ops will not trigger a load
+
+ cache.clear(); // this should propagate to the loader though
+ assertNotInCacheAndStore("k1", "k2", "k3", "k4");
+ }
+
+ public void testPreloading() {
+ Configuration preloadingCfg = cfg.clone();
+ preloadingCfg.getCacheLoaderConfig().setPreload(true);
+ ((DummyInMemoryCacheLoader.Cfg) preloadingCfg.getCacheLoaderConfig().getFirstCacheLoaderConfig()).setStore("preloadingCache");
+ cm.defineCache("preloadingCache", preloadingCfg);
+ Cache preloadingCache = cm.getCache("preloadingCache");
+ CacheStore preloadingStore = TestingUtil.extractComponent(preloadingCache, CacheLoaderManager.class).getCacheStore();
+
+ assert preloadingCache.getConfiguration().getCacheLoaderConfig().isPreload();
+
+ assertNotInCacheAndStore(preloadingCache, preloadingStore, "k1", "k2", "k3", "k4");
+
+ preloadingCache.put("k1", "v1");
+ preloadingCache.put("k2", "v2", lifespan, MILLISECONDS);
+ preloadingCache.put("k3", "v3");
+ preloadingCache.put("k4", "v4", lifespan, MILLISECONDS);
+
+ for (int i = 1; i < 5; i++) {
+ if (i % 2 == 1)
+ assertInCacheAndStore(preloadingCache, preloadingStore, "k" + i, "v" + i);
+ else
+ assertInCacheAndStore(preloadingCache, preloadingStore, "k" + i, "v" + i, lifespan);
+ }
+
+ DataContainer c = preloadingCache.getAdvancedCache().getDataContainer();
+ assert c.size() == 4;
+ preloadingCache.stop();
+ assert c.size() == 0;
+
+ preloadingCache.start();
+ assert preloadingCache.getConfiguration().getCacheLoaderConfig().isPreload();
+ c = preloadingCache.getAdvancedCache().getDataContainer();
+ assert c.size() == 4;
+
+ for (int i = 1; i < 5; i++) {
+ if (i % 2 == 1)
+ assertInCacheAndStore(preloadingCache, preloadingStore, "k" + i, "v" + i);
+ else
+ assertInCacheAndStore(preloadingCache, preloadingStore, "k" + i, "v" + i, lifespan);
+ }
+ }
+
+ public void testPurgeOnStartup() {
+ Configuration purgingCfg = cfg.clone();
+ purgingCfg.getCacheLoaderConfig().getFirstCacheLoaderConfig().setPurgeOnStartup(true);
+ ((DummyInMemoryCacheLoader.Cfg) purgingCfg.getCacheLoaderConfig().getFirstCacheLoaderConfig()).setStore("purgingCache");
+ cm.defineCache("purgingCache", purgingCfg);
+ Cache purgingCache = cm.getCache("purgingCache");
+ CacheStore purgingStore = TestingUtil.extractComponent(purgingCache, CacheLoaderManager.class).getCacheStore();
+
+ assertNotInCacheAndStore(purgingCache, purgingStore, "k1", "k2", "k3", "k4");
+
+ purgingCache.put("k1", "v1");
+ purgingCache.put("k2", "v2", lifespan, MILLISECONDS);
+ purgingCache.put("k3", "v3");
+ purgingCache.put("k4", "v4", lifespan, MILLISECONDS);
+
+ for (int i = 1; i < 5; i++) {
+ if (i % 2 == 1)
+ assertInCacheAndStore(purgingCache, purgingStore, "k" + i, "v" + i);
+ else
+ assertInCacheAndStore(purgingCache, purgingStore, "k" + i, "v" + i, lifespan);
+ }
+
+ DataContainer c = purgingCache.getAdvancedCache().getDataContainer();
+ assert c.size() == 4;
+ purgingCache.stop();
+ assert c.size() == 0;
+
+ purgingCache.start();
+ c = purgingCache.getAdvancedCache().getDataContainer();
+ assert c.size() == 0;
+
+ assertNotInCacheAndStore(purgingCache, purgingStore, "k1", "k2", "k3", "k4");
+ }
+
+ public void testTransactionalWrites() throws Exception {
+ assert cache.getStatus() == ComponentStatus.RUNNING;
+ assertNotInCacheAndStore("k1", "k2");
+
+ tm.begin();
+ cache.put("k1", "v1");
+ cache.put("k2", "v2", lifespan, MILLISECONDS);
+ Transaction t = tm.suspend();
+
+ assertNotInCacheAndStore("k1", "k2");
+
+ tm.resume(t);
+ tm.commit();
+
+ assertInCacheAndStore("k1", "v1");
+ assertInCacheAndStore("k2", "v2", lifespan);
+
+ tm.begin();
+ cache.clear();
+ t = tm.suspend();
+
+ assertInCacheAndStore("k1", "v1");
+ assertInCacheAndStore("k2", "v2", lifespan);
+ tm.resume(t);
+ tm.commit();
+
+ assertNotInCacheAndStore("k1", "k2");
+
+ tm.begin();
+ cache.put("k1", "v1");
+ cache.put("k2", "v2", lifespan, MILLISECONDS);
+ t = tm.suspend();
+
+ assertNotInCacheAndStore("k1", "k2");
+
+ tm.resume(t);
+ tm.rollback();
+
+ assertNotInCacheAndStore("k1", "k2");
+ cache.put("k1", "v1");
+ cache.put("k2", "v2", lifespan, MILLISECONDS);
+
+ assertInCacheAndStore("k1", "v1");
+ assertInCacheAndStore("k2", "v2", lifespan);
+
+ tm.begin();
+ cache.clear();
+ t = tm.suspend();
+
+ assertInCacheAndStore("k1", "v1");
+ assertInCacheAndStore("k2", "v2", lifespan);
+ tm.resume(t);
+ tm.rollback();
+
+ assertInCacheAndStore("k1", "v1");
+ assertInCacheAndStore("k2", "v2", lifespan);
+ }
+}
Copied: core/branches/flat/src/test/java/org/horizon/loader/decorators/AsyncTest.java (from rev 7695, core/branches/flat/src/test/java/org/horizon/loader/AsyncTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/loader/decorators/AsyncTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/loader/decorators/AsyncTest.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -0,0 +1,61 @@
+package org.horizon.loader.decorators;
+
+import org.horizon.CacheException;
+import org.horizon.loader.StoredEntry;
+import org.horizon.loader.dummy.DummyInMemoryCacheLoader;
+import org.horizon.util.TestingUtil;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.AfterTest;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Test;
+
+import java.util.concurrent.ExecutorService;
+
+@Test(groups = "unit", sequential = true)
+public class AsyncTest {
+
+ AsyncStore store;
+ ExecutorService asyncExecutor;
+
+
+ @BeforeTest
+ public void setUp() {
+ store = new AsyncStore(new DummyInMemoryCacheLoader(), new AsyncStoreConfig());
+ DummyInMemoryCacheLoader.Cfg cfg = new DummyInMemoryCacheLoader.Cfg();
+ cfg.setStore(AsyncTest.class.getName());
+ store.init(cfg, null, null);
+ store.start();
+ asyncExecutor = (ExecutorService) TestingUtil.extractField(store, "executor");
+ }
+
+ @AfterTest
+ public void tearDown() {
+ if (store != null) store.stop();
+ }
+
+ @AfterMethod
+ public void clearStore() {
+ if (store != null) store.clear();
+ }
+
+ public void testRestrictionOnAddingToAsyncQueue() throws Exception {
+ store.remove("blah");
+
+ store.store(new StoredEntry("one", "value"));
+ store.store(new StoredEntry("two", "value"));
+ store.store(new StoredEntry("three", "value"));
+ store.store(new StoredEntry("four", "value"));
+
+ // stop the cache store
+ store.stop();
+ try {
+ store.remove("blah");
+ assert false : "Should have restricted this entry from being made";
+ }
+ catch (CacheException expected) {
+ }
+
+ // clean up
+ store.start();
+ }
+}
Added: core/branches/flat/src/test/java/org/horizon/loader/decorators/ReadOnlyCacheStoreTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/loader/decorators/ReadOnlyCacheStoreTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/loader/decorators/ReadOnlyCacheStoreTest.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -0,0 +1,32 @@
+package org.horizon.loader.decorators;
+
+import static org.easymock.EasyMock.*;
+import org.horizon.loader.CacheStore;
+import org.horizon.loader.StoredEntry;
+import org.testng.annotations.Test;
+
+import java.io.InputStream;
+
+@Test(groups = "unit")
+public class ReadOnlyCacheStoreTest {
+ public void testWriteMethods() {
+ CacheStore mock = createMock(CacheStore.class);
+ ReadOnlyStore store = new ReadOnlyStore(mock);
+ StoredEntry mockEntry = new StoredEntry();
+ expect(mock.load(eq("key"))).andReturn(mockEntry).once();
+ replay(mock);
+
+ // these should be "silent" no-ops and not actually change anything.
+ store.clear();
+ store.purgeExpired();
+ store.remove("key");
+ store.store((StoredEntry) null);
+ store.store((InputStream) null);
+ store.prepare(null, null, true);
+ store.commit(null);
+ store.rollback(null);
+ assert mockEntry == store.load("key");
+
+ verify(mock);
+ }
+}
Added: core/branches/flat/src/test/java/org/horizon/loader/decorators/SingletonStoreTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/loader/decorators/SingletonStoreTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/loader/decorators/SingletonStoreTest.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -0,0 +1,321 @@
+package org.horizon.loader.decorators;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.horizon.BaseClusteredTest;
+import org.horizon.Cache;
+import org.horizon.config.CacheLoaderManagerConfig;
+import org.horizon.config.Configuration;
+import org.horizon.loader.CacheLoaderManager;
+import org.horizon.loader.CacheStore;
+import org.horizon.loader.StoredEntry;
+import org.horizon.loader.dummy.DummyInMemoryCacheLoader;
+import org.horizon.manager.CacheManager;
+import org.horizon.util.TestingUtil;
+import org.horizon.util.internals.ViewChangeListener;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.fail;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+
+@Test(groups = "functional", sequential = true)
+public class SingletonStoreTest extends BaseClusteredTest {
+ private static final Log log = LogFactory.getLog(SingletonStoreTest.class);
+ private static final AtomicInteger storeCounter = new AtomicInteger(0);
+ private CacheManager cm0, cm1, cm2;
+
+ @BeforeMethod
+ public void setUp() {
+ cm0 = addClusterEnabledCacheManager();
+ cm1 = addClusterEnabledCacheManager();
+ cm2 = addClusterEnabledCacheManager();
+
+ Configuration conf = new Configuration();
+ conf.setCacheMode(Configuration.CacheMode.REPL_SYNC);
+ DummyInMemoryCacheLoader.Cfg cfg = new DummyInMemoryCacheLoader.Cfg();
+ cfg.setStore("Store-" + storeCounter.getAndIncrement());
+ CacheLoaderManagerConfig pushingCfg = new CacheLoaderManagerConfig();
+ pushingCfg.addIndividualCacheLoaderConfig(cfg);
+ SingletonStoreConfig ssc = new SingletonStoreConfig();
+ ssc.setPushStateWhenCoordinator(true);
+ ssc.setSingletonStoreEnabled(true);
+ cfg.setSingletonStoreConfig(ssc);
+ conf.setCacheLoaderConfig(pushingCfg);
+
+ // cannot define on ALL cache managers since the same dummy in memory CL bin will be used!
+ cm0.defineCache("pushing", conf);
+ ((DummyInMemoryCacheLoader.Cfg) conf.getCacheLoaderConfig().getFirstCacheLoaderConfig()).setStore("Store-" + storeCounter.getAndIncrement());
+ cm1.defineCache("pushing", conf);
+ ((DummyInMemoryCacheLoader.Cfg) conf.getCacheLoaderConfig().getFirstCacheLoaderConfig()).setStore("Store-" + storeCounter.getAndIncrement());
+ cm2.defineCache("pushing", conf);
+
+ conf = new Configuration();
+ conf.setCacheMode(Configuration.CacheMode.REPL_SYNC);
+ cfg = new DummyInMemoryCacheLoader.Cfg();
+ cfg.setStore("Store-" + storeCounter.getAndIncrement());
+ CacheLoaderManagerConfig nonPushingCfg = new CacheLoaderManagerConfig();
+ nonPushingCfg.addIndividualCacheLoaderConfig(cfg);
+ ssc = new SingletonStoreConfig();
+ ssc.setPushStateWhenCoordinator(false);
+ ssc.setSingletonStoreEnabled(true);
+ cfg.setSingletonStoreConfig(ssc);
+ conf.setCacheLoaderConfig(nonPushingCfg);
+
+ // cannot define on ALL cache managers since the same dummy in memory CL bin will be used!
+ cm0.defineCache("nonPushing", conf);
+ ((DummyInMemoryCacheLoader.Cfg) conf.getCacheLoaderConfig().getFirstCacheLoaderConfig()).setStore("Store-" + storeCounter.getAndIncrement());
+ cm1.defineCache("nonPushing", conf);
+ ((DummyInMemoryCacheLoader.Cfg) conf.getCacheLoaderConfig().getFirstCacheLoaderConfig()).setStore("Store-" + storeCounter.getAndIncrement());
+ cm2.defineCache("nonPushing", conf);
+ }
+
+ private Cache[] getCaches(String name) {
+ return new Cache[]{
+ cm0.getCache(name), cm1.getCache(name), cm2.getCache(name)
+ };
+ }
+
+ private SingletonStore[] extractStores(Cache[] caches) {
+ SingletonStore[] stores = new SingletonStore[caches.length];
+
+ int i = 0;
+ for (Cache c : caches)
+ stores[i++] = (SingletonStore) TestingUtil.extractComponent(c, CacheLoaderManager.class).getCacheStore();
+ return stores;
+ }
+
+ private Object load(CacheStore cs, Object key) {
+ StoredEntry se = cs.load(key);
+ return se == null ? null : se.getValue();
+ }
+
+ public void testPutCacheLoaderWithNoPush() throws Exception {
+ Cache[] caches = getCaches("nonPushing");
+ for (Cache c : caches) c.start();
+
+ int i = 1;
+ for (Cache c : caches) {
+ c.put("key" + i, "value" + i);
+ i++;
+ }
+
+ // all values should be on all caches since they are sync-repl
+ for (Cache c : caches) {
+ for (i = 1; i < 4; i++) assert c.get("key" + i).equals("value" + i);
+ }
+
+ // now test the stores. These should *only* be on the store on cache 1.
+ CacheStore[] stores = extractStores(caches);
+
+ for (i = 1; i < 4; i++) {
+ // should ONLY be on the first loader!
+ assert load(stores[0], "key" + i).equals("value" + i);
+ assert load(stores[1], "key" + i) == null : "stores[1] should not have stored key key" + i;
+ assert load(stores[2], "key" + i) == null : "stores[2] should not have stored key key" + i;
+ }
+
+ cm0.stop();
+ TestingUtil.blockUntilViewsReceived(60000, cm1, cm2);
+
+ caches[1].put("key4", "value4");
+ caches[2].put("key5", "value5");
+
+ assert load(stores[1], "key4").equals("value4");
+ assert load(stores[1], "key5").equals("value5");
+
+ assert load(stores[2], "key4") == null;
+ assert load(stores[2], "key5") == null;
+
+ cm1.stop();
+ TestingUtil.blockUntilViewsReceived(60000, cm2);
+
+ caches[2].put("key6", "value6");
+ assert load(stores[2], "key6").equals("value6");
+ }
+
+ public void testPutCacheLoaderWithPush() throws Exception {
+ Cache[] caches = getCaches("pushing");
+ for (Cache c : caches) c.start();
+ Map<String, String> expected = new HashMap<String, String>();
+
+ expected.put("a-key", "a-value");
+ expected.put("aa-key", "aa-value");
+ expected.put("b-key", "b-value");
+ expected.put("bb-key", "bb-value");
+ expected.put("c-key", "c-value");
+ expected.put("d-key", "d-value");
+ expected.put("e-key", "e-value");
+ expected.put("g-key", "g-value");
+
+ caches[0].putAll(expected);
+
+ SingletonStore[] stores = extractStores(caches);
+
+ for (String key : expected.keySet()) {
+ assert load(stores[0], key).equals(expected.get(key));
+ assert load(stores[1], key) == null;
+ assert load(stores[2], key) == null;
+ }
+
+ ViewChangeListener viewChangeListener = new ViewChangeListener(caches[1]);
+
+ cm0.stop();
+
+ viewChangeListener.waitForViewChange(60, TimeUnit.SECONDS);
+
+ waitForPushStateCompletion(stores[1].pushStateFuture);
+
+ // cache store 1 should have all state now, and store 2 should have nothing
+
+ for (String key : expected.keySet()) {
+ assert load(stores[1], key).equals(expected.get(key));
+ assert load(stores[2], key) == null;
+ }
+
+ caches[1].put("h-key", "h-value");
+ caches[2].put("i-key", "i-value");
+ expected.put("h-key", "h-value");
+ expected.put("i-key", "i-value");
+
+ for (String key : expected.keySet()) {
+ assert load(stores[1], key).equals(expected.get(key));
+ assert load(stores[2], key) == null;
+ }
+
+ viewChangeListener = new ViewChangeListener(caches[2]);
+ cm1.stop();
+ viewChangeListener.waitForViewChange(60, TimeUnit.SECONDS);
+
+ waitForPushStateCompletion(stores[2].pushStateFuture);
+
+ for (String key : expected.keySet()) assert load(stores[2], key).equals(expected.get(key));
+
+ caches[2].put("aaa-key", "aaa-value");
+ expected.put("aaa-key", "aaa-value");
+
+ for (String key : expected.keySet()) assert load(stores[2], key).equals(expected.get(key));
+ }
+
+ public void testAvoidConcurrentStatePush() throws Exception {
+ final ExecutorService executor = Executors.newFixedThreadPool(2);
+ final CountDownLatch pushStateCanFinish = new CountDownLatch(1);
+ final CountDownLatch secondActiveStatusChangerCanStart = new CountDownLatch(1);
+ final TestingSingletonStore mscl = new TestingSingletonStore(pushStateCanFinish, secondActiveStatusChangerCanStart, new SingletonStoreConfig());
+
+ Future f1 = executor.submit(createActiveStatusChanger(mscl));
+ assert secondActiveStatusChangerCanStart.await(1000, TimeUnit.MILLISECONDS) : "Failed waiting on latch";
+
+ Future f2 = executor.submit(createActiveStatusChanger(mscl));
+
+ f1.get();
+ f2.get();
+
+ assertEquals(1, mscl.getNumberCreatedTasks());
+ }
+
+ public void testPushStateTimedOut() throws Throwable {
+ final CountDownLatch pushStateCanFinish = new CountDownLatch(1);
+ SingletonStoreConfig ssdc = new SingletonStoreConfig();
+ ssdc.setPushStateTimeout(100);
+ final TestingSingletonStore mscl = new TestingSingletonStore(pushStateCanFinish, null, ssdc);
+
+ Future f = Executors.newSingleThreadExecutor().submit(createActiveStatusChanger(mscl));
+ pushStateCanFinish.await(200, TimeUnit.MILLISECONDS);
+ pushStateCanFinish.countDown();
+
+ try {
+ f.get();
+ fail("Should have timed out");
+ }
+ catch (ExecutionException expected) {
+ Throwable e;
+ if ((e = expected.getCause().getCause().getCause()) instanceof TimeoutException) {
+ assert true : "This is expected";
+ } else {
+ throw e;
+ }
+ }
+ }
+
+ private void waitForPushStateCompletion(Future pushThreadFuture) throws Exception {
+ if (pushThreadFuture != null) pushThreadFuture.get();
+ }
+
+ private Callable<?> createActiveStatusChanger(SingletonStore mscl) {
+ return new ActiveStatusModifier(mscl);
+ }
+
+ class TestingSingletonStore extends SingletonStore {
+ private int numberCreatedTasks = 0;
+ private CountDownLatch pushStateCanFinish;
+ private CountDownLatch secondActiveStatusChangerCanStart;
+
+ public TestingSingletonStore(CountDownLatch pushStateCanFinish, CountDownLatch secondActiveStatusChangerCanStart, SingletonStoreConfig cfg) {
+ super(null, null, cfg);
+ this.pushStateCanFinish = pushStateCanFinish;
+ this.secondActiveStatusChangerCanStart = secondActiveStatusChangerCanStart;
+ }
+
+ public int getNumberCreatedTasks() {
+ return numberCreatedTasks;
+ }
+
+ public void setNumberCreatedTasks(int numberCreatedTasks) {
+ this.numberCreatedTasks = numberCreatedTasks;
+ }
+
+ @Override
+ protected Callable<?> createPushStateTask() {
+ return new Callable() {
+ public Object call() throws Exception {
+ numberCreatedTasks++;
+ try {
+ if (secondActiveStatusChangerCanStart != null) {
+ secondActiveStatusChangerCanStart.countDown();
+ }
+ pushStateCanFinish.await();
+ }
+ catch (InterruptedException e) {
+ fail("ActiveStatusModifier interrupted");
+ }
+ return null;
+ }
+ };
+ }
+
+
+ @Override
+ protected void awaitForPushToFinish(Future future, long timeout, TimeUnit unit) {
+ pushStateCanFinish.countDown();
+ super.awaitForPushToFinish(future, timeout, unit);
+ }
+ }
+
+ class ActiveStatusModifier implements Callable {
+ private SingletonStore scl;
+
+ public ActiveStatusModifier(SingletonStore singleton) {
+ scl = singleton;
+ }
+
+ public Object call() throws Exception {
+ log.debug("active status modifier started");
+ scl.activeStatusChanged(true);
+ scl.pushStateFuture.get();
+
+ return null;
+ }
+ }
+}
Modified: core/branches/flat/src/test/java/org/horizon/loader/dummy/DummyInMemoryCacheLoader.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/loader/dummy/DummyInMemoryCacheLoader.java 2009-02-16 14:25:32 UTC (rev 7696)
+++ core/branches/flat/src/test/java/org/horizon/loader/dummy/DummyInMemoryCacheLoader.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -5,6 +5,8 @@
import org.horizon.loader.AbstractCacheStore;
import org.horizon.loader.CacheLoaderConfig;
import org.horizon.loader.StoredEntry;
+import org.horizon.logging.Log;
+import org.horizon.logging.LogFactory;
import org.horizon.marshall.Marshaller;
import java.io.IOException;
@@ -20,7 +22,7 @@
import java.util.concurrent.ConcurrentMap;
public class DummyInMemoryCacheLoader extends AbstractCacheStore {
-
+ private static final Log log = LogFactory.getLog(DummyInMemoryCacheLoader.class);
static final ConcurrentMap<String, Map> stores = new ConcurrentHashMap<String, Map>();
String storeName = "__DEFAULT_STORES__";
Map<Object, StoredEntry> store;
@@ -73,6 +75,7 @@
StoredEntry se = store.get(key);
if (se == null) return null;
if (se.isExpired()) {
+ log.debug("Key {0} exists, but has expired. Entry is {1}", key, se);
store.remove(key);
return null;
}
@@ -84,9 +87,10 @@
Set<StoredEntry> s = new HashSet<StoredEntry>();
for (Iterator<StoredEntry> i = store.values().iterator(); i.hasNext();) {
StoredEntry se = i.next();
- if (se.isExpired())
+ if (se.isExpired()) {
+ log.debug("Key {0} exists, but has expired. Entry is {1}", se.getKey(), se);
i.remove();
- else
+ } else
s.add(se);
}
return s;
@@ -109,13 +113,16 @@
}
public void stop() {
- stores.remove(storeName);
}
public static class Cfg extends AbstractCacheLoaderConfig {
boolean debug;
- String store;
+ String store = "__DEFAULT_STORE__";
+ public Cfg() {
+ setClassName(DummyInMemoryCacheLoader.class.getName());
+ }
+
public boolean isDebug() {
return debug;
}
@@ -131,5 +138,10 @@
public void setStore(String store) {
this.store = store;
}
+
+ @Override
+ public Cfg clone() {
+ return (Cfg) super.clone();
+ }
}
}
Added: core/branches/flat/src/test/java/org/horizon/util/internals/ViewChangeListener.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/util/internals/ViewChangeListener.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/util/internals/ViewChangeListener.java 2009-02-17 01:07:15 UTC (rev 7697)
@@ -0,0 +1,45 @@
+package org.horizon.util.internals;
+
+import org.horizon.Cache;
+import org.horizon.manager.CacheManager;
+import org.horizon.notifications.Listener;
+import org.horizon.notifications.cachemanagerlistener.annotation.ViewChanged;
+import org.horizon.notifications.cachemanagerlistener.event.ViewChangedEvent;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Listens for view changes. Note that you do NOT have to register this listener; it does so automatically when
+ * constructed.
+ */
+@Listener
+public class ViewChangeListener {
+ CacheManager cm;
+ final CountDownLatch latch = new CountDownLatch(1);
+
+ public ViewChangeListener(Cache c) {
+ this(c.getCacheManager());
+ }
+
+ public ViewChangeListener(CacheManager cm) {
+ this.cm = cm;
+ cm.addListener(this);
+ }
+
+ @ViewChanged
+ public void onViewChange(ViewChangedEvent e) {
+ latch.countDown();
+ }
+
+ /**
+ * Blocks for a certain amount of time until a view change is received. Note that this class will start listening
+ * for the view change the moment it is constructed.
+ *
+ * @param time time to wait
+ * @param unit time unit
+ */
+ public void waitForViewChange(long time, TimeUnit unit) throws InterruptedException {
+ if (!latch.await(time, unit)) assert false : "View change not seen after " + time + " " + unit;
+ }
+}
15 years, 10 months
JBoss Cache SVN: r7696 - in core/trunk/src: test/java/org/jboss/cache and 13 other directories.
by jbosscache-commits@lists.jboss.org
Author: mircea.markus
Date: 2009-02-16 09:25:32 -0500 (Mon, 16 Feb 2009)
New Revision: 7696
Added:
core/trunk/src/test/java/org/jboss/cache/TestNameVerifier.java
Modified:
core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java
core/trunk/src/test/java/org/jboss/cache/buddyreplication/BuddyReplicationRejoinTest.java
core/trunk/src/test/java/org/jboss/cache/buddyreplication/mvcc/Buddy3NodesWithPoolNoDataGravitationTest.java
core/trunk/src/test/java/org/jboss/cache/commands/legacy/write/MoveCommandTest.java
core/trunk/src/test/java/org/jboss/cache/commands/legacy/write/PutDataMapCommandTest.java
core/trunk/src/test/java/org/jboss/cache/commands/legacy/write/VersionedInvalidateCommandTest.java
core/trunk/src/test/java/org/jboss/cache/config/ConfigurationTransformerTest.java
core/trunk/src/test/java/org/jboss/cache/config/parsing/CustomInterceptorsElementParserTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/JmxManualTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/CacheJmxWrapperTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/InterceptorRegistrationTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LegacyConfigurationTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LifecycleNotificationTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/OptimisticNotificationTest.java
core/trunk/src/test/java/org/jboss/cache/loader/UnnecessaryLoadingSetDataTest.java
core/trunk/src/test/java/org/jboss/cache/options/cachemodelocal/AsyncInvalidationOptLocksTest.java
core/trunk/src/test/java/org/jboss/cache/profiling/MockAsyncReplTest.java
core/trunk/src/test/java/org/jboss/cache/profiling/ProfileMapViewTest.java
core/trunk/src/test/java/org/jboss/cache/statetransfer/NonBlockingStateTransferTest.java
core/trunk/src/test/java/org/jboss/cache/transaction/MarkAsRollbackTest.java
core/trunk/src/test/java/org/jboss/cache/util/FastCopyHashMapTest.java
Log:
added test to check UT correctness
Modified: core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -877,18 +877,18 @@
*/
public boolean invocationsAllowed(boolean originLocal)
{
- log.trace("Testing if invocations are allowed.");
+ if (trace) 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.");
+ if (trace) 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 && blockInStarting)
{
- log.trace("Cache is starting; block.");
+ if (trace) log.trace("Cache is starting; block.");
try
{
blockUntilCacheStarts();
Added: core/trunk/src/test/java/org/jboss/cache/TestNameVerifier.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/TestNameVerifier.java (rev 0)
+++ core/trunk/src/test/java/org/jboss/cache/TestNameVerifier.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -0,0 +1,209 @@
+package org.jboss.cache;
+
+import org.testng.annotations.Test;
+
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.io.FilenameFilter;
+import java.io.File;
+import java.io.FileFilter;
+import java.io.PrintWriter;
+import java.io.BufferedReader;
+import java.io.FileReader;
+
+/**
+ * Class that tests that test names are correclty set for each test.
+ *
+ * @author Mircea.Markus(a)jboss.com
+ */
+@Test(groups = "functional", testName = "TestNameVerifier")
+public class TestNameVerifier {
+ String dir = "src\\test\\java\\org\\jboss\\cache";
+
+ Pattern packageLinePattern = Pattern.compile("package org.jboss.cache[^;]*");
+ Pattern classLinePattern = Pattern.compile("(abstract\\s*)??(public\\s*)(abstract\\s*)??class [^\\s]*");
+ Pattern atAnnotationPattern = Pattern.compile("@Test[^)]*");
+ Pattern testNamePattern = Pattern.compile("testName\\s*=\\s*\"[^\"]*\"");
+
+ String fileCache;
+
+ FilenameFilter javaFilter = new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ if (dir.getAbsolutePath().contains("testng")) return false;
+ return name.endsWith(".java");
+ }
+ };
+
+ FileFilter onlyDirs = new FileFilter() {
+ public boolean accept(File pathname) {
+ return pathname.isDirectory();
+ }
+ };
+
+ @Test(enabled = false, description = "Do not enable this unless you want your files to be updated with test names!!!")
+ public void process() throws Exception {
+ File[] javaFiles = getJavaFiles();
+ for (File file : javaFiles) {
+ if (needsUpdate(file)) {
+ System.out.println("Updating file: " + file.getAbsolutePath());
+ updateFile(file);
+ }
+ }
+ }
+
+ private void updateFile(File file) throws Exception {
+ String javaString = fileCache;
+ String testName = getTestName(javaString, file.getName());
+ String testNameStr = ", testName = \"" + testName + "\"";
+ javaString = replaceAtTestAnnotation(javaString, testNameStr);
+ persistNewFile(file, javaString);
+ }
+
+ private void persistNewFile(File file, String javaString) throws Exception {
+ if (file.delete()) {
+ System.out.println("!!!!!!!!!! error porcessing file " + file.getName());
+ return;
+ }
+ file.createNewFile();
+ PrintWriter writter = new PrintWriter(file);
+ writter.append(javaString);
+ writter.close();
+ }
+
+ private String replaceAtTestAnnotation(String javaString, String testNameStr) {
+ Matcher matcher = atAnnotationPattern.matcher(javaString);
+ boolean found = matcher.find();
+ assert found;
+ String theMatch = matcher.group();
+ return matcher.replaceFirst(theMatch + testNameStr);
+ }
+
+ private String getTestName(String javaString, String filename) {
+ String classNamePart = getClassNamePart(javaString, filename);
+
+ //abstract classes do not require test names
+ if (classNamePart.indexOf("abstract") >= 0) return null;
+
+ classNamePart = classNamePart.substring("public class ".length());
+ String packagePart = getPackagePart(javaString, filename);
+ //if the test is in org.horizon package then make sure no . is prepanded
+ String packagePrepend = ((packagePart != null) && (packagePart.length() > 0)) ? packagePart + "." : "";
+ return packagePrepend + classNamePart;
+ }
+
+ private String getClassNamePart(String javaString, String filename) {
+ Matcher matcher = classLinePattern.matcher(javaString);
+ boolean found = matcher.find();
+ assert found : "could not determine class name for file: " + filename;
+ return matcher.group();
+ }
+
+ private String getPackagePart(String javaString, String filename) {
+ Matcher matcher = packageLinePattern.matcher(javaString);
+ boolean found = matcher.find();
+ assert found : "Could not determine package name for file: " + filename;
+ String theMatch = matcher.group();
+ String partial = theMatch.substring("package org.jboss.cache".length());
+ if (partial.trim().length() == 0) return partial.trim();
+ return partial.substring(1);//drop the leading dot.
+ }
+
+
+ private boolean needsUpdate(File file) throws Exception {
+ String javaFileStr = getFileAsString(file);
+ if (javaFileStr.indexOf(" testName = \"") > 0) return false;
+ int atTestIndex = javaFileStr.indexOf("@Test");
+ int classDeclarationIndex = javaFileStr.indexOf("public class");
+ return atTestIndex > 0 && atTestIndex < classDeclarationIndex;
+ }
+
+ private String getFileAsString(File file) throws Exception {
+ StringBuilder builder = new StringBuilder();
+ BufferedReader fileReader = new BufferedReader(new FileReader(file));
+ String line;
+ while ((line = fileReader.readLine()) != null) {
+ builder.append(line + "\n");
+ }
+ this.fileCache = builder.toString();
+// fileReader.close();
+ return fileCache;
+ }
+
+ private File[] getJavaFiles() {
+ File file = new File(dir);
+ assert file.isDirectory();
+ ArrayList<File> result = new ArrayList<File>();
+ addJavaFiles(file, result);
+ return result.toArray(new File[0]);
+ }
+
+ private void addJavaFiles(File file, ArrayList<File> result) {
+ assert file.isDirectory();
+ File[] javaFiles = file.listFiles(javaFilter);
+// printFiles(javaFiles);
+ result.addAll(Arrays.asList(javaFiles));
+ for (File dir : file.listFiles(onlyDirs)) {
+ addJavaFiles(dir, result);
+ }
+ }
+
+ private void printFiles(File[] javaFiles) {
+ for (File f : javaFiles) {
+ System.out.println(f.getAbsolutePath());
+ }
+ }
+
+ public void verifyTestName() throws Exception {
+ File[] javaFiles = getJavaFiles();
+ StringBuilder errorMessage = new StringBuilder("Following test class(es) do not have an appropriate test name: \n");
+ boolean hasErrors = false;
+ for (File file : javaFiles) {
+ String expectedName = incorrectTestName(file);
+ if (expectedName != null) {
+ errorMessage.append(file.getAbsoluteFile()).append(" expected test name is: '").append(expectedName).append("' \n");
+ hasErrors = true;
+ }
+ }
+ assert !hasErrors : errorMessage.append("The rules for writting UTs are being descibed here: https://www.jboss.org/community/docs/DOC-13315");
+ }
+
+ private String incorrectTestName(File file) throws Exception {
+ String fileAsStr = getFileAsString(file);
+
+ boolean containsTestAnnotation = atAnnotationPattern.matcher(fileAsStr).find();
+ if (!containsTestAnnotation) return null;
+
+ String expectedTestName = getTestName(fileAsStr, file.getName());
+ if (expectedTestName == null) return null; //this happens when the class is abstract
+ Matcher matcher = this.testNamePattern.matcher(fileAsStr);
+ if (!matcher.find()) return expectedTestName;
+ String name = matcher.group().trim();
+ int firstIndexOfQuote = name.indexOf('"');
+ String existingTestName = name.substring(firstIndexOfQuote + 1, name.length() - 1); //to ignore last quote
+ if (!existingTestName.equals(expectedTestName)) return expectedTestName;
+ return null;
+ }
+
+
+ @Test(enabled = false)
+ public static void main(String[] args) throws Exception {
+ File file = new File("C:\\jboss\\coding\\za_trunk\\src\\test\\java\\org\\jboss\\cache\\statetransfer\\ForcedStateTransferTest.java");
+ String incorrectName = new TestNameVerifier().incorrectTestName(file);
+ System.out.println("incorrectName = " + incorrectName);
+
+
+// new TestNameVerifier().process();
+// Pattern classLinePattern = Pattern.compile("@Test[^)]*");
+// String totest = "aaaa\n" + "@Test(groups = {\"functional\", \"pessimistic\"})\n" + "{ dsadsadsa";
+// Matcher matcher = classLinePattern.matcher(totest);
+// boolean found = matcher.find();
+// System.out.println("found = " + found);
+// String theMatch = matcher.group();
+// String result = matcher.replaceFirst(theMatch + ", testName=\"alaBala\"");
+// System.out.println("theMatch = " + theMatch);
+// System.out.println("result = " + result);
+
+ }
+}
\ No newline at end of file
Property changes on: core/trunk/src/test/java/org/jboss/cache/TestNameVerifier.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Modified: core/trunk/src/test/java/org/jboss/cache/buddyreplication/BuddyReplicationRejoinTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/buddyreplication/BuddyReplicationRejoinTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/buddyreplication/BuddyReplicationRejoinTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -25,7 +25,7 @@
*
* @author Fredrik Johansson, Cubeia Ltd
*/
-@Test(groups = "functional", testName = "buddyreplication.BuddyReplicationTestsBase")
+@Test(groups = "functional", testName = "buddyreplication.BuddyReplicationRejoinTest")
public class BuddyReplicationRejoinTest extends BuddyReplicationTestsBase
{
private static Log log = LogFactory.getLog(BuddyReplicationRejoinTest.class);
Modified: core/trunk/src/test/java/org/jboss/cache/buddyreplication/mvcc/Buddy3NodesWithPoolNoDataGravitationTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/buddyreplication/mvcc/Buddy3NodesWithPoolNoDataGravitationTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/buddyreplication/mvcc/Buddy3NodesWithPoolNoDataGravitationTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -1,13 +1,12 @@
package org.jboss.cache.buddyreplication.mvcc;
-import org.testng.annotations.Test;
-import org.jboss.cache.buddyreplication.BuddyReplicationTestsBase;
import org.jboss.cache.config.Configuration;
+import org.testng.annotations.Test;
/**
* @author Mircea.Markus(a)jboss.com
*/
-@Test(groups = "functional", testName = "mvcc.buddyreplication.Buddy3NodesWithPoolNoDataGravitationTest")
+@Test(groups = "functional", testName = "buddyreplication.mvcc.Buddy3NodesWithPoolNoDataGravitationTest")
public class Buddy3NodesWithPoolNoDataGravitationTest extends org.jboss.cache.buddyreplication.Buddy3NodesWithPoolNoDataGravitationTest
{
@Override
Modified: core/trunk/src/test/java/org/jboss/cache/commands/legacy/write/MoveCommandTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/commands/legacy/write/MoveCommandTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/commands/legacy/write/MoveCommandTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -18,7 +18,7 @@
* @author Mircea.Markus(a)jboss.com
* @since 2.2
*/
-@Test(groups = "unit", sequential = true)
+@Test(groups = "unit", testName = "commands.legacy.write.MoveCommandTest")
public class MoveCommandTest extends AbstractDataCommandTest
{
MoveCommand command;
Modified: core/trunk/src/test/java/org/jboss/cache/commands/legacy/write/PutDataMapCommandTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/commands/legacy/write/PutDataMapCommandTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/commands/legacy/write/PutDataMapCommandTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -23,7 +23,7 @@
* @author Mircea.Markus(a)jboss.com
* @since 2.2
*/
-@Test(groups = "unit", sequential = true)
+@Test(groups = "unit", testName = "commands.legacy.write.PutDataMapCommandTest")
public class PutDataMapCommandTest extends TestContextBase
{
Fqn testFqn = Fqn.fromString("/testfqn");
Modified: core/trunk/src/test/java/org/jboss/cache/commands/legacy/write/VersionedInvalidateCommandTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/commands/legacy/write/VersionedInvalidateCommandTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/commands/legacy/write/VersionedInvalidateCommandTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -23,7 +23,7 @@
* @author Mircea.Markus(a)jboss.com
* @since 2.2
*/
-@Test(groups = "unit", sequential = true)
+@Test(groups = "unit", testName = "commands.legacy.write.VersionedInvalidateCommandTest")
public class VersionedInvalidateCommandTest extends AbstractDataCommandTest
{
DataVersion dataVersion;
Modified: core/trunk/src/test/java/org/jboss/cache/config/ConfigurationTransformerTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/config/ConfigurationTransformerTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/config/ConfigurationTransformerTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -23,7 +23,7 @@
* @author Mircea.Markus(a)jboss.com
* @since 3.0
*/
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "config.ConfigurationTransformerTest")
public class ConfigurationTransformerTest
{
public static final String XSLT_FILE = "config2to3.xslt";
Modified: core/trunk/src/test/java/org/jboss/cache/config/parsing/CustomInterceptorsElementParserTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/config/parsing/CustomInterceptorsElementParserTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/config/parsing/CustomInterceptorsElementParserTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -37,7 +37,7 @@
* @author Mircea.Markus(a)jboss.com
* @since 3.0
*/
-@Test (groups = "unit")
+@Test (groups = "unit", testName = "config.parsing.CustomInterceptorsElementParserTest")
public class CustomInterceptorsElementParserTest
{
CustomInterceptorsElementParser parser = new CustomInterceptorsElementParser();
Modified: core/trunk/src/test/java/org/jboss/cache/jmx/JmxManualTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/JmxManualTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/JmxManualTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -15,7 +15,7 @@
// do NOT enable this test in SVN as it will cause Hudson (or any other continuous integration test harness) to get
// stuck.
-@Test(groups = "maual", enabled = false)
+@Test(groups = "maual", enabled = false, testName = "jmx.JmxManualTest")
public class JmxManualTest
{
public void testLocal() throws IOException
Modified: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/CacheJmxWrapperTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/CacheJmxWrapperTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/CacheJmxWrapperTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -31,7 +31,7 @@
* @author <a href="mailto:manik AT jboss DOT org">Manik Surtani</a>
* @author Brian Stansberry
*/
-@Test(groups = "functional", testName = "jmx.deprecated.CacheJmxWrapperTestBase")
+@Test(groups = "functional", testName = "jmx.deprecated.CacheJmxWrapperTest")
public class CacheJmxWrapperTest extends CacheJmxWrapperTestBase
{
public void testCacheMBeanBinding() throws Exception
Modified: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/InterceptorRegistrationTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/InterceptorRegistrationTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/InterceptorRegistrationTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -34,7 +34,7 @@
* @author <a href="brian.stansberry(a)jboss.com">Brian Stansberry</a>
* @version $Revision$
*/
-@Test(groups = "functional", testName = "jmx.deprecated.CacheJmxWrapperTestBase")
+@Test(groups = "functional", testName = "jmx.deprecated.InterceptorRegistrationTest")
public class InterceptorRegistrationTest extends CacheJmxWrapperTestBase
{
Modified: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LegacyConfigurationTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LegacyConfigurationTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LegacyConfigurationTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -70,7 +70,7 @@
* @author <a href="brian.stansberry(a)jboss.com">Brian Stansberry</a>
* @version $Revision$
*/
-@Test(groups = "functional", testName = "jmx.deprecated.CacheJmxWrapperTestBase")
+@Test(groups = "functional", testName = "jmx.deprecated.LegacyConfigurationTest")
public class LegacyConfigurationTest extends CacheJmxWrapperTestBase
{
public void testLocalCache() throws Exception
Modified: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LifecycleNotificationTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LifecycleNotificationTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LifecycleNotificationTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -40,7 +40,7 @@
* @author <a href="brian.stansberry(a)jboss.com">Brian Stansberry</a>
* @version $Revision$
*/
-@Test (groups = "functional", testName = "jmx.deprecated.CacheJmxWrapperTestBase")
+@Test (groups = "functional", testName = "jmx.deprecated.LifecycleNotificationTest")
public class LifecycleNotificationTest extends CacheJmxWrapperTestBase
{
public void testGetStateAndStateNotification() throws Exception
Modified: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/OptimisticNotificationTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/OptimisticNotificationTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/OptimisticNotificationTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -12,7 +12,7 @@
/**
* @author <a href="mailto:manik AT jboss DOT org">Manik Surtani (manik AT jboss DOT org)</a>
*/
-@Test (groups = "functional", testName = "jmx.deprecated.NotificationTest")
+@Test (groups = "functional", testName = "jmx.deprecated.OptimisticNotificationTest")
public class OptimisticNotificationTest extends NotificationTest
{
public OptimisticNotificationTest()
Modified: core/trunk/src/test/java/org/jboss/cache/loader/UnnecessaryLoadingSetDataTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/loader/UnnecessaryLoadingSetDataTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/loader/UnnecessaryLoadingSetDataTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -25,7 +25,7 @@
* @author Elias Ross
* @since 3.0.0
*/
-@Test(groups = {"functional", "mvcc"}, enabled = false, description = "To do with the setData() method on Cache, which will only be valid in 3.1.0.GA.")
+@Test(groups = {"functional", "mvcc"}, enabled = false, testName = "loader.UnnecessaryLoadingSetDataTest", description = "To do with the setData() method on Cache, which will only be valid in 3.1.0.GA.")
public class UnnecessaryLoadingSetDataTest
{
private CacheSPI<Object, Object> cache;
Modified: core/trunk/src/test/java/org/jboss/cache/options/cachemodelocal/AsyncInvalidationOptLocksTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/options/cachemodelocal/AsyncInvalidationOptLocksTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/options/cachemodelocal/AsyncInvalidationOptLocksTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -7,12 +7,9 @@
package org.jboss.cache.options.cachemodelocal;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.util.TestingUtil;
-import org.jboss.cache.commands.ReplicableCommand;
-import org.jboss.cache.CacheSPI;
import org.testng.annotations.Test;
-@Test (groups = "functional", testName = "cachemodelocal.AsyncInvalidationOptLocksTest")
+@Test (groups = "functional", testName = "options.cachemodelocal.AsyncInvalidationOptLocksTest")
public class AsyncInvalidationOptLocksTest extends CacheModeLocalTestBase
{
public AsyncInvalidationOptLocksTest()
Modified: core/trunk/src/test/java/org/jboss/cache/profiling/MockAsyncReplTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/profiling/MockAsyncReplTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/profiling/MockAsyncReplTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -22,7 +22,7 @@
* @author Manik Surtani (<a href="mailto:manik AT jboss DOT org">manik AT jboss DOT org</a>)
* @since 3.0
*/
-@Test(groups = "profiling", enabled = false)
+@Test(groups = "profiling", enabled = false, testName="profiling.MockAsyncReplTest")
public class MockAsyncReplTest extends ProfileTest
{
@Override
Modified: core/trunk/src/test/java/org/jboss/cache/profiling/ProfileMapViewTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/profiling/ProfileMapViewTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/profiling/ProfileMapViewTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -26,7 +26,7 @@
/**
* Importnat - make sure you inly enable these tests locally!
*/
-@Test(groups = "profiling", enabled = false)
+@Test(groups = "profiling", enabled = false, testName = "profiling.ProfileMapViewTest")
public class ProfileMapViewTest
{
/*
Modified: core/trunk/src/test/java/org/jboss/cache/statetransfer/NonBlockingStateTransferTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/statetransfer/NonBlockingStateTransferTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/statetransfer/NonBlockingStateTransferTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -7,14 +7,6 @@
package org.jboss.cache.statetransfer;
-import static org.testng.AssertJUnit.assertEquals;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.concurrent.atomic.AtomicReference;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.Cache;
@@ -26,8 +18,14 @@
import org.jboss.cache.config.Configuration.CacheMode;
import org.jboss.cache.factories.UnitTestConfigurationFactory;
import org.jboss.cache.util.TestingUtil;
+import static org.testng.AssertJUnit.assertEquals;
import org.testng.annotations.Test;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+
@Test(groups="functional", testName = "statetransfer.NonBlockingStateTransferTest")
public class NonBlockingStateTransferTest
{
Modified: core/trunk/src/test/java/org/jboss/cache/transaction/MarkAsRollbackTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/transaction/MarkAsRollbackTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/transaction/MarkAsRollbackTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -13,7 +13,7 @@
import javax.transaction.RollbackException;
import javax.transaction.TransactionManager;
-@Test(groups = "functional")
+@Test(groups = "functional", testName = "transaction.MarkAsRollbackTest")
public class MarkAsRollbackTest
{
private static final Fqn fqn = Fqn.fromString("/a/b/c");
Modified: core/trunk/src/test/java/org/jboss/cache/util/FastCopyHashMapTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/util/FastCopyHashMapTest.java 2009-02-13 19:07:47 UTC (rev 7695)
+++ core/trunk/src/test/java/org/jboss/cache/util/FastCopyHashMapTest.java 2009-02-16 14:25:32 UTC (rev 7696)
@@ -8,7 +8,7 @@
import java.io.ObjectOutputStream;
import java.util.Map;
-@Test(groups = "unit")
+@Test(groups = "unit", testName = "util.FastCopyHashMapTest")
public class FastCopyHashMapTest
{
public void testSerialization() throws Exception
15 years, 10 months
JBoss Cache SVN: r7695 - core/trunk/src/test/resources.
by jbosscache-commits@lists.jboss.org
Author: jason.greene(a)jboss.com
Date: 2009-02-13 14:07:47 -0500 (Fri, 13 Feb 2009)
New Revision: 7695
Modified:
core/trunk/src/test/resources/log4j.xml
Log:
INFO is better than warn :)
Modified: core/trunk/src/test/resources/log4j.xml
===================================================================
--- core/trunk/src/test/resources/log4j.xml 2009-02-13 19:07:31 UTC (rev 7694)
+++ core/trunk/src/test/resources/log4j.xml 2009-02-13 19:07:47 UTC (rev 7695)
@@ -57,7 +57,7 @@
<!-- ================ -->
<category name="org.jboss.cache">
- <priority value="WARN"/>
+ <priority value="INFO"/>
</category>
<!-- these two are in separate sections since they
15 years, 10 months
JBoss Cache SVN: r7694 - core/trunk/src/main/java/org/jboss/cache.
by jbosscache-commits@lists.jboss.org
Author: jason.greene(a)jboss.com
Date: 2009-02-13 14:07:31 -0500 (Fri, 13 Feb 2009)
New Revision: 7694
Modified:
core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java
Log:
Use multiple impls of flush tracker
Modified: core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java 2009-02-13 19:06:47 UTC (rev 7693)
+++ core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java 2009-02-13 19:07:31 UTC (rev 7694)
@@ -131,7 +131,7 @@
private volatile boolean isInLocalMode;
private ComponentRegistry componentRegistry;
private LockManager lockManager;
- private FlushTracker flushTracker = new FlushTracker();
+ private FlushTracker flushTracker;
@Inject
@@ -153,11 +153,11 @@
this.lockManager = lockManager;
}
- public class FlushTracker
+ public abstract class FlushTracker
{
private final ReclosableLatch flushBlockGate = new ReclosableLatch();
private final AtomicInteger flushCompletionCount = new AtomicInteger();
- private final ReentrantReadWriteLock coordinationLock = new ReentrantReadWriteLock();
+
private final ReclosableLatch flushWaitGate = new ReclosableLatch(false);
public void block()
@@ -178,18 +178,21 @@
return flushCompletionCount.get();
}
- public void lockProcessingLock()
+ public abstract void lockProcessingLock();
+ public abstract void unlockProcessingLock();
+ public abstract void lockSuspendProcessingLock();
+ public abstract void unlockSuspendProcessingLock();
+
+ public void waitForFlushCompletion(long timeout)
{
- if (! configuration.isNonBlockingStateTransfer())
- return;
-
- for (;;)
+ for (; ;)
{
try
{
- if (!coordinationLock.readLock().tryLock(configuration.getStateRetrievalTimeout(), TimeUnit.MILLISECONDS))
- throw new TimeoutException("Could not obtain processing lock");
-
+ if (channel.flushSupported() && !flushBlockGate.await(timeout, TimeUnit.MILLISECONDS))
+ {
+ throw new TimeoutException("State retrieval timed out waiting for flush to unblock. (timeout = " + timeout + " millis) ");
+ }
return;
}
catch (InterruptedException e)
@@ -199,26 +202,16 @@
}
}
- public void unlockProcessingLock()
+ public void waitForFlushStart(long timeout)
{
- if (! configuration.isNonBlockingStateTransfer())
- return;
-
- coordinationLock.readLock().unlock();
- }
-
- public void lockSuspendProcessingLock()
- {
- if (! configuration.isNonBlockingStateTransfer())
- return;
-
- for (;;)
+ for (; ;)
{
try
{
- if (!coordinationLock.writeLock().tryLock(configuration.getStateRetrievalTimeout(), TimeUnit.MILLISECONDS))
- throw new TimeoutException("Could not obtain processing lock");
-
+ if (channel.flushSupported() && !flushWaitGate.await(timeout, TimeUnit.MILLISECONDS))
+ {
+ throw new TimeoutException("State retrieval timed out waiting for flush to block. (timeout = " + timeout + " millis) ");
+ }
return;
}
catch (InterruptedException e)
@@ -227,26 +220,41 @@
}
}
}
+ }
- public void unlockSuspendProcessingLock()
+ private final class StandardFlushTracker extends FlushTracker
+ {
+ // All locking methods are no-ops
+ public void lockProcessingLock()
{
- if (! configuration.isNonBlockingStateTransfer())
- return;
+ }
- if (coordinationLock.isWriteLockedByCurrentThread())
- coordinationLock.writeLock().unlock();
+ public void lockSuspendProcessingLock()
+ {
}
- public void waitForFlushCompletion(long timeout)
+ public void unlockProcessingLock()
{
- for (; ;)
+ }
+
+ public void unlockSuspendProcessingLock()
+ {
+ }
+ }
+
+ private final class NonBlockingFlushTracker extends FlushTracker
+ {
+ private final ReentrantReadWriteLock coordinationLock = new ReentrantReadWriteLock();
+
+ public void lockProcessingLock()
+ {
+ for (;;)
{
try
{
- if (channel.flushSupported() && !flushBlockGate.await(timeout, TimeUnit.MILLISECONDS))
- {
- throw new TimeoutException("State retrieval timed out waiting for flush to block. (timeout = " + timeout + " millis) ");
- }
+ if (!coordinationLock.readLock().tryLock(configuration.getStateRetrievalTimeout(), TimeUnit.MILLISECONDS))
+ throw new TimeoutException("Could not obtain processing lock");
+
return;
}
catch (InterruptedException e)
@@ -256,16 +264,20 @@
}
}
- public void waitForFlushStart(long timeout)
+ public void unlockProcessingLock()
{
- for (; ;)
+ coordinationLock.readLock().unlock();
+ }
+
+ public void lockSuspendProcessingLock()
+ {
+ for (;;)
{
try
{
- if (channel.flushSupported() && !flushWaitGate.await(timeout, TimeUnit.MILLISECONDS))
- {
- throw new TimeoutException("State retrieval timed out waiting for flush to block. (timeout = " + timeout + " millis) ");
- }
+ if (!coordinationLock.writeLock().tryLock(configuration.getStateRetrievalTimeout(), TimeUnit.MILLISECONDS))
+ throw new TimeoutException("Could not obtain processing lock");
+
return;
}
catch (InterruptedException e)
@@ -274,6 +286,13 @@
}
}
}
+
+ public void unlockSuspendProcessingLock()
+ {
+ if (coordinationLock.isWriteLockedByCurrentThread())
+ coordinationLock.writeLock().unlock();
+ }
+
}
// ------------ START: Lifecycle methods ------------
@@ -302,6 +321,7 @@
boolean fetchState = shouldFetchStateOnStartup();
boolean nonBlocking = configuration.isNonBlockingStateTransfer();
+ this.flushTracker = nonBlocking ? new NonBlockingFlushTracker() : new StandardFlushTracker();
initialiseChannelAndRpcDispatcher(fetchState && !nonBlocking);
if (!fetchState || nonBlocking)
15 years, 10 months