JBoss Cache SVN: r7609 - in core/branches/flat/src: main/java/org/horizon/tree and 1 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2009-01-28 19:04:52 -0500 (Wed, 28 Jan 2009)
New Revision: 7609
Modified:
core/branches/flat/src/main/java/org/horizon/lock/StripedLockManager.java
core/branches/flat/src/main/java/org/horizon/tree/NodeImpl.java
core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java
Log:
Modified: core/branches/flat/src/main/java/org/horizon/lock/StripedLockManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/lock/StripedLockManager.java 2009-01-28 23:43:56 UTC (rev 7608)
+++ core/branches/flat/src/main/java/org/horizon/lock/StripedLockManager.java 2009-01-29 00:04:52 UTC (rev 7609)
@@ -40,14 +40,13 @@
import java.util.concurrent.locks.Lock;
/**
- * // TODO: MANIK: Document this
+ * Handles locks for the MVCC based LockingInterceptor
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
* @since 1.0
*/
public class StripedLockManager implements LockManager {
protected Configuration configuration;
- protected long lockAcquisitionTimeout;
LockContainer<Object> lockContainer;
private TransactionManager transactionManager;
private InvocationContextContainer invocationContextContainer;
@@ -63,7 +62,6 @@
@Start
public void startLockManager() {
- this.lockAcquisitionTimeout = configuration.getLockAcquisitionTimeout();
lockContainer = transactionManager == null ? new ReentrantLockContainer<Object>(configuration.getConcurrencyLevel()) : new OwnableReentrantLockContainer<Object>(configuration.getConcurrencyLevel(), invocationContextContainer);
}
@@ -74,7 +72,7 @@
public boolean lock(Object key, Object owner) throws InterruptedException {
if (trace) log.trace("Attempting to lock " + key);
Lock lock = lockContainer.getLock(key);
- return lock.tryLock(lockAcquisitionTimeout, MILLISECONDS);
+ return lock.tryLock(configuration.getLockAcquisitionTimeout(), MILLISECONDS);
}
public boolean lock(Object key, Object owner, long timeoutMillis) throws InterruptedException {
@@ -86,7 +84,7 @@
public boolean lockAndRecord(Object key, InvocationContext ctx) throws InterruptedException {
if (trace) log.trace("Attempting to lock " + key);
Lock lock = lockContainer.getLock(key);
- if (lock.tryLock(ctx.getLockAcquisitionTimeout(lockAcquisitionTimeout), MILLISECONDS)) {
+ if (lock.tryLock(ctx.getLockAcquisitionTimeout(configuration.getLockAcquisitionTimeout()), MILLISECONDS)) {
ctx.addKeyLocked(key);
return true;
}
Modified: core/branches/flat/src/main/java/org/horizon/tree/NodeImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/NodeImpl.java 2009-01-28 23:43:56 UTC (rev 7608)
+++ core/branches/flat/src/main/java/org/horizon/tree/NodeImpl.java 2009-01-29 00:04:52 UTC (rev 7609)
@@ -121,9 +121,9 @@
if (childFqn != null) {
Node child = new NodeImpl(childFqn, cache);
child.removeChildren();
+ child.clearData(); // this is necessary in case we have a remove and then an add on the same node, in the same tx.
cache.remove(new NodeKey(childFqn, NodeKey.Type.DATA));
cache.remove(new NodeKey(childFqn, NodeKey.Type.STRUCTURE));
-// updateStructure(s);
return true;
}
Modified: core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java 2009-01-28 23:43:56 UTC (rev 7608)
+++ core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java 2009-01-29 00:04:52 UTC (rev 7609)
@@ -49,12 +49,8 @@
}
}, 0);
- cache1.getConfiguration().setSyncReplTimeout(1); // 1ms. this is *bound* to fail.
+ cache1.getConfiguration().setSyncReplTimeout(1);
cache2.getConfiguration().setSyncReplTimeout(1);
-
- cache1.start();
- cache2.start();
-
TestingUtil.blockUntilViewsReceived(10000, cache1, cache2);
cache1.put("k", "v");
@@ -63,10 +59,6 @@
@Test(groups = "functional", expectedExceptions = {TimeoutException.class})
public void testLockAcquisitionTimeout() throws Exception {
cache2.getConfiguration().setLockAcquisitionTimeout(1);
-
- cache1.start();
- cache2.start();
-
TestingUtil.blockUntilViewsReceived(10000, cache1, cache2);
// get a lock on cache 2 and hold on to it.
15 years, 11 months
JBoss Cache SVN: r7608 - in core/branches/flat/src: main/java/org/horizon/remoting and 6 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2009-01-28 18:43:56 -0500 (Wed, 28 Jan 2009)
New Revision: 7608
Added:
core/branches/flat/src/test/java/org/horizon/atomic/AtomicHashMapTestAssertions.java
core/branches/flat/src/test/java/org/horizon/atomic/ClusteredAPITest.java
Modified:
core/branches/flat/src/main/java/org/horizon/batch/BatchContainer.java
core/branches/flat/src/main/java/org/horizon/remoting/RPCManagerImpl.java
core/branches/flat/src/main/java/org/horizon/remoting/transport/jgroups/JGroupsTransport.java
core/branches/flat/src/test/java/org/horizon/BaseClusteredTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java
core/branches/flat/src/test/java/org/horizon/atomic/APITest.java
core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java
core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.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
Log:
Modified: core/branches/flat/src/main/java/org/horizon/batch/BatchContainer.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/batch/BatchContainer.java 2009-01-28 18:27:32 UTC (rev 7607)
+++ core/branches/flat/src/main/java/org/horizon/batch/BatchContainer.java 2009-01-28 23:43:56 UTC (rev 7608)
@@ -61,9 +61,9 @@
public boolean startBatch(boolean autoBatch) throws CacheException {
BatchDetails bd = batchDetails.get();
try {
- bd.invocationCount++;
if (transactionManager.getTransaction() == null && bd.tx == null) {
transactionManager.begin();
+ bd.invocationCount = 1;
bd.suspendTxAfterInvocation = !autoBatch;
// do not suspend if this is from an AutoBatch!
@@ -73,8 +73,10 @@
bd.tx = transactionManager.suspend();
return true;
- }
- return false;
+ } else {
+ bd.invocationCount++;
+ return false;
+ }
}
catch (Exception e) {
throw new CacheException("Unable to start batch", e);
Modified: core/branches/flat/src/main/java/org/horizon/remoting/RPCManagerImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/RPCManagerImpl.java 2009-01-28 18:27:32 UTC (rev 7607)
+++ core/branches/flat/src/main/java/org/horizon/remoting/RPCManagerImpl.java 2009-01-28 23:43:56 UTC (rev 7608)
@@ -121,7 +121,7 @@
}
// mainly for unit testing
- public void setTransport(Transport transport) {
- this.t = transport;
+ public void setTransport(Transport t) {
+ this.t = t;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/remoting/transport/jgroups/JGroupsTransport.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/transport/jgroups/JGroupsTransport.java 2009-01-28 18:27:32 UTC (rev 7607)
+++ core/branches/flat/src/main/java/org/horizon/remoting/transport/jgroups/JGroupsTransport.java 2009-01-28 23:43:56 UTC (rev 7608)
@@ -289,7 +289,7 @@
boolean needNotification = false;
if (newMembers != null) {
- // TODO: Implement breaking stale locks for dead members
+ // TODO: Implement breaking stale locks for dead members. This should be in the TxINterceptor or TransactionTable, with a listener on the cache manager.
// if (members != null) {
// we had a membership list before this event. Check to make sure we haven't lost any members,
// and if so, determine what members have been removed
Modified: core/branches/flat/src/test/java/org/horizon/BaseClusteredTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/BaseClusteredTest.java 2009-01-28 18:27:32 UTC (rev 7607)
+++ core/branches/flat/src/test/java/org/horizon/BaseClusteredTest.java 2009-01-28 23:43:56 UTC (rev 7608)
@@ -18,6 +18,7 @@
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
+import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -64,6 +65,16 @@
}
}
+ 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 = addCacheManager();
+ 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;
@@ -115,7 +126,7 @@
}
public void waitForReplication() {
- waitForReplication(600, TimeUnit.SECONDS);
+ waitForReplication(120, TimeUnit.SECONDS);
}
public void waitForReplication(long time, TimeUnit unit) {
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-01-28 18:27:32 UTC (rev 7607)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java 2009-01-28 23:43:56 UTC (rev 7608)
@@ -8,11 +8,13 @@
import org.horizon.commands.write.PutKeyValueCommand;
import org.horizon.commands.write.RemoveCommand;
import org.horizon.config.Configuration;
-import org.horizon.factories.ComponentRegistry;
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.transaction.DummyTransactionManagerLookup;
import org.horizon.transaction.TransactionTable;
import org.horizon.util.TestingUtil;
@@ -22,6 +24,7 @@
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
+import java.util.ArrayList;
import java.util.List;
@Test(groups = "functional", sequential = true)
@@ -90,28 +93,34 @@
}
public void testAsyncForce() throws Exception {
- RPCManager rpcManager = EasyMock.createNiceMock(RPCManager.class);
- RPCManager originalRpcManager = cache1.getConfiguration().getRuntimeConfig().getRPCManager();
- List<Address> memberList = originalRpcManager.getMembers();
- expect(rpcManager.getMembers()).andReturn(memberList).anyTimes();
- // inject a mock RPC manager so that we can test whether calls made are sync or async.
- ComponentRegistry cr = TestingUtil.extractComponentRegistry(cache1);
- cr.registerComponent(rpcManager, RPCManager.class);
- cr.rewire();
+ Transport mockTransport = createNiceMock(Transport.class);
+ RPCManagerImpl rpcManager = (RPCManagerImpl) TestingUtil.extractComponent(cache1, RPCManager.class);
+ Transport originalTransport = TestingUtil.extractComponent(cache1, Transport.class);
+ try {
- // specify what we expectWithTx called on the mock Rpc Manager. For params we don't care about, just use ANYTHING.
- // setting the mock object to expectWithTx the "sync" param to be false.
- expect(rpcManager.invokeRemotely(anyAddresses(), (RPCCommand) anyObject(), eq(ResponseMode.ASYNCHRONOUS), anyLong(), anyBoolean())).andReturn(null);
+ Address mockAddress1 = createNiceMock(Address.class);
+ Address mockAddress2 = createNiceMock(Address.class);
- replay(rpcManager);
+ List<Address> memberList = new ArrayList<Address>(2);
+ memberList.add(mockAddress1);
+ memberList.add(mockAddress2);
- // now try a simple replication. Since the RPCManager is a mock object it will not actually replicate anything.
- cache1.putForExternalRead(key, value);
- verify(rpcManager);
+ expect(mockTransport.getMembers()).andReturn(memberList).anyTimes();
+ rpcManager.setTransport(mockTransport);
+ // specify what we expectWithTx called on the mock Rpc Manager. For params we don't care about, just use ANYTHING.
+ // setting the mock object to expectWithTx the "sync" param to be false.
+ expect(mockTransport.invokeRemotely((List<Address>) anyObject(), (RPCCommand) anyObject(),
+ eq(ResponseMode.ASYNCHRONOUS), anyLong(), anyBoolean(), (ResponseFilter) isNull())).andReturn(null);
- // cleanup
- TestingUtil.extractComponentRegistry(cache1).registerComponent(originalRpcManager, RPCManager.class);
- cache1.remove(key);
+ replay(mockAddress1, mockAddress2, mockTransport);
+
+ // now try a simple replication. Since the RPCManager is a mock object it will not actually replicate anything.
+ cache1.putForExternalRead(key, value);
+ verify(mockTransport);
+
+ } finally {
+ if (rpcManager != null) rpcManager.setTransport(originalTransport);
+ }
}
public void testTxSuspension() throws Exception {
@@ -139,19 +148,28 @@
}
public void testExceptionSuppression() throws Exception {
- RPCManager barfingRpcManager = EasyMock.createNiceMock(RPCManager.class);
- RPCManager originalRpcManager = cache1.getConfiguration().getRuntimeConfig().getRPCManager();
+ Transport mockTransport = createNiceMock(Transport.class);
+ RPCManagerImpl rpcManager = (RPCManagerImpl) TestingUtil.extractComponent(cache1, RPCManager.class);
+ Transport originalTransport = TestingUtil.extractComponent(cache1, Transport.class);
try {
- List<Address> memberList = originalRpcManager.getMembers();
- expect(barfingRpcManager.getMembers()).andReturn(memberList).anyTimes();
- expect(barfingRpcManager.getAddress()).andReturn(originalRpcManager.getAddress()).anyTimes();
- expect(barfingRpcManager.invokeRemotely(anyAddresses(), (RPCCommand) anyObject(), anyResponseMode(), anyLong(), anyBoolean())).andThrow(new RuntimeException("Barf!")).anyTimes();
- replay(barfingRpcManager);
- TestingUtil.extractComponentRegistry(cache1).registerComponent(barfingRpcManager, RPCManager.class);
- cache1.getConfiguration().getRuntimeConfig().setRPCManager(barfingRpcManager);
- TestingUtil.extractComponentRegistry(cache1).rewire();
+ Address mockAddress1 = createNiceMock(Address.class);
+ Address mockAddress2 = createNiceMock(Address.class);
+ List<Address> memberList = new ArrayList<Address>(2);
+ memberList.add(mockAddress1);
+ memberList.add(mockAddress2);
+
+ expect(mockTransport.getMembers()).andReturn(memberList).anyTimes();
+ rpcManager.setTransport(mockTransport);
+
+
+ expect(mockTransport.invokeRemotely(anyAddresses(), (RPCCommand) anyObject(), anyResponseMode(),
+ anyLong(), anyBoolean(), (ResponseFilter) anyObject()))
+ .andThrow(new RuntimeException("Barf!")).anyTimes();
+
+ replay(mockTransport);
+
try {
cache1.put(key, value);
fail("Should have barfed");
@@ -173,7 +191,7 @@
cache1.putForExternalRead(key, value);
}
finally {
- TestingUtil.extractComponentRegistry(cache1).registerComponent(originalRpcManager, RPCManager.class);
+ if (rpcManager != null) rpcManager.setTransport(originalTransport);
}
}
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-01-28 18:27:32 UTC (rev 7607)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java 2009-01-28 23:43:56 UTC (rev 7608)
@@ -3,7 +3,6 @@
import org.horizon.config.Configuration;
import org.horizon.manager.CacheManager;
import org.horizon.manager.DefaultCacheManager;
-import org.horizon.transaction.DummyTransactionManager;
import org.horizon.transaction.DummyTransactionManagerLookup;
import org.horizon.tree.Fqn;
import org.horizon.tree.Node;
@@ -11,6 +10,7 @@
import org.horizon.tree.TreeCacheImpl;
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;
@@ -44,6 +44,11 @@
tm = TestingUtil.getTransactionManager(cache.getCache());
}
+ @AfterMethod
+ public void tearDown() {
+ TestingUtil.killCaches(cache.getCache());
+ }
+
public void testAddingData() {
Node<Object, Object> rootNode = cache.getRoot();
Node<Object, Object> nodeA = rootNode.addChild(A);
@@ -322,11 +327,9 @@
}
public void testDoubleRemovalOfData() throws Exception {
-
-
- assert DummyTransactionManager.getInstance().getTransaction() == null;
+ assert tm.getTransaction() == null;
cache.put("/foo/1/2/3", "item", 1);
- assert DummyTransactionManager.getInstance().getTransaction() == null;
+ assert tm.getTransaction() == null;
assert 1 == (Integer) cache.get("/foo/1/2/3", "item");
tm.begin();
assert 1 == (Integer) cache.get("/foo/1/2/3", "item");
Modified: core/branches/flat/src/test/java/org/horizon/atomic/APITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/atomic/APITest.java 2009-01-28 18:27:32 UTC (rev 7607)
+++ core/branches/flat/src/test/java/org/horizon/atomic/APITest.java 2009-01-28 23:43:56 UTC (rev 7608)
@@ -21,213 +21,144 @@
*/
package org.horizon.atomic;
+import static org.horizon.atomic.AtomicHashMapTestAssertions.assertIsEmpty;
+import static org.horizon.atomic.AtomicHashMapTestAssertions.assertIsEmptyMap;
import org.horizon.config.Configuration;
-import org.horizon.config.Configuration.CacheMode;
import org.horizon.manager.DefaultCacheManager;
-import org.horizon.transaction.DummyTransactionManager;
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.SystemException;
import javax.transaction.Transaction;
-import java.util.Map;
+import javax.transaction.TransactionManager;
-@Test(groups = "functional")
+@Test(groups = "functional", sequential = true)
public class APITest {
- private void assertIsEmpty(Map map) {
- assert map.size() == 0;
- assert map.get("blah") == null;
- assert !map.containsKey("blah");
+ AtomicMapCache cache;
+ TransactionManager tm;
+
+ @BeforeTest
+ private void setUp() {
+ Configuration c = new Configuration();
+ c.setInvocationBatchingEnabled(true);
+ c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ cache = (AtomicMapCache) new DefaultCacheManager(c).getCache();
+ tm = TestingUtil.getTransactionManager(cache);
}
- private void assertIsEmptyMap(AtomicMapCache cache, Object key) {
- assertIsEmpty(cache.getAtomicMap(key));
+ @AfterTest
+ private void tearDown() {
+ cache.getCacheManager().stop();
}
+ @AfterMethod
+ private void clearUp() throws SystemException {
+ if (tm.getTransaction() != null) {
+ try {
+ tm.rollback();
+ } catch (Exception ignored) {
+ // try to suspend?
+ tm.suspend();
+ }
+ }
+ cache.clear();
+ }
+
public void testAtomicMap() {
- Configuration c = new Configuration();
- c.setInvocationBatchingEnabled(true);
- AtomicMapCache cache = (AtomicMapCache) new DefaultCacheManager(c).getCache();
- try {
- AtomicMap map = cache.getAtomicMap("map");
+ AtomicMap map = cache.getAtomicMap("map");
- assertIsEmpty(map);
- assertIsEmptyMap(cache, "map");
+ assertIsEmpty(map);
+ assertIsEmptyMap(cache, "map");
- map.put("blah", "blah");
- assert map.size() == 1;
- assert map.get("blah").equals("blah");
- assert map.containsKey("blah");
+ map.put("blah", "blah");
+ assert map.size() == 1;
+ assert map.get("blah").equals("blah");
+ assert map.containsKey("blah");
- map.clear();
+ map.clear();
- assertIsEmpty(map);
- assertIsEmptyMap(cache, "map");
- }
- finally {
- cache.stop();
- }
+ assertIsEmpty(map);
+ assertIsEmptyMap(cache, "map");
}
public void testReadSafetyEmptyCache() throws Exception {
- Configuration c = new Configuration();
- c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- c.setInvocationBatchingEnabled(true);
- AtomicMapCache cache = (AtomicMapCache) new DefaultCacheManager(c).getCache();
- try {
- AtomicMap map = cache.getAtomicMap("map");
+ AtomicMap map = cache.getAtomicMap("map");
- assertIsEmpty(map);
- assertIsEmptyMap(cache, "map");
+ assertIsEmpty(map);
+ assertIsEmptyMap(cache, "map");
- DummyTransactionManager.getInstance().begin();
- map.put("blah", "blah");
- assert map.size() == 1;
- assert map.get("blah").equals("blah");
- assert map.containsKey("blah");
- Transaction t = DummyTransactionManager.getInstance().suspend();
+ tm.begin();
+ map.put("blah", "blah");
+ assert map.size() == 1;
+ assert map.get("blah").equals("blah");
+ assert map.containsKey("blah");
+ Transaction t = tm.suspend();
- assertIsEmpty(map);
- assertIsEmptyMap(cache, "map");
+ assertIsEmpty(map);
+ assertIsEmptyMap(cache, "map");
- DummyTransactionManager.getInstance().resume(t);
- DummyTransactionManager.getInstance().commit();
+ tm.resume(t);
+ tm.commit();
- assert map.size() == 1;
- assert map.get("blah").equals("blah");
- assert map.containsKey("blah");
+ assert map.size() == 1;
+ assert map.get("blah").equals("blah");
+ assert map.containsKey("blah");
- map.clear();
+ map.clear();
- assertIsEmpty(map);
- assertIsEmptyMap(cache, "map");
- }
- finally {
- cache.stop();
- }
+ assertIsEmpty(map);
+ assertIsEmptyMap(cache, "map");
}
public void testReadSafetyNotEmptyCache() throws Exception {
- Configuration c = new Configuration();
- c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- c.setInvocationBatchingEnabled(true);
- AtomicMapCache cache = (AtomicMapCache) new DefaultCacheManager(c).getCache();
- try {
- AtomicMap map = cache.getAtomicMap("map");
+ AtomicMap map = cache.getAtomicMap("map");
- DummyTransactionManager.getInstance().begin();
- map.put("blah", "blah");
- assert map.size() == 1;
- assert map.get("blah").equals("blah");
- assert map.containsKey("blah");
- Transaction t = DummyTransactionManager.getInstance().suspend();
+ tm.begin();
+ map.put("blah", "blah");
+ assert map.size() == 1;
+ assert map.get("blah").equals("blah");
+ assert map.containsKey("blah");
+ Transaction t = tm.suspend();
- assertIsEmpty(map);
- assertIsEmptyMap(cache, "map");
+ assertIsEmpty(map);
+ assertIsEmptyMap(cache, "map");
- DummyTransactionManager.getInstance().resume(t);
- DummyTransactionManager.getInstance().commit();
+ tm.resume(t);
+ tm.commit();
- assert map.size() == 1;
- assert map.get("blah").equals("blah");
- assert map.containsKey("blah");
+ assert map.size() == 1;
+ assert map.get("blah").equals("blah");
+ assert map.containsKey("blah");
- map.clear();
+ map.clear();
- assertIsEmpty(map);
- assertIsEmptyMap(cache, "map");
- }
- finally {
- cache.stop();
- }
+ assertIsEmpty(map);
+ assertIsEmptyMap(cache, "map");
}
public void testReadSafetyRollback() throws Exception {
- Configuration c = new Configuration();
- c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- c.setInvocationBatchingEnabled(true);
- AtomicMapCache cache = (AtomicMapCache) new DefaultCacheManager(c).getCache();
- try {
- AtomicMap map = cache.getAtomicMap("map");
+ AtomicMap map = cache.getAtomicMap("map");
- DummyTransactionManager.getInstance().begin();
- map.put("blah", "blah");
- assert map.size() == 1;
- assert map.get("blah").equals("blah");
- assert map.containsKey("blah");
- Transaction t = DummyTransactionManager.getInstance().suspend();
+ tm.begin();
+ map.put("blah", "blah");
+ assert map.size() == 1;
+ assert map.get("blah").equals("blah");
+ assert map.containsKey("blah");
+ Transaction t = tm.suspend();
- assertIsEmpty(map);
- assertIsEmptyMap(cache, "map");
+ assertIsEmpty(map);
+ assertIsEmptyMap(cache, "map");
- DummyTransactionManager.getInstance().resume(t);
- DummyTransactionManager.getInstance().rollback();
+ tm.resume(t);
+ tm.rollback();
- assertIsEmpty(map);
- assertIsEmptyMap(cache, "map");
- }
- finally {
- cache.stop();
- }
+ assertIsEmpty(map);
+ assertIsEmptyMap(cache, "map");
}
-
- public void testReplicationCommit() throws Exception {
- Configuration c = new Configuration();
- c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- c.setCacheMode(CacheMode.REPL_SYNC);
- c.setInvocationBatchingEnabled(true);
- AtomicMapCache cache1 = (AtomicMapCache) new DefaultCacheManager(c).getCache();
- AtomicMapCache cache2 = (AtomicMapCache) new DefaultCacheManager(c).getCache();
-
- try {
- TestingUtil.blockUntilViewsReceived(20000, cache1, cache2);
- AtomicMap map = cache1.getAtomicMap("map");
-
- DummyTransactionManager.getInstance().begin();
- map.put("existing", "existing");
- map.put("blah", "blah");
- DummyTransactionManager.getInstance().commit();
-
- assert map.size() == 2;
- assert map.get("blah").equals("blah");
- assert map.containsKey("blah");
-
- System.out.println("Map on cache 2 is " + cache2.getAtomicMap("map"));
-
- assert cache2.getAtomicMap("map").size() == 2;
- assert cache2.getAtomicMap("map").get("blah").equals("blah");
- assert cache2.getAtomicMap("map").containsKey("blah");
- }
- finally {
- TestingUtil.killCaches(cache1, cache2);
- }
- }
-
- public void testReplicationRollback() throws Exception {
- Configuration c = new Configuration();
- c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- c.setCacheMode(CacheMode.REPL_SYNC);
- c.setInvocationBatchingEnabled(true);
- AtomicMapCache cache1 = (AtomicMapCache) new DefaultCacheManager(c).getCache();
- AtomicMapCache cache2 = (AtomicMapCache) new DefaultCacheManager(c).getCache();
-
- try {
- TestingUtil.blockUntilViewsReceived(20000, cache1, cache2);
- AtomicMap map = cache1.getAtomicMap("map");
-
- DummyTransactionManager.getInstance().begin();
- map.put("existing", "existing");
- map.put("blah", "blah");
- DummyTransactionManager.getInstance().rollback();
-
- assertIsEmpty(map);
- assertIsEmptyMap(cache1, "map");
- assertIsEmptyMap(cache2, "map");
- }
- finally {
- TestingUtil.killCaches(cache1, cache2);
- }
- }
}
Added: core/branches/flat/src/test/java/org/horizon/atomic/AtomicHashMapTestAssertions.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/atomic/AtomicHashMapTestAssertions.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/atomic/AtomicHashMapTestAssertions.java 2009-01-28 23:43:56 UTC (rev 7608)
@@ -0,0 +1,16 @@
+package org.horizon.atomic;
+
+import java.util.Map;
+
+public class AtomicHashMapTestAssertions {
+
+ public static void assertIsEmpty(Map map) {
+ assert map.size() == 0;
+ assert map.get("blah") == null;
+ assert !map.containsKey("blah");
+ }
+
+ public static void assertIsEmptyMap(AtomicMapCache cache, Object key) {
+ assertIsEmpty(cache.getAtomicMap(key));
+ }
+}
Added: core/branches/flat/src/test/java/org/horizon/atomic/ClusteredAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/atomic/ClusteredAPITest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/atomic/ClusteredAPITest.java 2009-01-28 23:43:56 UTC (rev 7608)
@@ -0,0 +1,65 @@
+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.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 {
+ AtomicMapCache cache1, cache2;
+
+ @BeforeMethod
+ public void setUp() {
+ Configuration c = new Configuration();
+ c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
+ c.setInvocationBatchingEnabled(true);
+
+ 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 {
+ AtomicMap map = cache1.getAtomicMap("map");
+
+ DummyTransactionManager.getInstance().begin();
+ map.put("existing", "existing");
+ map.put("blah", "blah");
+ DummyTransactionManager.getInstance().commit();
+
+ assert map.size() == 2;
+ assert map.get("blah").equals("blah");
+ assert map.containsKey("blah");
+
+ System.out.println("Map on cache 2 is " + cache2.getAtomicMap("map"));
+
+ assert cache2.getAtomicMap("map").size() == 2;
+ assert cache2.getAtomicMap("map").get("blah").equals("blah");
+ assert cache2.getAtomicMap("map").containsKey("blah");
+ }
+
+ public void testReplicationRollback() throws Exception {
+ AtomicMap map = cache1.getAtomicMap("map");
+
+ DummyTransactionManager.getInstance().begin();
+ map.put("existing", "existing");
+ map.put("blah", "blah");
+ DummyTransactionManager.getInstance().rollback();
+
+ assertIsEmpty(map);
+ assertIsEmptyMap(cache1, "map");
+ assertIsEmptyMap(cache2, "map");
+ }
+}
Modified: core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java 2009-01-28 18:27:32 UTC (rev 7607)
+++ core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java 2009-01-28 23:43:56 UTC (rev 7608)
@@ -11,7 +11,6 @@
import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.config.Configuration;
-import org.horizon.manager.CacheManager;
import org.horizon.transaction.DummyTransactionManagerLookup;
import org.horizon.util.TestingUtil;
import static org.testng.AssertJUnit.assertEquals;
@@ -19,6 +18,7 @@
import org.testng.annotations.Test;
import javax.transaction.TransactionManager;
+import java.util.List;
import java.util.concurrent.TimeUnit;
/**
@@ -37,13 +37,10 @@
asyncConfiguration.setSyncRollbackPhase(true);
asyncConfiguration.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- CacheManager cm1 = addCacheManager();
- CacheManager cm2 = addCacheManager();
+ List<Cache> caches = createClusteredCaches(2, "asyncRepl", asyncConfiguration);
- defineCacheOnAllManagers("asyncRepl", asyncConfiguration);
-
- cache1 = cm1.getCache("asyncRepl");
- cache2 = cm2.getCache("asyncRepl");
+ cache1 = caches.get(0);
+ cache2 = caches.get(1);
}
public void testWithNoTx() throws Exception {
Modified: core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java 2009-01-28 18:27:32 UTC (rev 7607)
+++ core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java 2009-01-28 23:43:56 UTC (rev 7608)
@@ -1,66 +1,53 @@
package org.horizon.replication;
+import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
-import org.horizon.UnitTestCacheManager;
+import org.horizon.commands.VisitableCommand;
import org.horizon.config.Configuration;
+import org.horizon.context.InvocationContext;
+import org.horizon.interceptors.base.CommandInterceptor;
import org.horizon.lock.TimeoutException;
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;
-import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
+import java.util.List;
/**
* Tests the type of exceptions thrown for Lock Acquisition Timeouts versus Sync Repl Timeouts
*
* @author <a href="mailto:manik@jboss.org">Manik Surtani</a>
*/
-@Test(groups = {"functional"}, sequential = true)
-public class ExceptionTest {
+@Test(groups = "functional", sequential = true)
+public class ExceptionTest extends BaseClusteredTest {
private Cache cache1;
private Cache cache2;
- private static String DELAYED_CLUSTER_CONFIG =
- "UDP(mcast_addr=224.0.0.36;mcast_port=55566;ip_ttl=32;" +
- " mcast_send_buf_size=150000;mcast_recv_buf_size=80000):" +
- "PING(timeout=1000;num_initial_members=2):" +
- "MERGE2(min_interval=5000;max_interval=10000):" +
- "FD_SOCK:" +
- "VERIFY_SUSPECT(timeout=1500):" +
- "pbcast.NAKACK(gc_lag=50;max_xmit_size=8192;retransmit_timeout=600,1200,2400,4800):" +
- "UNICAST(timeout=600,1200,2400,4800):" +
- "pbcast.STABLE(desired_avg_gossip=20000):" +
- "FRAG(frag_size=8192;down_thread=false;up_thread=false):" +
- "pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;" +
- "shun=false;print_local_addr=true):" +
- "pbcast.STATE_TRANSFER:" +
- "DELAY(in_delay=100;out_delay=100)";
-
- private Cache createCache(String jgroupsConfig) {
+ @BeforeMethod
+ public void setUp() {
Configuration c = new Configuration();
c.setSyncCommitPhase(true);
c.setSyncRollbackPhase(true);
c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
- // TODO fix this
-// if (jgroupsConfig != null) c.setClusterConfig(jgroupsConfig);
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- Cache cache = new UnitTestCacheManager(c).createCache("testCache");
- return cache;
- }
- @AfterMethod
- public void tearDown() {
- TestingUtil.killCaches(cache1, cache2);
- cache1 = null;
- cache2 = null;
+ List<Cache> caches = createClusteredCaches(2, "ExceptionTestCache", c);
+ cache1 = caches.get(0);
+ cache2 = caches.get(1);
}
- @Test(groups = {"functional"}, expectedExceptions = {TimeoutException.class})
+ @Test(groups = "functional", expectedExceptions = {TimeoutException.class})
public void testSyncReplTimeout() {
- cache1 = createCache(DELAYED_CLUSTER_CONFIG);
- cache2 = createCache(DELAYED_CLUSTER_CONFIG);
+ cache2.addInterceptor(new CommandInterceptor() {
+ @Override
+ protected Object handleDefault(InvocationContext ctx, VisitableCommand cmd) throws Throwable {
+ // Add a delay
+ Thread.sleep(100);
+ return super.handleDefault(ctx, cmd);
+ }
+ }, 0);
cache1.getConfiguration().setSyncReplTimeout(1); // 1ms. this is *bound* to fail.
cache2.getConfiguration().setSyncReplTimeout(1);
@@ -73,10 +60,8 @@
cache1.put("k", "v");
}
- @Test(groups = {"functional"}, expectedExceptions = {TimeoutException.class})
+ @Test(groups = "functional", expectedExceptions = {TimeoutException.class})
public void testLockAcquisitionTimeout() throws Exception {
- cache1 = createCache(null);
- cache2 = createCache(null);
cache2.getConfiguration().setLockAcquisitionTimeout(1);
cache1.start();
@@ -88,7 +73,7 @@
TransactionManager tm = cache2.getConfiguration().getRuntimeConfig().getTransactionManager();
tm.begin();
cache2.put("block", "block");
- Transaction t = tm.suspend();
+ tm.suspend();
cache1.put("block", "v");
}
}
Modified: core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java 2009-01-28 18:27:32 UTC (rev 7607)
+++ core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java 2009-01-28 23:43:56 UTC (rev 7608)
@@ -7,16 +7,15 @@
*/
package org.horizon.replication;
-import org.horizon.CacheSPI;
-import org.horizon.UnitTestCacheManager;
+import org.horizon.BaseClusteredTest;
+import org.horizon.Cache;
import org.horizon.config.Configuration;
import org.horizon.lock.IsolationLevel;
-import org.horizon.transaction.DummyTransactionManager;
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.AfterMethod;
+import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.transaction.NotSupportedException;
@@ -25,68 +24,36 @@
import javax.transaction.TransactionManager;
import java.io.NotSerializableException;
import java.io.Serializable;
+import java.util.List;
-/**
- * Teting of replication exception for a Nonerislizable object
- *
- * @author Ben Wang
- */
-@Test(groups = {"functional"}, sequential = true)
-public class ReplicationExceptionTest {
- private CacheSPI<String, ContainerData> cache1, cache2;
+@Test(groups = "functional", sequential = true)
+public class ReplicationExceptionTest extends BaseClusteredTest {
+ private Cache<String, ContainerData> cache1, cache2;
- @AfterMethod(alwaysRun = true)
- public void tearDown() throws Exception {
- // We just can't kill DummyTransactionManager. We are sharing single instance in more tests.
- TestingUtil.killTransaction(DummyTransactionManager.getInstance());
- destroyCaches();
- /*
- if (old_factory != null)
- {
- System.setProperty(Context.INITIAL_CONTEXT_FACTORY, old_factory);
- old_factory = null;
- }
- */
- }
+ @BeforeMethod
+ public void setUp() {
+ Configuration configuration = new Configuration();
- private TransactionManager beginTransaction() throws SystemException, NotSupportedException {
- TransactionManager mgr = cache1.getConfiguration().getRuntimeConfig().getTransactionManager();
- mgr.begin();
- return mgr;
- }
+ configuration.setCacheMode(Configuration.CacheMode.REPL_SYNC);
+ configuration.setIsolationLevel(IsolationLevel.REPEATABLE_READ);
- private void initCaches(Configuration.CacheMode cachingMode) {
- Configuration conf1 = new Configuration();
- Configuration conf2 = new Configuration();
+ configuration.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ configuration.setLockAcquisitionTimeout(5000);
- conf1.setCacheMode(cachingMode);
- conf2.setCacheMode(cachingMode);
- conf1.setIsolationLevel(IsolationLevel.SERIALIZABLE);
- conf2.setIsolationLevel(IsolationLevel.SERIALIZABLE);
+ List<Cache> caches = createClusteredCaches(2, "replicatinExceptionTest", configuration);
- conf1.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- conf2.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- conf1.setLockAcquisitionTimeout(5000);
- conf2.setLockAcquisitionTimeout(5000);
-
- cache1 = (CacheSPI) new UnitTestCacheManager(conf1).createCache("testCache");
- cache2 = (CacheSPI) new UnitTestCacheManager(conf2).createCache("testCache");
-
-
- cache1.start();
- cache2.start();
+ cache1 = caches.get(0);
+ cache2 = caches.get(1);
}
- void destroyCaches() throws Exception {
- TestingUtil.killCaches(cache1, cache2);
- cache1 = null;
- cache2 = null;
+ private TransactionManager beginTransaction() throws SystemException, NotSupportedException {
+ TransactionManager mgr = TestingUtil.getTransactionManager(cache1);
+ mgr.begin();
+ return mgr;
}
public void testNonSerializableRepl() throws Exception {
try {
- initCaches(Configuration.CacheMode.REPL_SYNC);
-
cache1.put("test", new ContainerData());
// We should not come here.
@@ -106,8 +73,6 @@
TransactionManager tm;
try {
- initCaches(Configuration.CacheMode.REPL_SYNC);
-
tm = beginTransaction();
cache1.put("test", new ContainerData());
tm.commit();
Modified: core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java 2009-01-28 18:27:32 UTC (rev 7607)
+++ core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java 2009-01-28 23:43:56 UTC (rev 7608)
@@ -7,62 +7,40 @@
*/
package org.horizon.replication;
+import org.horizon.BaseClusteredTest;
+import org.horizon.Cache;
import org.horizon.CacheException;
-import org.horizon.CacheSPI;
-import org.horizon.UnitTestCacheManager;
import org.horizon.config.Configuration;
import org.horizon.lock.IsolationLevel;
import org.horizon.logging.Log;
import org.horizon.logging.LogFactory;
import org.horizon.notifications.annotation.CacheEntryModified;
import org.horizon.notifications.annotation.CacheEntryRemoved;
+import org.horizon.notifications.annotation.Listener;
import org.horizon.notifications.event.Event;
import org.horizon.notifications.event.TransactionalEvent;
-import org.horizon.transaction.DummyTransactionManager;
import org.horizon.transaction.DummyTransactionManagerLookup;
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 javax.transaction.Transaction;
import javax.transaction.TransactionManager;
+import java.util.List;
import java.util.Map;
import java.util.Set;
/**
- * Test out the TreeCacheListener
+ * Test out the CacheListener
*/
-@Test(groups = {"functional"}, sequential = true)
-public class SyncCacheListenerTest {
- private CacheSPI<Object, Object> cache1, cache2;
- private final static Log log_ = LogFactory.getLog(SyncCacheListenerTest.class);
+@Test(groups = "functional", sequential = true)
+public class SyncCacheListenerTest extends BaseClusteredTest {
+ private Cache<Object, Object> cache1, cache2;
+ private final static Log log = LogFactory.getLog(SyncCacheListenerTest.class);
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
- System.out.println("*** starting setUp()");
- initCaches();
- System.out.println("*** finished setUp()");
- }
-
- @AfterMethod(alwaysRun = true)
- public void tearDown() throws Exception {
- System.out.println("*** starting tearDown()");
- // We just can't kill DummyTransactionManager. We are sharing single instance in more tests.
- TestingUtil.killTransaction(DummyTransactionManager.getInstance());
- destroyCaches();
- /*
- if (old_factory != null)
- {
- System.setProperty(Context.INITIAL_CONTEXT_FACTORY, old_factory);
- old_factory = null;
- }
- */
- System.out.println("*** finished tearDown()");
- }
-
- private void initCaches() {
Configuration conf = new Configuration();
conf.setSyncCommitPhase(true);
conf.setCacheMode(Configuration.CacheMode.REPL_SYNC);
@@ -70,25 +48,21 @@
conf.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
conf.setLockAcquisitionTimeout(5000);
- cache1 = (CacheSPI) new UnitTestCacheManager(conf).createCache("firstCache");
- cache2 = (CacheSPI) new UnitTestCacheManager(conf).createCache("firstCache");
- TestingUtil.blockUntilViewReceived(cache2, 2, 1000);
- }
+ List<Cache> caches = createClusteredCaches(2, "cache", conf);
- private void destroyCaches() {
- TestingUtil.killCaches(cache1, cache2);
- cache1 = null;
- cache2 = null;
+ cache1 = caches.get(0);
+ cache2 = caches.get(1);
+ TestingUtil.blockUntilViewsReceived(10000, cache1, cache2);
}
public void testSyncTxRepl() throws Exception {
Integer age;
- TransactionManager tm = cache1.getTransactionManager();
+ TransactionManager tm = TestingUtil.getTransactionManager(cache1);
tm.begin();
Transaction tx = tm.getTransaction();
- Listener lis = new Listener();
- cache1.getNotifier().addListener(lis);
+ LocalListener lis = new LocalListener();
+ cache1.addListener(lis);
lis.put("age", 38);
tm.suspend();
@@ -105,7 +79,7 @@
public void testRemoteCacheListener() throws Exception {
Integer age;
RemoteListener lis = new RemoteListener();
- cache2.getNotifier().addListener(lis);
+ cache2.addListener(lis);
cache1.put("age", 38);
// value on cache2 must be 38
@@ -117,7 +91,7 @@
public void testSyncRepl() throws Exception {
Integer age;
- Listener lis = new Listener();
+ LocalListener lis = new LocalListener();
cache1.addListener(lis);
lis.put("age", 38);
@@ -143,7 +117,7 @@
TransactionManager tm = cache1.getConfiguration().getRuntimeConfig().getTransactionManager();
tm.begin();
Transaction tx = tm.getTransaction();
- Listener lis = new Listener();
+ LocalListener lis = new LocalListener();
cache1.put("age", 38);
lis.put("name", "Ben");
@@ -167,8 +141,8 @@
public void testSyncReplMap() throws Exception {
Integer age;
- Listener lis = new Listener();
- cache1.getNotifier().addListener(lis);
+ LocalListener lis = new LocalListener();
+ cache1.addListener(lis);
lis.put("age", 38);
cache1.put("name", "Ben");
@@ -178,8 +152,8 @@
assertTrue("\"age\" must be 38", age == 38);
}
- @org.horizon.notifications.annotation.Listener
- public class Listener {
+ @Listener
+ public class LocalListener {
Object key = null;
public void put(Object key, Object val) {
@@ -198,7 +172,7 @@
@CacheEntryModified
public void nodeModified(Event ne) {
if (!ne.isPre()) {
- log_.debug("nodeModified visited with fqn: " + key);
+ log.debug("nodeModified visited with fqn: " + key);
try {
// test out if we can get the read lock since there is a write lock going as well.
cache1.get(key);
@@ -212,14 +186,14 @@
}
- @org.horizon.notifications.annotation.Listener
+ @Listener
public class RemoteListener {
@CacheEntryRemoved
@CacheEntryModified
public void callback(TransactionalEvent e) {
System.out.println("Callback got event " + e);
- log_.debug("Callback got event " + e);
+ log.debug("Callback got event " + e);
assertFalse("node was removed on remote cache so isLocal should be false", e.isOriginLocal());
}
}
Modified: core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java 2009-01-28 18:27:32 UTC (rev 7607)
+++ core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java 2009-01-28 23:43:56 UTC (rev 7608)
@@ -44,8 +44,7 @@
Configuration replSync = new Configuration();
replSync.setCacheMode(Configuration.CacheMode.REPL_SYNC);
- cm1.defineCache("replSync", replSync);
- cm2.defineCache("replSync", replSync);
+ defineCacheOnAllManagers("replSync", replSync);
cache1 = cm1.getCache("replSync");
cache2 = cm2.getCache("replSync");
15 years, 11 months
JBoss Cache SVN: r7607 - core/branches/flat/src/main/java/org/horizon/remoting/transport/jgroups.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2009-01-28 13:27:32 -0500 (Wed, 28 Jan 2009)
New Revision: 7607
Modified:
core/branches/flat/src/main/java/org/horizon/remoting/transport/jgroups/CommandAwareRpcDispatcher.java
core/branches/flat/src/main/java/org/horizon/remoting/transport/jgroups/JGroupsTransport.java
Log:
Modified: core/branches/flat/src/main/java/org/horizon/remoting/transport/jgroups/CommandAwareRpcDispatcher.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/transport/jgroups/CommandAwareRpcDispatcher.java 2009-01-28 18:26:32 UTC (rev 7606)
+++ core/branches/flat/src/main/java/org/horizon/remoting/transport/jgroups/CommandAwareRpcDispatcher.java 2009-01-28 18:27:32 UTC (rev 7607)
@@ -22,6 +22,7 @@
package org.horizon.remoting.transport.jgroups;
import org.horizon.CacheException;
+import org.horizon.commands.RPCCommand;
import org.horizon.commands.ReplicableCommand;
import org.horizon.logging.Log;
import org.horizon.logging.LogFactory;
@@ -117,7 +118,7 @@
public Object handle(Message req) {
if (isValid(req)) {
try {
- return executeCommand((ReplicableCommand) req_marshaller.objectFromByteBuffer(req.getBuffer(), req.getOffset(), req.getLength()), req);
+ return executeCommand((RPCCommand) req_marshaller.objectFromByteBuffer(req.getBuffer(), req.getOffset(), req.getLength()), req);
}
catch (Throwable x) {
if (trace) log.trace("Problems invoking command.", x);
@@ -128,7 +129,7 @@
}
}
- protected Object executeCommand(ReplicableCommand cmd, Message req) throws Throwable {
+ protected Object executeCommand(RPCCommand cmd, Message req) throws Throwable {
if (cmd == null) throw new NullPointerException("Unable to execute a null command! Message was " + req);
if (trace) log.trace("Executing command: {0} [sender={1}]", cmd, req.getSrc());
return inboundInvocationHandler.handle(cmd);
Modified: core/branches/flat/src/main/java/org/horizon/remoting/transport/jgroups/JGroupsTransport.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/transport/jgroups/JGroupsTransport.java 2009-01-28 18:26:32 UTC (rev 7606)
+++ core/branches/flat/src/main/java/org/horizon/remoting/transport/jgroups/JGroupsTransport.java 2009-01-28 18:27:32 UTC (rev 7607)
@@ -1,7 +1,7 @@
package org.horizon.remoting.transport.jgroups;
import org.horizon.CacheException;
-import org.horizon.commands.ReplicableCommand;
+import org.horizon.commands.RPCCommand;
import org.horizon.config.GlobalConfiguration;
import org.horizon.config.parsing.XmlConfigHelper;
import org.horizon.lock.TimeoutException;
@@ -216,7 +216,7 @@
// outbound RPC
// ------------------------------------------------------------------------------------------------------------------
- public List<Object> invokeRemotely(List<Address> recipients, ReplicableCommand cacheCommand, ResponseMode mode, long timeout, boolean usePriorityQueue, ResponseFilter responseFilter)
+ public List<Object> invokeRemotely(List<Address> recipients, RPCCommand rpcCommand, ResponseMode mode, long timeout, boolean usePriorityQueue, ResponseFilter responseFilter)
throws Exception {
if (recipients != null && recipients.isEmpty()) {
@@ -225,16 +225,16 @@
return Collections.emptyList();
}
- log.trace("dests={0}, command={1}, mode={2}, timeout={3}", recipients, cacheCommand, mode, timeout);
+ log.trace("dests={0}, command={1}, mode={2}, timeout={3}", recipients, rpcCommand, mode, timeout);
- RspList rsps = dispatcher.invokeRemoteCommands(toJGroupsAddressVector(recipients), cacheCommand, toJGroupsMode(mode),
+ RspList rsps = dispatcher.invokeRemoteCommands(toJGroupsAddressVector(recipients), rpcCommand, toJGroupsMode(mode),
timeout, false, usePriorityQueue,
toJGroupsFilter(responseFilter));
if (mode == ResponseMode.ASYNCHRONOUS) return Collections.emptyList();// async case
if (trace)
- log.trace("Cache [{0}]: responses for command {1}:\n{2}", getAddress(), cacheCommand.getClass().getSimpleName(), rsps);
+ log.trace("Cache [{0}]: responses for command {1}:\n{2}", getAddress(), rpcCommand.getClass().getSimpleName(), rsps);
// short-circuit no-return-value calls.
if (rsps == null) return Collections.emptyList();
@@ -308,9 +308,8 @@
members = fromJGroupsAddressList(newMembers);
needNotification = true;
}
-
// Now that we have a view, figure out if we are the coordinator
- coordinator = (members != null && members.size() != 0 && members.get(0).equals(address));
+ coordinator = (members != null && members.size() != 0 && members.get(0).equals(getAddress()));
// now notify listeners - *after* updating the coordinator. - JBCACHE-662
if (needNotification && notifier != null) {
15 years, 11 months
JBoss Cache SVN: r7606 - in core/branches/flat/src: main/java/org/horizon/executors and 10 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2009-01-28 13:26:32 -0500 (Wed, 28 Jan 2009)
New Revision: 7606
Added:
core/branches/flat/src/test/java/org/horizon/BaseClusteredTest.java
Removed:
core/branches/flat/src/test/java/org/horizon/BaseReplicatedTest.java
core/branches/flat/src/test/java/org/horizon/util/internals/ReplicationListener.java
Modified:
core/branches/flat/src/main/java/org/horizon/Cache.java
core/branches/flat/src/main/java/org/horizon/CacheDelegate.java
core/branches/flat/src/main/java/org/horizon/executors/DefaultExecutorFactory.java
core/branches/flat/src/main/java/org/horizon/executors/DefaultScheduledExecutorFactory.java
core/branches/flat/src/main/java/org/horizon/factories/InterceptorChainFactory.java
core/branches/flat/src/main/java/org/horizon/interceptors/InterceptorChain.java
core/branches/flat/src/main/java/org/horizon/transaction/DummyTransactionManager.java
core/branches/flat/src/main/java/org/horizon/tree/TreeCache.java
core/branches/flat/src/main/java/org/horizon/tree/TreeCacheImpl.java
core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.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/replication/AsyncReplTest.java
core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java
Log:
replication code + tests on shared transport
Modified: core/branches/flat/src/main/java/org/horizon/Cache.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/Cache.java 2009-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/main/java/org/horizon/Cache.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -81,13 +81,48 @@
String getVersion();
+ /**
+ * Adds a custom interceptor to the interceptor chain, at specified position, where the first interceptor in the
+ * chain is at position 0 and the last one at NUM_INTERCEPTORS - 1.
+ *
+ * @param i the interceptor to add
+ * @param position the position to add the interceptor
+ */
void addInterceptor(CommandInterceptor i, int position);
- void addInterceptor(CommandInterceptor i, Class<? extends CommandInterceptor> afterInterceptor);
+ /**
+ * Adds a custom interceptor to the interceptor chain, after an instance of the specified interceptor type. Throws a
+ * cache exception if it cannot find an interceptor of the specified type.
+ *
+ * @param i interceptor to add
+ * @param afterInterceptor interceptor type after which to place custom interceptor
+ */
+ void addInterceptorAfter(CommandInterceptor i, Class<? extends CommandInterceptor> afterInterceptor);
+ /**
+ * Adds a custom interceptor to the interceptor chain, before an instance of the specified interceptor type. Throws a
+ * cache exception if it cannot find an interceptor of the specified type.
+ *
+ * @param i interceptor to add
+ * @param beforeInterceptor interceptor type before which to place custom interceptor
+ */
+ void addInterceptorBefore(CommandInterceptor i, Class<? extends CommandInterceptor> beforeInterceptor);
+
+ /**
+ * Removes the interceptor at a specified position, where the first interceptor in the chain is at position 0 and the
+ * last one at getInterceptorChain().size() - 1.
+ *
+ * @param position the position at which to remove an interceptor
+ */
void removeInterceptor(int position);
+ /**
+ * Removes the interceptor of specified type.
+ *
+ * @param interceptorType type of interceptor to remove
+ */
void removeInterceptor(Class<? extends CommandInterceptor> interceptorType);
+
CacheManager getCacheManager();
}
Modified: core/branches/flat/src/main/java/org/horizon/CacheDelegate.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/CacheDelegate.java 2009-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/main/java/org/horizon/CacheDelegate.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -285,19 +285,23 @@
}
public void addInterceptor(CommandInterceptor i, int position) {
- throw new IllegalStateException();//todo Implement me properly
+ invoker.addInterceptor(i, position);
}
- public void addInterceptor(CommandInterceptor i, Class<? extends CommandInterceptor> afterInterceptor) {
- throw new IllegalStateException();//todo Implement me properly
+ public void addInterceptorAfter(CommandInterceptor i, Class<? extends CommandInterceptor> afterInterceptor) {
+ invoker.addInterceptorAfter(i, afterInterceptor);
}
+ public void addInterceptorBefore(CommandInterceptor i, Class<? extends CommandInterceptor> beforeInterceptor) {
+ invoker.addInterceptorBefore(i, beforeInterceptor);
+ }
+
public void removeInterceptor(int position) {
- throw new IllegalStateException();//todo Implement me properly
+ invoker.removeInterceptor(position);
}
public void removeInterceptor(Class<? extends CommandInterceptor> interceptorType) {
- throw new IllegalStateException();//todo Implement me properly
+ invoker.removeInterceptor(interceptorType);
}
public CacheLoaderManager getCacheLoaderManager() {
Modified: core/branches/flat/src/main/java/org/horizon/executors/DefaultExecutorFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/executors/DefaultExecutorFactory.java 2009-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/main/java/org/horizon/executors/DefaultExecutorFactory.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -26,7 +26,7 @@
ThreadFactory tf = new ThreadFactory() {
public Thread newThread(Runnable r) {
- return new Thread(threadNamePrefix + "-" + counter.getAndIncrement());
+ return new Thread(r, threadNamePrefix + "-" + counter.getAndIncrement());
}
};
Modified: core/branches/flat/src/main/java/org/horizon/executors/DefaultScheduledExecutorFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/executors/DefaultScheduledExecutorFactory.java 2009-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/main/java/org/horizon/executors/DefaultScheduledExecutorFactory.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -18,7 +18,7 @@
final AtomicInteger counter = new AtomicInteger(0);
return Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
public Thread newThread(Runnable r) {
- return new Thread(threadNamePrefix + "-" + counter.getAndIncrement());
+ return new Thread(r, threadNamePrefix + "-" + counter.getAndIncrement());
}
});
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/InterceptorChainFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/InterceptorChainFactory.java 2009-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/main/java/org/horizon/factories/InterceptorChainFactory.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -171,7 +171,7 @@
throw new ConfigurationException("Cannot add after class: " + config.getAfterClass()
+ " as no such iterceptor exists in the default chain");
}
- interceptorChain.addAfterInterceptor(config.getInterceptor(), withClassName.get(0).getClass());
+ interceptorChain.addInterceptorAfter(config.getInterceptor(), withClassName.get(0).getClass());
}
if (config.getBeforeClass() != null) {
List<CommandInterceptor> withClassName = interceptorChain.getInterceptorsWithClassName(config.getBeforeClass());
@@ -179,7 +179,7 @@
throw new ConfigurationException("Cannot add before class: " + config.getAfterClass()
+ " as no such iterceptor exists in the default chain");
}
- interceptorChain.addBeforeInterceptor(config.getInterceptor(), withClassName.get(0).getClass());
+ interceptorChain.addInterceptorBefore(config.getInterceptor(), withClassName.get(0).getClass());
}
}
}
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/InterceptorChain.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/InterceptorChain.java 2009-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/InterceptorChain.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -182,7 +182,7 @@
*
* @return true if the interceptor was added; i.e. the afterInterceptor exists
*/
- public synchronized boolean addAfterInterceptor(CommandInterceptor toAdd, Class<? extends CommandInterceptor> afterInterceptor) {
+ public synchronized boolean addInterceptorAfter(CommandInterceptor toAdd, Class<? extends CommandInterceptor> afterInterceptor) {
CommandInterceptor it = firstInChain;
while (it != null) {
if (it.getClass().equals(afterInterceptor)) {
@@ -200,7 +200,7 @@
*
* @return true if the interceptor was added; i.e. the afterInterceptor exists
*/
- public synchronized boolean addBeforeInterceptor(CommandInterceptor toAdd, Class<? extends CommandInterceptor> beforeInterceptor) {
+ public synchronized boolean addInterceptorBefore(CommandInterceptor toAdd, Class<? extends CommandInterceptor> beforeInterceptor) {
if (firstInChain.getClass().equals(beforeInterceptor)) {
toAdd.setNext(firstInChain);
firstInChain = toAdd;
Modified: core/branches/flat/src/main/java/org/horizon/transaction/DummyTransactionManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/transaction/DummyTransactionManager.java 2009-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/main/java/org/horizon/transaction/DummyTransactionManager.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -27,6 +27,7 @@
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
+import javax.naming.NoInitialContextException;
import java.util.Properties;
/**
@@ -54,8 +55,10 @@
Context ctx = new InitialContext(p);
ctx.bind("java:/TransactionManager", instance);
ctx.bind("UserTransaction", utx);
- }
- catch (NamingException e) {
+ } catch (NoInitialContextException nie) {
+ log.debug(nie.getMessage());
+
+ } catch (NamingException e) {
log.debug("binding of DummyTransactionManager failed", e);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/tree/TreeCache.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/TreeCache.java 2009-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/main/java/org/horizon/tree/TreeCache.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -23,15 +23,8 @@
import org.horizon.Cache;
import org.horizon.CacheException;
-import org.horizon.ComponentStatus;
-import org.horizon.config.Configuration;
-import org.horizon.context.InvocationContext;
-import org.horizon.interceptors.base.CommandInterceptor;
import org.horizon.lifecycle.Lifecycle;
-import org.horizon.notifications.Listenable;
-import org.horizon.remoting.transport.Address;
-import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -55,7 +48,7 @@
* @see Node
* @since 1.0
*/
-public interface TreeCache<K, V> extends Lifecycle, Listenable {
+public interface TreeCache<K, V> extends Lifecycle {
/**
* Returns the root node of this cache.
*
@@ -236,41 +229,6 @@
void evict(Fqn fqn);
/**
- * Gets where the cache currently is its lifecycle transitions.
- *
- * @return the CacheStatus. Will not return <code>null</code>.
- */
- ComponentStatus getCacheStatus();
-
- /**
- * @return the current invocation context for the current invocation and cache instance.
- * @throws IllegalStateException if the cache has been destroyed.
- */
- InvocationContext getInvocationContext();
-
- /**
- * Sets the passed in {@link InvocationContext} as current.
- *
- * @param ctx invocation context to use
- * @throws IllegalStateException if the cache has been destroyed.
- */
- void setInvocationContext(InvocationContext ctx);
-
- /**
- * Returns the local address of this cache in a cluster, or <code>null</code> if running in local mode.
- *
- * @return the local address of this cache in a cluster, or <code>null</code> if running in local mode.
- */
- Address getAddress();
-
- /**
- * Returns a list of members in the cluster, or <code>null</code> if running in local mode.
- *
- * @return a {@link List} of members in the cluster, or <code>null</code> if running in local mode.
- */
- List<Address> getMembers();
-
- /**
* Moves a part of the cache to a different subtree.
* <p/>
* E.g.:
@@ -380,77 +338,23 @@
void clearData(Fqn fqn);
/**
- * Starts a batch. This is a lightweight batching mechanism that groups cache writes together and finally performs
- * the write, persistence and/or replication when {@link #endBatch(boolean)} is called rather than for each
- * invocation on the cache.
- * <p/>
- * Note that if there is an existing transaction in scope and the cache has been configured to use a JTA compliant
- * transaction manager, calls to {@link #startBatch()} and {@link #endBatch(boolean)} are ignored and treated as
- * no-ops.
- * <p/>
- *
- * @see #endBatch(boolean)
- * @since 1.0
+ * @return a reference to the underlying cache instance
*/
- void startBatch();
+ Cache<K, V> getCache();
/**
- * Ends an existing ongoing batch. A no-op if a batch has not been started yet.
- * <p/>
- * Note that if there is an existing transaction in scope and the cache has been configured to use a JTA compliant
- * transaction manager, calls to {@link #startBatch()} and {@link #endBatch(boolean)} are ignored and treated as
- * no-ops.
- * <p/>
+ * Tests if an Fqn exists. Convenience method for {@link #exists(Fqn)}
*
- * @param successful if <tt>true</tt>, changes made in the batch are committed. If <tt>false</tt>, they are
- * discarded.
- * @see #startBatch()
- * @since 1.0
+ * @param fqn string representation of an Fqn
+ * @return true if the fqn exists, false otherwise
*/
- void endBatch(boolean successful);
+ boolean exists(String fqn);
/**
- * Adds a custom interceptor to the interceptor chain, at specified position, where the first interceptor in the
- * chain is at position 0 and the last one at getInterceptorChain().size() - 1.
+ * Tests if an Fqn exists.
*
- * @param i the interceptor to add
- * @param position the position to add the interceptor
- * @since 1.0
+ * @param fqn Fqn to test
+ * @return true if the fqn exists, false otherwise
*/
- void addInterceptor(CommandInterceptor i, int position);
-
- /**
- * Adds a custom interceptor to the interceptor chain, after an instance of the specified interceptor type. Throws a
- * cache exception if it cannot find an interceptor of the specified type.
- *
- * @param i interceptor to add
- * @param afterInterceptor interceptor type after which to place custom interceptor
- * @since 1.0
- */
- void addInterceptor(CommandInterceptor i, Class<? extends CommandInterceptor> afterInterceptor);
-
- /**
- * Removes the interceptor at a specified position, where the first interceptor in the chain is at position 0 and the
- * last one at getInterceptorChain().size() - 1.
- *
- * @param position the position at which to remove an interceptor
- * @since 1.0
- */
- void removeInterceptor(int position);
-
- /**
- * Removes the interceptor of specified type.
- *
- * @param interceptorType type of interceptor to remove
- * @since 1.0
- */
- void removeInterceptor(Class<? extends CommandInterceptor> interceptorType);
-
- Configuration getConfiguration();
-
- Cache<K, V> getCache();
-
- boolean exists(String fqn);
-
boolean exists(Fqn fqn);
}
Modified: core/branches/flat/src/main/java/org/horizon/tree/TreeCacheImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/TreeCacheImpl.java 2009-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/main/java/org/horizon/tree/TreeCacheImpl.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -23,16 +23,10 @@
import org.horizon.Cache;
import org.horizon.CacheException;
-import org.horizon.ComponentStatus;
import org.horizon.atomic.AtomicMap;
-import org.horizon.config.Configuration;
-import org.horizon.context.InvocationContext;
-import org.horizon.interceptors.base.CommandInterceptor;
import org.horizon.logging.Log;
import org.horizon.logging.LogFactory;
-import org.horizon.remoting.transport.Address;
-import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -287,70 +281,10 @@
}
// ------------------ nothing different; just delegate to the cache
- public void addListener(Object listener) {
- cache.addListener(listener);
- }
-
- public void removeListener(Object listener) {
- cache.removeListener(listener);
- }
-
- public Set<Object> getListeners() {
- return cache.getListeners();
- }
-
- public void startBatch() {
- cache.startBatch();
- }
-
- public void endBatch(boolean successful) {
- cache.endBatch(successful);
- }
-
- public void addInterceptor(CommandInterceptor i, int position) {
- cache.addInterceptor(i, position);
- }
-
- public void addInterceptor(CommandInterceptor i, Class<? extends CommandInterceptor> afterInterceptor) {
- cache.addInterceptor(i, afterInterceptor);
- }
-
- public void removeInterceptor(int position) {
- cache.removeInterceptor(position);
- }
-
- public void removeInterceptor(Class<? extends CommandInterceptor> interceptorType) {
- cache.removeInterceptor(interceptorType);
- }
-
- public Configuration getConfiguration() {
- return cache.getConfiguration();
- }
-
public Cache getCache() {
return cache;
}
- public ComponentStatus getCacheStatus() {
- return cache.getCacheStatus();
- }
-
- public InvocationContext getInvocationContext() {
- return cache.getInvocationContext();
- }
-
- public void setInvocationContext(InvocationContext ctx) {
- cache.setInvocationContext(ctx);
- }
-
- public Address getAddress() {
- return cache.getCacheManager().getAddress();
- }
-
- public List<Address> getMembers() {
- return cache.getCacheManager().getMembers();
- }
-
public void start() throws CacheException {
cache.start();
createRoot();
Modified: core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java 2009-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -89,20 +89,6 @@
}
/**
- * Injects an interceptor after a specified interceptor in a running cache. Your new interceptor need not be
- * initialised with pointers to the next interceptor, etc. as this method does all that for you, including calling
- * setCache().
- *
- * @param cache running cache instance
- * @param interceptorToInject interceptor instance to inject.
- * @param interceptorAfterWhichToInject class of interceptor to search for in the chain and after which to add your
- * interceptor
- */
- public static void injectInterceptor(CacheSPI<?, ?> cache, CommandInterceptor interceptorToInject, Class<? extends CommandInterceptor> interceptorAfterWhichToInject) {
- cache.addInterceptor(interceptorToInject, interceptorAfterWhichToInject);
- }
-
- /**
* Loops, continually calling {@link #areCacheViewsComplete(Cache[])} until it either returns true or
* <code>timeout</code> ms have elapsed.
*
@@ -628,4 +614,8 @@
ComponentRegistry cr = extractComponentRegistry(cache);
return cr.getComponent(componentType);
}
+
+ public static TransactionManager getTransactionManager(Cache cache) {
+ return extractComponent(cache, TransactionManager.class);
+ }
}
Copied: core/branches/flat/src/test/java/org/horizon/BaseClusteredTest.java (from rev 7605, core/branches/flat/src/test/java/org/horizon/BaseReplicatedTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/BaseClusteredTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/BaseClusteredTest.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -0,0 +1,163 @@
+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.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;
+
+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 addCacheManager() {
+ 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 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
+ public void cleanupThreadLocals() {
+ TestingUtil.killCacheManagers(cacheManagerThreadLocal.get().toArray(new CacheManager[cacheManagerThreadLocal.get().size()]));
+ cacheManagerThreadLocal.get().clear();
+ }
+
+ 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.addInterceptor(new ReplListenerInterceptor(), 0);
+ }
+
+ public void expectAny() {
+ expect();
+ }
+
+ 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);
+ }
+
+ 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);
+ }
+
+ public void expect(Class<? extends VisitableCommand>... expectedCommands) {
+ if (this.expectedCommands == null) {
+ this.expectedCommands = new HashSet<Class<? extends VisitableCommand>>();
+ }
+ this.expectedCommands.addAll(Arrays.asList(expectedCommands));
+ }
+
+ public void waitForReplication() {
+ waitForReplication(600, TimeUnit.SECONDS);
+ }
+
+ public void waitForReplication(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/BaseReplicatedTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/BaseReplicatedTest.java 2009-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/test/java/org/horizon/BaseReplicatedTest.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -1,68 +0,0 @@
-package org.horizon;
-
-import org.horizon.config.Configuration;
-import org.horizon.config.GlobalConfiguration;
-import org.horizon.manager.CacheManager;
-import org.horizon.manager.DefaultCacheManager;
-import org.horizon.util.TestingUtil;
-import org.testng.annotations.AfterMethod;
-
-import java.util.LinkedList;
-import java.util.List;
-
-public abstract class BaseReplicatedTest {
- 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 addCacheManager() {
- 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 void assertClusterSize(String message, int size) {
- for (CacheManager cm : cacheManagerThreadLocal.get()) {
- assert cm.getMembers() != null && cm.getMembers().size() == size : message;
- }
- }
-
- @AfterMethod
- public void cleanupThreadLocals() {
- TestingUtil.killCacheManagers(cacheManagerThreadLocal.get().toArray(new CacheManager[cacheManagerThreadLocal.get().size()]));
- cacheManagerThreadLocal.get().clear();
- }
-
-}
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-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -2,23 +2,21 @@
import org.easymock.EasyMock;
import static org.easymock.EasyMock.*;
+import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
-import org.horizon.CacheSPI;
-import org.horizon.UnitTestCacheFactory;
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.factories.ComponentRegistry;
+import org.horizon.manager.CacheManager;
import org.horizon.remoting.RPCManager;
import org.horizon.remoting.ResponseMode;
import org.horizon.remoting.transport.Address;
import org.horizon.transaction.DummyTransactionManagerLookup;
import org.horizon.transaction.TransactionTable;
import org.horizon.util.TestingUtil;
-import org.horizon.util.internals.ReplicationListener;
import static org.testng.AssertJUnit.*;
-import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -26,52 +24,37 @@
import javax.transaction.TransactionManager;
import java.util.List;
-@Test(groups = {"functional", "jgroups", "transaction"})
-public class PutForExternalReadTest {
- protected final String key = "k", value = "v", value2 = "v2";
+@Test(groups = "functional", sequential = true)
+public class PutForExternalReadTest extends BaseClusteredTest {
+ final String key = "k", value = "v", value2 = "v2";
+ Cache cache1, cache2;
+ TransactionManager tm1, tm2;
+ ReplListener replListener1, replListener2;
- protected CacheSPI<String, String> cache1, cache2;
-
- ReplicationListener replListener1;
- ReplicationListener replListener2;
-
- protected TransactionManager tm1, tm2;
-
- protected boolean useTx;
-
-
@BeforeMethod(alwaysRun = true)
public void setUp() {
-
- UnitTestCacheFactory<String, String> cf = new UnitTestCacheFactory<String, String>();
Configuration c = new Configuration();
c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
- cache1 = (CacheSPI<String, String>) cf.createCache(c, false);
- cache1.getConfiguration().setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- // TODO fix this
-// cache1.getConfiguration().setSerializationExecutorPoolSize(0);//this is very important for async tests!
+ c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ CacheManager cm1 = addCacheManager();
+ CacheManager cm2 = addCacheManager();
+ defineCacheOnAllManagers("replSync", c);
- cache1.start();
- tm1 = cache1.getConfiguration().getRuntimeConfig().getTransactionManager();
+ cache1 = cm1.getCache("replSync");
+ cache2 = cm2.getCache("replSync");
- cache2 = (CacheSPI<String, String>) cf.createCache(cache1.getConfiguration().clone());
-
- tm2 = cache2.getConfiguration().getRuntimeConfig().getTransactionManager();
- replListener1 = new ReplicationListener(cache1);
- replListener2 = new ReplicationListener(cache2);
-
+ tm1 = TestingUtil.getTransactionManager(cache1);
+ tm2 = TestingUtil.getTransactionManager(cache2);
TestingUtil.blockUntilViewsReceived(10000, cache1, cache2);
- }
- @AfterMethod(alwaysRun = true)
- public void tearDown() {
- TestingUtil.killCaches(cache1, cache2);
+ replListener1 = attachReplicationListener(cache1);
+ replListener2 = attachReplicationListener(cache2);
}
public void testNoOpWhenKeyPresent() {
replListener2.expect(PutKeyValueCommand.class);
cache1.putForExternalRead(key, value);
- replListener2.waitForReplicationToOccur();
+ replListener2.waitForReplication();
assertEquals("PFER should have succeeded", value, cache1.get(key));
@@ -80,14 +63,14 @@
// reset
replListener2.expect(RemoveCommand.class);
cache1.remove(key);
- replListener2.waitForReplicationToOccur();
+ replListener2.waitForReplication();
assert cache1.isEmpty() : "Should have reset";
assert cache2.isEmpty() : "Should have reset";
replListener2.expect(PutKeyValueCommand.class);
cache1.put(key, value);
- replListener2.waitForReplicationToOccur();
+ replListener2.waitForReplication();
// now this pfer should be a no-op
cache1.putForExternalRead(key, value2);
@@ -135,7 +118,7 @@
// create parent node first
replListener2.expect(PutKeyValueCommand.class);
cache1.put(key + "0", value);
- replListener2.waitForReplicationToOccur();
+ replListener2.waitForReplication();
// start a tx and do some stuff.
replListener2.expect(PutKeyValueCommand.class);
@@ -144,7 +127,7 @@
cache1.putForExternalRead(key, value); // should have happened in a separate tx and have committed already.
Transaction t = tm1.suspend();
- replListener2.waitForReplicationToOccur();
+ replListener2.waitForReplication();
assertEquals("PFER should have completed", value, cache1.get(key));
assertEquals("PFER should have completed", value, cache2.get(key));
@@ -200,7 +183,7 @@
replListener2.expect(PutKeyValueCommand.class);
cache1.putForExternalRead(key, value);
- replListener2.waitForReplicationToOccur();
+ replListener2.waitForReplication();
assertEquals("PFER updated cache1", value, cache1.get(key));
assertEquals("PFER propagated to cache2 as expected", value, cache2.get(key));
@@ -243,7 +226,7 @@
tm1.begin();
cache1.putForExternalRead(key, value);
tm1.commit();
- replListener2.waitForReplicationToOccur();
+ replListener2.waitForReplication();
TransactionTable tt1 = getTransactionTable(cache1);
TransactionTable tt2 = getTransactionTable(cache2);
@@ -260,7 +243,7 @@
cache1.putForExternalRead(key, value);
cache1.put(key, value);
tm1.commit();
- replListener2.waitForReplicationToOccur();
+ replListener2.waitForReplication();
assert tt1.getNumGlobalTransactions() == 0 : "Cache 1 should have no stale global TXs";
assert tt1.getNumLocalTransactions() == 0 : "Cache 1 should have no stale local TXs";
@@ -272,7 +255,7 @@
cache1.put(key, value);
cache1.putForExternalRead(key, value);
tm1.commit();
- replListener2.waitForReplicationToOccur();
+ replListener2.waitForReplication();
assert tt1.getNumGlobalTransactions() == 0 : "Cache 1 should have no stale global TXs";
assert tt1.getNumLocalTransactions() == 0 : "Cache 1 should have no stale local TXs";
@@ -286,7 +269,7 @@
cache1.putForExternalRead(key, value);
cache1.put(key, value);
tm1.commit();
- replListener2.waitForReplicationToOccur();
+ replListener2.waitForReplication();
assert tt1.getNumGlobalTransactions() == 0 : "Cache 1 should have no stale global TXs";
assert tt1.getNumLocalTransactions() == 0 : "Cache 1 should have no stale local TXs";
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-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -1,8 +1,8 @@
package org.horizon.api.tree;
-import org.horizon.CacheSPI;
-import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
+import org.horizon.manager.CacheManager;
+import org.horizon.manager.DefaultCacheManager;
import org.horizon.transaction.DummyTransactionManager;
import org.horizon.transaction.DummyTransactionManagerLookup;
import org.horizon.tree.Fqn;
@@ -11,7 +11,6 @@
import org.horizon.tree.TreeCacheImpl;
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;
@@ -26,35 +25,26 @@
*
* @author <a href="mailto:manik AT jboss DOT org">Manik Surtani</a>
*/
-@Test(groups = "functional")
+@Test(groups = "functional", sequential = true)
public class NodeAPITest {
- protected ThreadLocal<TreeCache<Object, Object>> cacheTL = new ThreadLocal<TreeCache<Object, Object>>();
- protected static final Fqn A = Fqn.fromString("/a"), B = Fqn.fromString("/b"), C = Fqn.fromString("/c"), D = Fqn.fromString("/d");
- protected Fqn A_B = Fqn.fromRelativeFqn(A, B);
- protected Fqn A_C = Fqn.fromRelativeFqn(A, C);
- protected TransactionManager tm;
+ 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);
+ Fqn A_C = Fqn.fromRelativeFqn(A, C);
+ TransactionManager tm;
+ TreeCache cache;
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
// start a single cache instance
Configuration c = new Configuration();
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- CacheSPI<Object, Object> cache = (CacheSPI<Object, Object>) new UnitTestCacheFactory<Object, Object>().createCache(c, false);
- cache.getConfiguration().setInvocationBatchingEnabled(true);
- cache.start();
- cacheTL.set(new TreeCacheImpl(cache));
- tm = cache.getTransactionManager();
+ c.setInvocationBatchingEnabled(true);
+ CacheManager cm = new DefaultCacheManager(c);
+ cache = new TreeCacheImpl(cm.getCache());
+ tm = TestingUtil.getTransactionManager(cache.getCache());
}
- @AfterMethod(alwaysRun = true)
- public void tearDown() {
- TreeCache<Object, Object> cache = cacheTL.get();
- TestingUtil.killTreeCaches(cache);
- cacheTL.set(null);
- }
-
public void testAddingData() {
- TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
Node<Object, Object> nodeA = rootNode.addChild(A);
nodeA.put("key", "value");
@@ -63,7 +53,6 @@
}
public void testAddingDataTx() throws Exception {
- TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
tm.begin();
Node<Object, Object> nodeA = rootNode.addChild(A);
@@ -74,7 +63,6 @@
}
public void testOverwritingDataTx() throws Exception {
- TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
Node<Object, Object> nodeA = rootNode.addChild(A);
@@ -93,7 +81,7 @@
* Remember, Fqns are relative!!
*/
public void testParentsAndChildren() {
- TreeCache<Object, Object> cache = cacheTL.get();
+
Node<Object, Object> rootNode = cache.getRoot();
Node<Object, Object> nodeA = rootNode.addChild(A);
@@ -138,7 +126,7 @@
public void testImmutabilityOfData() {
- TreeCache<Object, Object> cache = cacheTL.get();
+
Node<Object, Object> rootNode = cache.getRoot();
rootNode.put("key", "value");
@@ -161,7 +149,7 @@
}
public void testDefensiveCopyOfData() {
- TreeCache<Object, Object> cache = cacheTL.get();
+
Node<Object, Object> rootNode = cache.getRoot();
rootNode.put("key", "value");
@@ -187,7 +175,7 @@
}
public void testDefensiveCopyOfChildren() {
- TreeCache<Object, Object> cache = cacheTL.get();
+
Node<Object, Object> rootNode = cache.getRoot();
Fqn childFqn = Fqn.fromString("/child");
@@ -215,7 +203,7 @@
public void testImmutabilityOfChildren() {
- TreeCache<Object, Object> cache = cacheTL.get();
+
Node<Object, Object> rootNode = cache.getRoot();
rootNode.addChild(A);
@@ -230,7 +218,7 @@
}
public void testGetChildAPI() {
- TreeCache<Object, Object> cache = cacheTL.get();
+
Node<Object, Object> rootNode = cache.getRoot();
// creates a Node<Object, Object> with fqn /a/b/c
@@ -249,7 +237,7 @@
}
public void testClearingData() {
- TreeCache<Object, Object> cache = cacheTL.get();
+
Node<Object, Object> rootNode = cache.getRoot();
rootNode.put("k", "v");
@@ -261,7 +249,7 @@
}
public void testClearingDataTx() throws Exception {
- TreeCache<Object, Object> cache = cacheTL.get();
+
Node<Object, Object> rootNode = cache.getRoot();
tm.begin();
@@ -276,7 +264,7 @@
}
public void testPutData() {
- TreeCache<Object, Object> cache = cacheTL.get();
+
Node<Object, Object> rootNode = cache.getRoot();
assertTrue(rootNode.getData().isEmpty());
@@ -311,7 +299,7 @@
}
public void testGetChildrenNames() throws Exception {
- TreeCache<Object, Object> cache = cacheTL.get();
+
Node<Object, Object> rootNode = cache.getRoot();
rootNode.addChild(A).put("k", "v");
@@ -334,8 +322,8 @@
}
public void testDoubleRemovalOfData() throws Exception {
- TreeCache<Object, Object> cache = cacheTL.get();
+
assert DummyTransactionManager.getInstance().getTransaction() == null;
cache.put("/foo/1/2/3", "item", 1);
assert DummyTransactionManager.getInstance().getTransaction() == null;
@@ -356,8 +344,8 @@
}
public void testDoubleRemovalOfData2() throws Exception {
- TreeCache<Object, Object> cache = cacheTL.get();
+
cache.put("/foo/1/2", "item", 1);
tm.begin();
assertEquals(cache.get("/foo/1", "item"), null);
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-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -6,8 +6,10 @@
*/
package org.horizon.api.tree;
-import org.horizon.UnitTestCacheFactory;
+import org.horizon.BaseClusteredTest;
+import org.horizon.Cache;
import org.horizon.config.Configuration;
+import org.horizon.manager.CacheManager;
import org.horizon.transaction.DummyTransactionManagerLookup;
import org.horizon.tree.Fqn;
import org.horizon.tree.Node;
@@ -16,56 +18,46 @@
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 javax.transaction.TransactionManager;
-@Test(groups = {"functional", "jgroups", "pessimistic"}, testName = "api.NodeReplicatedMoveTest")
-public class NodeReplicatedMoveTest {
- private class NodeReplicatedMoveTestTL {
- protected TreeCache<Object, Object> cache1;
- protected TreeCache<Object, Object> cache2;
- protected TransactionManager tm;
- }
+@Test(groups = "functional", sequential = true, testName = "api.NodeReplicatedMoveTest")
+public class NodeReplicatedMoveTest extends BaseClusteredTest {
- protected ThreadLocal<NodeReplicatedMoveTestTL> threadLocal = new ThreadLocal<NodeReplicatedMoveTestTL>();
+ 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";
- protected static final Fqn A = Fqn.fromString("/a"), B = Fqn.fromString("/b"), C = Fqn.fromString("/c"), D = Fqn.fromString("/d"), E = Fqn.fromString("/e");
- protected static final Object k = "key", vA = "valueA", vB = "valueB", vC = "valueC", vD = "valueD", vE = "valueE";
+ TreeCache<Object, Object> cache1, cache2;
+ TransactionManager tm1;
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
- NodeReplicatedMoveTestTL tl = new NodeReplicatedMoveTestTL();
- threadLocal.set(tl);
Configuration c = new Configuration();
c.setInvocationBatchingEnabled(true);
c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
c.setSyncCommitPhase(true);
c.setSyncRollbackPhase(true);
- // start a single cache instance
- tl.cache1 = new TreeCacheImpl<Object, Object>(new UnitTestCacheFactory<Object, Object>().createCache(c.clone()));
- tl.cache2 = new TreeCacheImpl<Object, Object>(new UnitTestCacheFactory<Object, Object>().createCache(c.clone()));
- tl.tm = tl.cache1.getConfiguration().getRuntimeConfig().getTransactionManager();
- TestingUtil.blockUntilViewsReceived(10000, tl.cache1.getCache(), tl.cache2.getCache());
- }
+ CacheManager cm1 = addCacheManager();
+ CacheManager cm2 = addCacheManager();
- @AfterMethod(alwaysRun = true)
- public void tearDown() {
- NodeReplicatedMoveTestTL tl = threadLocal.get();
- if (tl != null) {
- TestingUtil.killTreeCaches(tl.cache1, tl.cache2);
- threadLocal.set(null);
- }
- }
+ defineCacheOnAllManagers("replSync", c);
+ 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);
+ }
+
public void testReplicatability() {
- NodeReplicatedMoveTestTL tl = threadLocal.get();
- Node<Object, Object> rootNode = tl.cache1.getRoot();
+ Node<Object, Object> rootNode = cache1.getRoot();
Node<Object, Object> nodeA = rootNode.addChild(A);
Node<Object, Object> nodeB = nodeA.addChild(B);
@@ -73,25 +65,24 @@
nodeA.put(k, vA);
nodeB.put(k, vB);
- assertEquals(vA, tl.cache1.getRoot().getChild(A).get(k));
- assertEquals(vB, tl.cache1.getRoot().getChild(A).getChild(B).get(k));
+ assertEquals(vA, cache1.getRoot().getChild(A).get(k));
+ assertEquals(vB, cache1.getRoot().getChild(A).getChild(B).get(k));
- assertEquals(vA, tl.cache2.getRoot().getChild(A).get(k));
- assertEquals(vB, tl.cache2.getRoot().getChild(A).getChild(B).get(k));
+ assertEquals(vA, cache2.getRoot().getChild(A).get(k));
+ assertEquals(vB, cache2.getRoot().getChild(A).getChild(B).get(k));
// now move...
- tl.cache1.move(nodeB.getFqn(), Fqn.ROOT);
+ cache1.move(nodeB.getFqn(), Fqn.ROOT);
- assertEquals(vA, tl.cache1.getRoot().getChild(A).get(k));
- assertEquals(vB, tl.cache1.getRoot().getChild(B).get(k));
+ assertEquals(vA, cache1.getRoot().getChild(A).get(k));
+ assertEquals(vB, cache1.getRoot().getChild(B).get(k));
- assertEquals(vA, tl.cache2.getRoot().getChild(A).get(k));
- assertEquals(vB, tl.cache2.getRoot().getChild(B).get(k));
+ assertEquals(vA, cache2.getRoot().getChild(A).get(k));
+ assertEquals(vB, cache2.getRoot().getChild(B).get(k));
}
public void testReplTxCommit() throws Exception {
- NodeReplicatedMoveTestTL tl = threadLocal.get();
- Node<Object, Object> rootNode = tl.cache1.getRoot();
+ Node<Object, Object> rootNode = cache1.getRoot();
Fqn A_B = Fqn.fromRelativeFqn(A, B);
Node<Object, Object> nodeA = rootNode.addChild(A);
Node<Object, Object> nodeB = nodeA.addChild(B);
@@ -99,54 +90,53 @@
nodeA.put(k, vA);
nodeB.put(k, vB);
- assertEquals(vA, tl.cache1.getRoot().getChild(A).get(k));
- assertEquals(vB, tl.cache1.getRoot().getChild(A).getChild(B).get(k));
+ assertEquals(vA, cache1.getRoot().getChild(A).get(k));
+ assertEquals(vB, cache1.getRoot().getChild(A).getChild(B).get(k));
- assertEquals(vA, tl.cache2.getRoot().getChild(A).get(k));
- assertEquals(vB, tl.cache2.getRoot().getChild(A).getChild(B).get(k));
+ assertEquals(vA, cache2.getRoot().getChild(A).get(k));
+ assertEquals(vB, cache2.getRoot().getChild(A).getChild(B).get(k));
// now move...
- tl.tm.begin();
- tl.cache1.move(nodeB.getFqn(), Fqn.ROOT);
+ tm1.begin();
+ cache1.move(nodeB.getFqn(), Fqn.ROOT);
- assertEquals(vA, tl.cache1.get(A, k));
- assertNull(tl.cache1.get(A_B, k));
- assertEquals(vB, tl.cache1.get(B, k));
- tl.tm.commit();
+ assertEquals(vA, cache1.get(A, k));
+ assertNull(cache1.get(A_B, k));
+ assertEquals(vB, cache1.get(B, k));
+ tm1.commit();
- assertEquals(vA, tl.cache1.getRoot().getChild(A).get(k));
- assertEquals(vB, tl.cache1.getRoot().getChild(B).get(k));
- assertEquals(vA, tl.cache2.getRoot().getChild(A).get(k));
- assertEquals(vB, tl.cache2.getRoot().getChild(B).get(k));
+ assertEquals(vA, cache1.getRoot().getChild(A).get(k));
+ assertEquals(vB, cache1.getRoot().getChild(B).get(k));
+ assertEquals(vA, cache2.getRoot().getChild(A).get(k));
+ assertEquals(vB, cache2.getRoot().getChild(B).get(k));
}
public void testReplTxRollback() throws Exception {
- NodeReplicatedMoveTestTL tl = threadLocal.get();
- Node<Object, Object> rootNode = tl.cache1.getRoot();
+ Node<Object, Object> rootNode = cache1.getRoot();
Node<Object, Object> nodeA = rootNode.addChild(A);
Node<Object, Object> nodeB = nodeA.addChild(B);
nodeA.put(k, vA);
nodeB.put(k, vB);
- assertEquals(vA, tl.cache1.getRoot().getChild(A).get(k));
- assertEquals(vB, tl.cache1.getRoot().getChild(A).getChild(B).get(k));
- assertEquals(vA, tl.cache2.getRoot().getChild(A).get(k));
- assertEquals(vB, tl.cache2.getRoot().getChild(A).getChild(B).get(k));
+ assertEquals(vA, cache1.getRoot().getChild(A).get(k));
+ assertEquals(vB, cache1.getRoot().getChild(A).getChild(B).get(k));
+ assertEquals(vA, cache2.getRoot().getChild(A).get(k));
+ assertEquals(vB, cache2.getRoot().getChild(A).getChild(B).get(k));
// now move...
- tl.tm.begin();
- tl.cache1.move(nodeB.getFqn(), Fqn.ROOT);
+ tm1.begin();
+ cache1.move(nodeB.getFqn(), Fqn.ROOT);
- assertEquals(vA, tl.cache1.get(A, k));
- assertEquals(vB, tl.cache1.get(B, k));
+ assertEquals(vA, cache1.get(A, k));
+ assertEquals(vB, cache1.get(B, k));
- tl.tm.rollback();
+ tm1.rollback();
- assertEquals(vA, tl.cache1.getRoot().getChild(A).get(k));
- assertEquals(vB, tl.cache1.getRoot().getChild(A).getChild(B).get(k));
- assertEquals(vA, tl.cache2.getRoot().getChild(A).get(k));
- assertEquals(vB, tl.cache2.getRoot().getChild(A).getChild(B).get(k));
+ assertEquals(vA, cache1.getRoot().getChild(A).get(k));
+ assertEquals(vB, cache1.getRoot().getChild(A).getChild(B).get(k));
+ assertEquals(vA, cache2.getRoot().getChild(A).get(k));
+ assertEquals(vB, cache2.getRoot().getChild(A).getChild(B).get(k));
}
}
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-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -7,17 +7,16 @@
package org.horizon.api.tree;
+import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
-import org.horizon.CacheSPI;
-import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
+import org.horizon.manager.CacheManager;
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.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -27,37 +26,31 @@
/**
* @author <a href="mailto:manik AT jboss DOT org">Manik Surtani (manik AT jboss DOT org)</a>
*/
-@Test(groups = {"functional", "jgroups", "pessimistic"}, sequential = true, testName = "api.SyncReplTest")
-public class SyncReplTest {
- private CacheSPI<Object, Object> c1, c2;
+@Test(groups = "functional", sequential = true, testName = "api.SyncReplTest")
+public class SyncReplTest extends BaseClusteredTest {
private TreeCache<Object, Object> cache1, cache2;
@BeforeMethod(alwaysRun = true)
public void setUp() {
- System.out.println("*** In setUp()");
Configuration c = new Configuration();
c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
c.setInvocationBatchingEnabled(true);
c.setFetchInMemoryState(false);
- c1 = (CacheSPI<Object, Object>) new UnitTestCacheFactory<Object, Object>().createCache(c.clone());
- c2 = (CacheSPI<Object, Object>) new UnitTestCacheFactory<Object, Object>().createCache(c.clone());
+ CacheManager cm1 = addCacheManager();
+ CacheManager cm2 = addCacheManager();
+ defineCacheOnAllManagers("replSync", c);
+
+ 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);
-
- System.out.println("*** Finished setUp()");
}
- @AfterMethod(alwaysRun = true)
- public void tearDown() {
- TestingUtil.killCaches(c1, c2);
- cache1 = null;
- cache2 = null;
- }
-
public void testBasicOperation() {
assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
@@ -82,8 +75,8 @@
assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
Fqn fqn = Fqn.fromString("/JSESSIONID/1010.10.5:3000/1234567890/1");
- cache1.getConfiguration().setSyncCommitPhase(true);
- cache2.getConfiguration().setSyncCommitPhase(true);
+ cache1.getCache().getConfiguration().setSyncCommitPhase(true);
+ cache2.getCache().getConfiguration().setSyncCommitPhase(true);
cache1.put(fqn, "age", 38);
@@ -100,28 +93,18 @@
Map<Object, Object> map = new HashMap<Object, Object>();
map.put("1", "1");
map.put("2", "2");
- cache1.getInvocationContext().getOptionOverrides().setSuppressLocking(true);
+ cache1.getCache().getInvocationContext().getOptionOverrides().setSuppressLocking(true);
cache1.getRoot().addChild(fqn).putAll(map);
- cache1.getInvocationContext().getOptionOverrides().setSuppressLocking(true);
+ cache1.getCache().getInvocationContext().getOptionOverrides().setSuppressLocking(true);
assertEquals("Value should be set", "1", cache1.get(fqn, "1"));
map = new HashMap<Object, Object>();
map.put("3", "3");
map.put("4", "4");
- cache1.getInvocationContext().getOptionOverrides().setSuppressLocking(true);
+ cache1.getCache().getInvocationContext().getOptionOverrides().setSuppressLocking(true);
cache1.getRoot().addChild(fqn1).putAll(map);
- cache1.getInvocationContext().getOptionOverrides().setSuppressLocking(true);
+ cache1.getCache().getInvocationContext().getOptionOverrides().setSuppressLocking(true);
assertEquals("Value should be set", "2", cache1.get(fqn, "2"));
}
-
-
- private void assertClusterSize(String message, int size) {
- assertClusterSize(message, size, cache1);
- assertClusterSize(message, size, cache2);
- }
-
- private void assertClusterSize(String message, int size, TreeCache c) {
- assertEquals(message, size, c.getMembers().size());
- }
}
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-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -7,10 +7,10 @@
package org.horizon.api.tree;
+import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
-import org.horizon.CacheSPI;
-import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
+import org.horizon.manager.CacheManager;
import org.horizon.transaction.DummyTransactionManagerLookup;
import org.horizon.tree.Fqn;
import org.horizon.tree.Node;
@@ -18,7 +18,6 @@
import org.horizon.tree.TreeCacheImpl;
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;
@@ -28,22 +27,16 @@
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.TransactionManager;
-import java.util.ArrayList;
-import java.util.List;
/**
* @author <a href="mailto:manik AT jboss DOT org">Manik Surtani (manik AT jboss DOT org)</a>
*/
-@Test(groups = {"functional", "jgroups", "transaction", "pessimistic"}, sequential = true, testName = "api.SyncReplTxTest")
-public class SyncReplTxTest {
- private List<CacheSPI<Object, Object>> flatCaches;
- private List<TreeCache<Object, Object>> caches;
+@Test(groups = "functional", sequential = true, testName = "api.SyncReplTxTest")
+public class SyncReplTxTest extends BaseClusteredTest {
+ TreeCache<Object, Object> cache1, cache2;
@BeforeMethod(alwaysRun = true)
public void setUp() throws CloneNotSupportedException {
- System.out.println("*** In setUp()");
- caches = new ArrayList<TreeCache<Object, Object>>();
- flatCaches = new ArrayList<CacheSPI<Object, Object>>();
Configuration c = new Configuration();
c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
c.setFetchInMemoryState(false);
@@ -52,30 +45,22 @@
c.setSyncRollbackPhase(true);
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- CacheSPI<Object, Object> cache1 = (CacheSPI<Object, Object>) new UnitTestCacheFactory<Object, Object>().createCache(c.clone());
- CacheSPI<Object, Object> cache2 = (CacheSPI<Object, Object>) new UnitTestCacheFactory<Object, Object>().createCache(c.clone());
+ CacheManager cm1 = addCacheManager();
+ CacheManager cm2 = addCacheManager();
- flatCaches.add(cache1);
- flatCaches.add(cache2);
+ defineCacheOnAllManagers("replSync", c);
- TestingUtil.blockUntilViewsReceived(caches.toArray(new Cache[0]), 10000);
+ Cache c1 = cm1.getCache("replSync");
+ Cache c2 = cm2.getCache("replSync");
- caches.add(new TreeCacheImpl<Object, Object>(cache1));
- caches.add(new TreeCacheImpl<Object, Object>(cache2));
+ TestingUtil.blockUntilViewsReceived(10000, cm1, cm2);
- System.out.println("*** Finished setUp()");
+ cache1 = new TreeCacheImpl<Object, Object>(c1);
+ cache2 = new TreeCacheImpl<Object, Object>(c2);
}
- @AfterMethod(alwaysRun = true)
- public void tearDown() {
- System.out.println("*** In tearDown()");
- TestingUtil.killTreeCaches(caches);
- caches = null;
- System.out.println("*** Finished tearDown()");
- }
-
- private TransactionManager beginTransaction(Cache<Object, Object> cache) throws NotSupportedException, SystemException {
- TransactionManager mgr = cache.getConfiguration().getRuntimeConfig().getTransactionManager();
+ private TransactionManager beginTransaction(Cache cache) throws NotSupportedException, SystemException {
+ TransactionManager mgr = TestingUtil.getTransactionManager(cache);
mgr.begin();
return mgr;
}
@@ -86,29 +71,19 @@
Fqn f = Fqn.fromString("/test/data");
String k = "key", v = "value";
- assertNull("Should be null", caches.get(0).getRoot().getChild(f));
- assertNull("Should be null", caches.get(1).getRoot().getChild(f));
+ assertNull("Should be null", cache1.getRoot().getChild(f));
+ assertNull("Should be null", cache2.getRoot().getChild(f));
- Node<Object, Object> node = caches.get(0).getRoot().addChild(f);
+ Node<Object, Object> node = cache1.getRoot().addChild(f);
assertNotNull("Should not be null", node);
- TransactionManager tm = beginTransaction(caches.get(0).getCache());
+ TransactionManager tm = beginTransaction(cache1.getCache());
node.put(k, v);
tm.commit();
assertEquals(v, node.get(k));
- assertEquals(v, caches.get(0).get(f, k));
- assertEquals("Should have replicated", v, caches.get(1).get(f, k));
+ assertEquals(v, cache1.get(f, k));
+ assertEquals("Should have replicated", v, cache2.get(f, k));
}
-
- private void assertClusterSize(String message, int size) {
- for (Cache<Object, Object> c : flatCaches) {
- assertClusterSize(message, size, c);
- }
- }
-
- private void assertClusterSize(String message, int size, Cache<Object, Object> c) {
- assertEquals(message, size, c.getCacheManager().getMembers().size());
- }
}
\ No newline at end of file
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-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -222,7 +222,7 @@
}
public void testRpcManagerElements() {
- assertEquals("CacheMode.LOCAL cache has no address", null, cache.getAddress());
- assertEquals("CacheMode.LOCAL cache has no members list", null, cache.getMembers());
+ assertEquals("CacheMode.LOCAL cache has no address", null, cache.getCache().getCacheManager().getAddress());
+ assertEquals("CacheMode.LOCAL cache has no members list", null, cache.getCache().getCacheManager().getMembers());
}
}
Modified: core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java 2009-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -8,99 +8,89 @@
package org.horizon.replication;
+import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
-import org.horizon.CacheSPI;
-import org.horizon.UnitTestCacheManager;
import org.horizon.config.Configuration;
+import org.horizon.manager.CacheManager;
import org.horizon.transaction.DummyTransactionManagerLookup;
import org.horizon.util.TestingUtil;
-import org.horizon.util.internals.ReplicationListener;
-import static org.testng.AssertJUnit.*;
-import org.testng.annotations.AfterMethod;
+import static org.testng.AssertJUnit.assertEquals;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.transaction.TransactionManager;
+import java.util.concurrent.TimeUnit;
/**
* Unit test for replicated async CacheSPI. Use locking and multiple threads to test concurrent access to the tree.
*/
-@Test(groups = {"functional", "jgroups"})
-public class AsyncReplTest {
+@Test(groups = "functional", sequential = true)
+public class AsyncReplTest extends BaseClusteredTest {
- private class AsyncReplTestTL {
- private Configuration configuration;
- private CacheSPI<Object, Object> cache1, cache2;
- private UnitTestCacheManager cacheManager1, cacheManager2;
- private ReplicationListener replListener1, replListener2;
- }
+ Cache cache1, cache2;
- private ThreadLocal<AsyncReplTestTL> threadLocal = new ThreadLocal<AsyncReplTestTL>();
-
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
- AsyncReplTestTL tl = new AsyncReplTestTL();
- threadLocal.set(tl);
+ Configuration asyncConfiguration = new Configuration();
+ asyncConfiguration.setCacheMode(Configuration.CacheMode.REPL_ASYNC);
+ asyncConfiguration.setSyncCommitPhase(true);
+ asyncConfiguration.setSyncRollbackPhase(true);
+ asyncConfiguration.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- tl.configuration = new Configuration();
- tl.configuration.setCacheMode(Configuration.CacheMode.REPL_ASYNC);
- tl.configuration.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ CacheManager cm1 = addCacheManager();
+ CacheManager cm2 = addCacheManager();
- log("creating cache1");
- tl.cacheManager1 = new UnitTestCacheManager(tl.configuration);
- tl.cache1 = (CacheSPI) tl.cacheManager1.createCache("testCache");
- tl.replListener1 = new ReplicationListener(tl.cache1);
+ defineCacheOnAllManagers("asyncRepl", asyncConfiguration);
- log("creating cache2");
- tl.cacheManager2 = new UnitTestCacheManager(tl.configuration);
- tl.cache2 = (CacheSPI) tl.cacheManager2.createCache("testCache");
- tl.replListener2 = new ReplicationListener(tl.cache2);
+ cache1 = cm1.getCache("asyncRepl");
+ cache2 = cm2.getCache("asyncRepl");
}
- /**
- * Provides a hook for multiplexer integration. This default implementation is a no-op; subclasses that test mux
- * integration would override to integrate the given cache with a multiplexer.
- * <p/>
- * param cache a cache that has been configured but not yet created.
- */
- protected void configureMultiplexer(Cache cache) throws Exception {
- // default does nothing
- }
+ public void testWithNoTx() throws Exception {
+ ReplListener replListener2 = attachReplicationListener(cache2);
- @AfterMethod(alwaysRun = true)
- public void tearDown() throws Exception {
- AsyncReplTestTL tl = threadLocal.get();
- TestingUtil.killCaches(tl.cache1, tl.cache2);
- threadLocal.set(null);
+ String key = "key";
+
+ replListener2.expectAny();
+ cache1.put(key, "value1");
+ // allow for replication
+ replListener2.waitForReplication(60, TimeUnit.SECONDS);
+ assertEquals("value1", cache1.get(key));
+ assertEquals("value1", cache2.get(key));
+
+ replListener2.expectAny();
+ cache1.put(key, "value2");
+ assertEquals("value2", cache1.get(key));
+
+ replListener2.waitForReplication(60, TimeUnit.SECONDS);
+
+ assertEquals("value2", cache1.get(key));
+ assertEquals("value2", cache2.get(key));
}
- public void testTxCompletion() throws Exception {
- AsyncReplTestTL tl = threadLocal.get();
- CacheSPI<Object, Object> cache1 = tl.cache1;
- CacheSPI<Object, Object> cache2 = tl.cache2;
- ReplicationListener replListener1 = tl.replListener1;
- ReplicationListener replListener2 = tl.replListener2;
+ public void testWithTx() throws Exception {
+ ReplListener replListener2 = attachReplicationListener(cache2);
String key = "key";
replListener2.expectAny();
cache1.put(key, "value1");
// allow for replication
- replListener2.waitForReplicationToOccur(500);
+ replListener2.waitForReplication(60, TimeUnit.SECONDS);
assertEquals("value1", cache1.get(key));
assertEquals("value1", cache2.get(key));
- TransactionManager mgr = cache1.getTransactionManager();
+ TransactionManager mgr = TestingUtil.getTransactionManager(cache1);
mgr.begin();
- replListener2.expectAny();
+ replListener2.expectAnyWithTx();
cache1.put(key, "value2");
assertEquals("value2", cache1.get(key));
assertEquals("value1", cache2.get(key));
mgr.commit();
- replListener2.waitForReplicationToOccur(500);
+ replListener2.waitForReplication(60, TimeUnit.SECONDS);
assertEquals("value2", cache1.get(key));
assertEquals("value2", cache2.get(key));
@@ -115,86 +105,4 @@
assertEquals("value2", cache1.get(key));
assertEquals("value2", cache2.get(key));
}
-
- public void testPutShouldNotReplicateToDifferentCluster() {
- AsyncReplTestTL tl = threadLocal.get();
- CacheSPI<Object, Object> cache1 = tl.cache1;
- CacheSPI<Object, Object> cache2 = tl.cache2;
- ReplicationListener replListener1 = tl.replListener1;
- ReplicationListener replListener2 = tl.replListener2;
-
- CacheSPI<Object, Object> cache3 = null, cache4 = null;
- try {
- // TODO: fix this
-// tl.configuration.setClusterName("otherTest");
- cache3 = (CacheSPI<Object, Object>) new UnitTestCacheManager(tl.configuration).createCache("testCache");
- cache4 = (CacheSPI<Object, Object>) new UnitTestCacheManager(tl.configuration).createCache("testCache");
- replListener2.expectAny();
- cache1.put("age", 38);
- // because we use async repl, modfication may not yet have been propagated to cache2, so
- // we have to wait a little
- replListener2.waitForReplicationToOccur(500);
- assertNull("Should not have replicated", cache3.get("age"));
- }
- catch (Exception e) {
- fail(e.toString());
- }
- finally {
- if (cache3 != null) {
- cache3.stop();
- }
- if (cache4 != null) {
- cache4.stop();
- }
- }
- }
-
- public void testAsyncReplDelay() {
- Integer age;
- AsyncReplTestTL tl = threadLocal.get();
- CacheSPI<Object, Object> cache1 = tl.cache1;
- CacheSPI<Object, Object> cache2 = tl.cache2;
- ReplicationListener replListener1 = tl.replListener1;
- ReplicationListener replListener2 = tl.replListener2;
-
- try {
- cache1.put("age", 38);
-
- // value on cache2 may be 38 or not yet replicated
- age = (Integer) cache2.get("age");
- log("attr \"age\" of \"/a/b/c\" on cache2=" + age);
- assertTrue("should be either null or 38", age == null || age == 38);
- }
- catch (Exception e) {
- fail(e.toString());
- }
- }
-
- public void testAsyncReplTxDelay() {
- Integer age;
- AsyncReplTestTL tl = threadLocal.get();
- CacheSPI<Object, Object> cache1 = tl.cache1;
- CacheSPI<Object, Object> cache2 = tl.cache2;
- ReplicationListener replListener1 = tl.replListener1;
- ReplicationListener replListener2 = tl.replListener2;
-
- try {
- TransactionManager tm = cache1.getTransactionManager();
- tm.begin();
- cache1.put("age", 38);
- tm.commit();
-
- // value on cache2 may be 38 or not yet replicated
- age = (Integer) cache2.get("age");
- log("attr \"age\" of \"/a/b/c\" on cache2=" + age);
- assertTrue("should be either null or 38", age == null || age == 38);
- }
- catch (Exception e) {
- fail(e.toString());
- }
- }
-
- private void log(String msg) {
- System.out.println("-- [" + Thread.currentThread() + "]: " + msg);
- }
}
Modified: core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java 2009-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -7,7 +7,7 @@
package org.horizon.replication;
import static org.easymock.EasyMock.*;
-import org.horizon.BaseReplicatedTest;
+import org.horizon.BaseClusteredTest;
import org.horizon.Cache;
import org.horizon.commands.RPCCommand;
import org.horizon.config.Configuration;
@@ -32,7 +32,7 @@
* @author <a href="mailto:manik@jboss.org">Manik Surtani (manik(a)jboss.org)</a>
*/
@Test(groups = "functional", sequential = true)
-public class SyncReplTest extends BaseReplicatedTest {
+public class SyncReplTest extends BaseClusteredTest {
Cache cache1, cache2;
String k = "key", v = "value";
Deleted: core/branches/flat/src/test/java/org/horizon/util/internals/ReplicationListener.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/util/internals/ReplicationListener.java 2009-01-28 14:34:08 UTC (rev 7605)
+++ core/branches/flat/src/test/java/org/horizon/util/internals/ReplicationListener.java 2009-01-28 18:26:32 UTC (rev 7606)
@@ -1,254 +0,0 @@
-package org.horizon.util.internals;
-
-import org.horizon.Cache;
-import org.horizon.commands.ReplicableCommand;
-import org.horizon.commands.remote.ReplicateCommand;
-import org.horizon.commands.tx.CommitCommand;
-import org.horizon.commands.tx.PrepareCommand;
-import org.horizon.config.Configuration;
-import org.horizon.context.InvocationContext;
-import org.horizon.factories.ComponentRegistry;
-import org.horizon.io.ByteBuffer;
-import org.horizon.logging.Log;
-import org.horizon.logging.LogFactory;
-import org.horizon.marshall.HorizonMarshaller;
-import org.horizon.marshall.Marshaller;
-import org.horizon.remoting.RPCManager;
-import org.horizon.remoting.transport.jgroups.CommandAwareRpcDispatcher;
-import org.horizon.util.TestingUtil;
-import org.jgroups.blocks.RpcDispatcher;
-import org.jgroups.util.Buffer;
-
-import java.io.InputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-
-/*
-* Utility class that notifies when certain commands were asynchronously replicated on secondary cache.
- * Especially useful for avaoiding Thread.sleep() statements.
- * <p/>
- * Usage:
- * <pre>
- * Cache c1, c2; //these being two async caches
- * AsyncReplicationListener listener2 = new AsyncReplicationListener(c2);
- * listener2.expect(PutKeyValueCommand.class);
- * c1.put(fqn, key, value);
- * listener2.waitForReplicationToOccur(1000); // -this will block here untill c2 recieves the PutKeyValueCommand command
- * </pre>
- * Lifecycle - after being used (i.e. waitForReplicationToOccur returns sucessfully) the object returns to the
- * non-initialized state and *can* be reused through expect-wait cycle.
- * <b>Note</b>: this class might be used aswell for sync caches, e.g. a test could have subclasses which use sync and
- * async replication
- *
- * @author Mircea.Markus(a)jboss.com
- * @since 1.0
- */
-public class ReplicationListener {
- private CountDownLatch latch = new CountDownLatch(1);
- private Set<Class<? extends ReplicableCommand>> expectedCommands;
- Configuration configuration;
- private static final Log log = LogFactory.getLog(ReplicationListener.class);
-
- /**
- * Builds a listener that will observe the given cache for recieving replication commands.
- */
- public ReplicationListener(Cache cache) {
- ComponentRegistry componentRegistry = TestingUtil.extractComponentRegistry(cache);
- RPCManager rpcManager = componentRegistry.getComponent(RPCManager.class);
- CommandAwareRpcDispatcher realDispatcher = (CommandAwareRpcDispatcher) TestingUtil.extractField(rpcManager, "rpcDispatcher");
- RpcDispatcher.Marshaller2 realMarshaller = (RpcDispatcher.Marshaller2) realDispatcher.getMarshaller();
- RpcDispatcher.Marshaller2 delegate = null;
- delegate = new MarshallerDelegate(realMarshaller);
- realDispatcher.setMarshaller(delegate);
- realDispatcher.setRequestMarshaller(delegate);
- realDispatcher.setResponseMarshaller(delegate);
- configuration = cache.getConfiguration();
- }
-
- private class MarshallerDelegate implements RpcDispatcher.Marshaller2 {
- RpcDispatcher.Marshaller2 marshaller;
-
- private MarshallerDelegate(RpcDispatcher.Marshaller2 marshaller) {
- this.marshaller = marshaller;
- }
-
- public byte[] objectToByteBuffer(Object obj) throws Exception {
- return marshaller.objectToByteBuffer(obj);
- }
-
- public Object objectFromByteBuffer(byte bytes[]) throws Exception {
- Object result = marshaller.objectFromByteBuffer(bytes);
- if (result instanceof ReplicateCommand && expectedCommands != null) {
- ReplicateCommand replicateCommand = (ReplicateCommand) result;
- return new ReplicateCommandDelegate(replicateCommand);
- }
- return result;
- }
-
- public Buffer objectToBuffer(Object o) throws Exception {
- return marshaller.objectToBuffer(o);
- }
-
- public Object objectFromByteBuffer(byte[] bytes, int i, int i1) throws Exception {
- Object result = marshaller.objectFromByteBuffer(bytes, i, i1);
- if (result instanceof ReplicateCommand && expectedCommands != null) {
- ReplicateCommand replicateCommand = (ReplicateCommand) result;
- return new ReplicateCommandDelegate(replicateCommand);
- }
- return result;
- }
- }
-
- /**
- * We want the notification to be performed only *after* the remote command is executed.
- */
- private class ReplicateCommandDelegate extends ReplicateCommand {
- ReplicateCommand realOne;
-
- private ReplicateCommandDelegate(ReplicateCommand realOne) {
- this.realOne = realOne;
- }
-
- @Override
- public Object perform(InvocationContext ctx) throws Throwable {
- try {
- return realOne.perform(ctx);
- }
- finally {
- log.trace("Processed command: " + realOne);
- Iterator<Class<? extends ReplicableCommand>> it = expectedCommands.iterator();
- while (it.hasNext()) {
- Class<? extends ReplicableCommand> replicableCommandClass = it.next();
- if (realOne.containsCommandType(replicableCommandClass)) {
- it.remove();
- } else if (realOne.getSingleCommand() instanceof PrepareCommand) //explicit transaction
- {
- PrepareCommand prepareCommand = (PrepareCommand) realOne.getSingleCommand();
- if (prepareCommand.containsModificationType(replicableCommandClass)) {
- it.remove();
- }
- }
- }
- if (expectedCommands.isEmpty()) {
- latch.countDown();
- }
- }
- }
- }
-
- /**
- * Needed for region based marshalling.
- */
- private class RegionMarshallerDelegate extends HorizonMarshaller {
- private Marshaller realOne;
-
- private RegionMarshallerDelegate(Marshaller realOne) {
- this.realOne = realOne;
- }
-
- @Override
- public void objectToObjectStream(Object obj, ObjectOutputStream out) throws Exception {
- realOne.objectToObjectStream(obj, out);
- }
-
- @Override
- public Object objectFromObjectStream(ObjectInputStream in) throws Exception {
- return realOne.objectFromObjectStream(in);
- }
-
- @Override
- public Object objectFromStream(InputStream is) throws Exception {
- return realOne.objectFromStream(is);
- }
-
- public Object objectFromByteBuffer(byte[] bytes) throws Exception {
- return this.objectFromByteBuffer(bytes, 0, bytes.length);
- }
-
-
- public ByteBuffer objectToBuffer(Object o) throws Exception {
- return realOne.objectToBuffer(o);
- }
-
- public Object objectFromByteBuffer(byte[] buffer, int i, int i1) throws Exception {
- Object result = realOne.objectFromByteBuffer(buffer, i, i1);
- if (result instanceof ReplicateCommand && expectedCommands != null) {
- ReplicateCommand replicateCommand = (ReplicateCommand) result;
- result = new ReplicateCommandDelegate(replicateCommand);
- }
- return result;
- }
- }
-
- /**
- * Waits for 1 minute
- */
- public void waitForReplicationToOccur() {
- waitForReplicationToOccur(60000);
- }
-
- /**
- * Blocks for the elements specified through {@link #expect(Class[])} invocations to be replicated in this cache. if
- * replication does not occur in the give timeout then an exception is being thrown.
- */
- public void waitForReplicationToOccur(long timeoutMillis) {
- log.trace("enter... ReplicationListener.waitForReplicationToOccur");
- waitForReplicationToOccur(timeoutMillis, TimeUnit.MILLISECONDS);
- log.trace("exit... ReplicationListener.waitForReplicationToOccur");
- }
-
- /**
- * Similar to {@link #waitForReplicationToOccur(long)} except that this method provides more flexibility in time
- * units.
- *
- * @param timeout the maximum time to wait
- * @param timeUnit the time unit of the <tt>timeout</tt> argument.
- */
- public void waitForReplicationToOccur(long timeout, TimeUnit timeUnit) {
- assert expectedCommands != null : "there are no replication expectations; please use AsyncReplicationListener.expect(...) before calling this method";
- try {
- if (!latch.await(timeout, timeUnit)) {
- assert false : "waiting for more than " + timeout + " " + timeUnit + " and following commands did not replicate: " + expectedCommands;
- }
- }
- catch (InterruptedException e) {
- throw new IllegalStateException("unexpected", e);
- }
- finally {
- expectedCommands = null;
- latch = new CountDownLatch(1);
- }
- }
-
- /**
- * {@link #waitForReplicationToOccur(long)} will block untill all the commands specified here are being replicated to
- * this cache. The method can be called several times with various arguments.
- */
- public void expect(Class<? extends ReplicableCommand>... expectedCommands) {
- if (this.expectedCommands == null) {
- this.expectedCommands = new HashSet<Class<? extends ReplicableCommand>>();
- }
- this.expectedCommands.addAll(Arrays.asList(expectedCommands));
- }
-
- /**
- * Waits untill first command is replicated.
- */
- public void expectAny() {
- expect();
- }
-
- public void expectWithTx(Class<? extends ReplicableCommand>... writeCommands) {
- expect(PrepareCommand.class);
- //this is because for async replication we have an 1pc transaction
- if (configuration.getCacheMode().isSynchronous()) expect(CommitCommand.class);
- }
-
-}
\ No newline at end of file
15 years, 11 months
JBoss Cache SVN: r7605 - in core/branches/flat/src: main/java/org/horizon/commands and 15 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2009-01-28 09:34:08 -0500 (Wed, 28 Jan 2009)
New Revision: 7605
Added:
core/branches/flat/src/main/java/org/horizon/commands/RPCCommand.java
core/branches/flat/src/test/java/org/horizon/BaseReplicatedTest.java
Modified:
core/branches/flat/src/main/java/org/horizon/cluster/ReplicationQueue.java
core/branches/flat/src/main/java/org/horizon/commands/CommandsFactoryImpl.java
core/branches/flat/src/main/java/org/horizon/commands/RemoteCommandFactory.java
core/branches/flat/src/main/java/org/horizon/commands/ReplicableCommand.java
core/branches/flat/src/main/java/org/horizon/commands/read/SizeCommand.java
core/branches/flat/src/main/java/org/horizon/commands/remote/ReplicateCommand.java
core/branches/flat/src/main/java/org/horizon/commands/write/PutKeyValueCommand.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/ReadCommittedEntry.java
core/branches/flat/src/main/java/org/horizon/container/UnsortedDataContainer.java
core/branches/flat/src/main/java/org/horizon/factories/ComponentRegistry.java
core/branches/flat/src/main/java/org/horizon/factories/EmptyConstructorFactory.java
core/branches/flat/src/main/java/org/horizon/factories/GlobalComponentRegistry.java
core/branches/flat/src/main/java/org/horizon/interceptors/InvalidationInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/base/BaseRpcInterceptor.java
core/branches/flat/src/main/java/org/horizon/manager/DefaultCacheManager.java
core/branches/flat/src/main/java/org/horizon/marshall/HorizonMarshaller.java
core/branches/flat/src/main/java/org/horizon/marshall/VersionAwareMarshaller.java
core/branches/flat/src/main/java/org/horizon/remoting/InboundInvocationHandler.java
core/branches/flat/src/main/java/org/horizon/remoting/InboundInvocationHandlerImpl.java
core/branches/flat/src/main/java/org/horizon/remoting/RPCManager.java
core/branches/flat/src/main/java/org/horizon/remoting/RPCManagerImpl.java
core/branches/flat/src/main/java/org/horizon/remoting/transport/Transport.java
core/branches/flat/src/test/java/org/horizon/BasicTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java
core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java
core/branches/flat/src/test/java/org/horizon/util/internals/ReplicationListener.java
Log:
replication code + tests on shared transport
Modified: core/branches/flat/src/main/java/org/horizon/cluster/ReplicationQueue.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/cluster/ReplicationQueue.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/cluster/ReplicationQueue.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -22,6 +22,7 @@
package org.horizon.cluster;
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;
@@ -60,7 +61,7 @@
/**
* Holds the replication jobs: LinkedList<MethodCall>
*/
- final List<ReplicableCommand> elements = new LinkedList<ReplicableCommand>();
+ final List<RPCCommand> elements = new LinkedList<RPCCommand>();
/**
* For periodical replication
@@ -128,7 +129,7 @@
/**
* Adds a new method call.
*/
- public void add(ReplicateCommand job) {
+ public void add(RPCCommand job) {
if (job == null)
throw new NullPointerException("job is null");
synchronized (elements) {
Modified: core/branches/flat/src/main/java/org/horizon/commands/CommandsFactoryImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/CommandsFactoryImpl.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/commands/CommandsFactoryImpl.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -21,6 +21,7 @@
*/
package org.horizon.commands;
+import org.horizon.CacheSPI;
import org.horizon.commands.read.GetKeyValueCommand;
import org.horizon.commands.read.SizeCommand;
import org.horizon.commands.remote.ReplicateCommand;
@@ -36,7 +37,6 @@
import org.horizon.commands.write.ReplaceCommand;
import org.horizon.container.DataContainer;
import org.horizon.factories.annotations.Inject;
-import org.horizon.interceptors.InterceptorChain;
import org.horizon.notifications.CacheNotifier;
import org.horizon.remoting.transport.Address;
import org.horizon.transaction.GlobalTransaction;
@@ -51,13 +51,16 @@
public class CommandsFactoryImpl implements CommandsFactory {
private DataContainer dataContainer;
private CacheNotifier notifier;
- private InterceptorChain interceptorChain;
+ private CacheSPI cache;
+ // some stateless commands can be reused so that they aren't constructed again all the time.
+ SizeCommand cachedSizeCommand;
+
@Inject
- public void setupDependencies(DataContainer container, CacheNotifier notifier, InterceptorChain interceptorChain) {
+ public void setupDependencies(DataContainer container, CacheNotifier notifier, CacheSPI cache) {
this.dataContainer = container;
this.notifier = notifier;
- this.interceptorChain = interceptorChain;
+ this.cache = cache;
}
public PutKeyValueCommand buildPutKeyValueCommand(Object key, Object value) {
@@ -73,7 +76,10 @@
}
public SizeCommand buildSizeCommand() {
- return new SizeCommand(dataContainer);
+ if (cachedSizeCommand == null) {
+ cachedSizeCommand = new SizeCommand(dataContainer);
+ }
+ return cachedSizeCommand;
}
public GetKeyValueCommand buildGetKeyValueCommand(Object key) {
@@ -107,11 +113,11 @@
}
public ReplicateCommand buildReplicateCommand(List<ReplicableCommand> toReplicate) {
- return new ReplicateCommand(toReplicate);
+ return new ReplicateCommand(toReplicate, cache.getName());
}
public ReplicateCommand buildReplicateCommand(ReplicableCommand call) {
- return new ReplicateCommand(call);
+ return new ReplicateCommand(call, cache.getName());
}
public void initializeReplicableCommand(ReplicableCommand c) {
@@ -126,13 +132,10 @@
case RemoveCommand.METHOD_ID:
((RemoveCommand) c).init(notifier);
break;
- case ReplicateCommand.MULTIPLE_METHOD_ID:
- case ReplicateCommand.SINGLE_METHOD_ID:
+ case ReplicateCommand.METHOD_ID:
ReplicateCommand rc = (ReplicateCommand) c;
- if (rc.getModifications() != null)
- for (ReplicableCommand nested : rc.getModifications()) initializeReplicableCommand(nested);
- initializeReplicableCommand(rc.getSingleModification());
- rc.initialize(interceptorChain);
+ if (rc.getCommands() != null)
+ for (ReplicableCommand nested : rc.getCommands()) initializeReplicableCommand(nested);
break;
case PrepareCommand.METHOD_ID:
PrepareCommand pc = (PrepareCommand) c;
Added: core/branches/flat/src/main/java/org/horizon/commands/RPCCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/RPCCommand.java (rev 0)
+++ core/branches/flat/src/main/java/org/horizon/commands/RPCCommand.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -0,0 +1,67 @@
+package org.horizon.commands;
+
+import org.horizon.interceptors.InterceptorChain;
+
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * The RPCManager only replicates commands wrapped in an RPCCommand. As a wrapper, an RPCCommand could contain a single
+ * {@link org.horizon.commands.ReplicableCommand} or a List of them.
+ *
+ * @author Manik Surtani
+ * @since 1.0
+ */
+public interface RPCCommand extends ReplicableCommand {
+
+ /**
+ * @return true if this only wraps a single ReplicableCommand. False if it wraps more than one.
+ */
+ boolean isSingleCommand();
+
+ /**
+ * A convenience method if there is only a single command being transported, i.e., if {@link #isSingleCommand()} is
+ * true. If {@link #isSingleCommand()} is false, this method throws a {@link IllegalStateException} so it should
+ * only be used after testing {@link #isSingleCommand()}.
+ *
+ * @return a single ReplicableCommand.
+ */
+ ReplicableCommand getSingleCommand();
+
+ /**
+ * A more generic mechanism to get a hold of the commands wrapped. Even if {@link #isSingleCommand()} is true, this
+ * command returns a valid and usable List.
+ *
+ * @return a list of all commands.
+ */
+ List<ReplicableCommand> getCommands();
+
+ /**
+ * Adds a single command to the list of commands being wrapped
+ *
+ * @param command command to add
+ */
+ void addCommand(ReplicableCommand command);
+
+ /**
+ * Adds a collection of commands to the list of commands being wrapped
+ *
+ * @param commands commands to add
+ */
+ void addCommands(Collection<? extends ReplicableCommand> commands);
+
+ /**
+ * @return the name of the cache that produced this command. This will also be the name of the cache this command is
+ * intended for.
+ */
+ String getCacheName();
+
+ void setCacheName(String name);
+
+ /**
+ * Sets the interceptor chain on which to invoke the command.
+ *
+ * @param interceptorChain chain to invoke command on
+ */
+ void setInterceptorChain(InterceptorChain interceptorChain);
+}
Modified: core/branches/flat/src/main/java/org/horizon/commands/RemoteCommandFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/RemoteCommandFactory.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/commands/RemoteCommandFactory.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -61,8 +61,7 @@
case RollbackCommand.METHOD_ID:
command = new RollbackCommand();
break;
- case ReplicateCommand.MULTIPLE_METHOD_ID:
- case ReplicateCommand.SINGLE_METHOD_ID:
+ case ReplicateCommand.METHOD_ID:
command = new ReplicateCommand();
break;
Modified: core/branches/flat/src/main/java/org/horizon/commands/ReplicableCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/ReplicableCommand.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/commands/ReplicableCommand.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -25,7 +25,7 @@
/**
* The core of the command-based cache framework. Commands correspond to specific areas of functionality in the cache,
- * and can be replicated using the {@link org.horizon.marshall.Marshaller} framework.
+ * and can be replicated using the {@link org.horizon.remoting.RPCManager}
*
* @author Mircea.Markus(a)jboss.com
* @author Manik Surtani
Modified: core/branches/flat/src/main/java/org/horizon/commands/read/SizeCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/read/SizeCommand.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/commands/read/SizeCommand.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -27,7 +27,7 @@
import org.horizon.context.InvocationContext;
/**
- * // TODO: MANIK: Document this
+ * Command to calculate the size of the cache
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
* @since 1.0
@@ -58,4 +58,11 @@
public void setParameters(int commandId, Object[] parameters) {
// no-op
}
+
+ @Override
+ public String toString() {
+ return "SizeCommand{" +
+ "containerSize=" + container.size() +
+ '}';
+ }
}
Modified: core/branches/flat/src/main/java/org/horizon/commands/remote/ReplicateCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/remote/ReplicateCommand.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/commands/remote/ReplicateCommand.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -21,6 +21,7 @@
*/
package org.horizon.commands.remote;
+import org.horizon.commands.RPCCommand;
import org.horizon.commands.ReplicableCommand;
import org.horizon.commands.VisitableCommand;
import org.horizon.context.InvocationContext;
@@ -29,11 +30,12 @@
import org.horizon.logging.LogFactory;
import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
import java.util.List;
/**
- * Command that implements cluster replication logic. Essentially mimics the replicate() and replicateAll() methods in
- * 2.1.x, we may need to revisit the usefulness of such a command.
+ * Command that implements cluster replication logic.
* <p/>
* This is not a {@link VisitableCommand} and hence not passed up the {@link org.horizon.interceptors.base.CommandInterceptor}
* chain.
@@ -42,52 +44,38 @@
* @author Mircea.Markus(a)jboss.com
* @since 1.0
*/
-public class ReplicateCommand implements ReplicableCommand {
- public static final byte SINGLE_METHOD_ID = 13;
- public static final byte MULTIPLE_METHOD_ID = 14;
+public class ReplicateCommand implements RPCCommand {
+ public static final byte METHOD_ID = 13;
- private InterceptorChain invoker;
+ private InterceptorChain interceptorChain;
private static final Log log = LogFactory.getLog(ReplicateCommand.class);
private static final boolean trace = log.isTraceEnabled();
- /**
- * optimisation - rather than constructing a new list each for scenarios where a single modification needs to be
- * replicated rather use this instance.
- */
- private ReplicableCommand singleModification;
- private List<ReplicableCommand> modifications;
+ private List<ReplicableCommand> commands;
+ private String cacheName;
- public ReplicateCommand(List<ReplicableCommand> modifications) {
+ public ReplicateCommand(List<ReplicableCommand> modifications, String cacheName) {
if (modifications != null && modifications.size() == 1) {
- singleModification = modifications.get(0);
+ this.commands = Collections.singletonList(modifications.get(0));
} else {
- this.modifications = modifications;
+ this.commands = modifications;
}
+ this.cacheName = cacheName;
}
- public ReplicateCommand(ReplicableCommand command) {
- this.singleModification = command;
+ public ReplicateCommand(ReplicableCommand command, String cacheName) {
+ commands = Collections.singletonList(command);
+ this.cacheName = cacheName;
}
public ReplicateCommand() {
}
- public void initialize(InterceptorChain interceptorChain) {
- this.invoker = interceptorChain;
+ public void setInterceptorChain(InterceptorChain interceptorChain) {
+ this.interceptorChain = interceptorChain;
}
- public void setSingleModification(ReplicableCommand singleModification) {
- this.singleModification = singleModification;
- }
-
- public void setModifications(List<ReplicableCommand> modifications) {
- if (modifications != null && modifications.size() == 1)
- singleModification = modifications.get(0);
- else
- this.modifications = modifications;
- }
-
/**
* Executes commands replicated to the current cache instance by other cache instances.
*
@@ -97,21 +85,21 @@
*/
public Object perform(InvocationContext ctx) throws Throwable {
if (isSingleCommand()) {
- return processSingleCommand(singleModification);
+ return processCommand(ctx, commands.get(0));
} else {
- for (ReplicableCommand command : modifications) processSingleCommand(command);
+ for (ReplicableCommand command : commands) processCommand(ctx, command);
return null;
}
}
- private Object processSingleCommand(ReplicableCommand cacheCommand)
+ private Object processCommand(InvocationContext ctx, ReplicableCommand cacheCommand)
throws Throwable {
Object result;
try {
if (trace) log.trace("Invoking command " + cacheCommand + ", with originLocal flag set to false.");
-
+ ctx.setOriginLocal(false);
if (cacheCommand instanceof VisitableCommand) {
- Object retVal = invoker.invokeRemote((VisitableCommand) cacheCommand);
+ Object retVal = interceptorChain.invokeRemote((VisitableCommand) cacheCommand);
// we only need to return values for a set of remote calls; not every call.
if (returnValueForRemoteCall(cacheCommand)) {
result = retVal;
@@ -119,7 +107,8 @@
result = null;
}
} else {
- result = cacheCommand.perform(null);
+ throw new RuntimeException("Do we still need to deal with non-visitable commands?");
+// result = cacheCommand.perform(null);
}
}
catch (Throwable ex) {
@@ -143,35 +132,57 @@
}
public byte getCommandId() {
- return isSingleCommand() ? SINGLE_METHOD_ID : MULTIPLE_METHOD_ID;
+ return METHOD_ID;
}
- public List<ReplicableCommand> getModifications() {
- return modifications;
+ public List<ReplicableCommand> getCommands() {
+ return commands;
}
- public ReplicableCommand getSingleModification() {
- return singleModification;
+ public void addCommand(ReplicableCommand command) {
+ if (commands == null) {
+ commands = Collections.singletonList(command);
+ } else {
+ upgradeCommandsListIfNeeded();
+ commands.add(command);
+ }
}
+ public void addCommands(Collection<? extends ReplicableCommand> commands) {
+ upgradeCommandsListIfNeeded();
+ this.commands.addAll(commands);
+ }
+
+ private void upgradeCommandsListIfNeeded() {
+ if (!(commands instanceof ArrayList)) {
+ commands = new ArrayList<ReplicableCommand>(commands);
+ }
+ }
+
+ public String getCacheName() {
+ return cacheName;
+ }
+
+ public void setCacheName(String name) {
+ this.cacheName = cacheName;
+ }
+
+ public ReplicableCommand getSingleCommand() {
+ return commands.get(0);
+ }
+
public Object[] getParameters() {
- if (isSingleCommand())
- return new Object[]{singleModification};
- else
- return new Object[]{modifications};
+ return new Object[]{cacheName, commands};
}
@SuppressWarnings("unchecked")
public void setParameters(int commandId, Object[] args) {
- if (commandId == SINGLE_METHOD_ID) {
- singleModification = (ReplicableCommand) args[0];
- } else {
- modifications = (List<ReplicableCommand>) args[0];
- }
+ cacheName = (String) args[0];
+ commands = (List<ReplicableCommand>) args[1];
}
public boolean isSingleCommand() {
- return singleModification != null;
+ return commands != null && commands.size() == 1;
}
@Override
@@ -181,28 +192,14 @@
ReplicateCommand that = (ReplicateCommand) o;
- if (modifications != null ? !modifications.equals(that.modifications) : that.modifications != null) return false;
- if (singleModification != null ? !singleModification.equals(that.singleModification) : that.singleModification != null)
- return false;
-
- return true;
+ return !(commands != null ? !commands.equals(that.commands) : that.commands != null);
}
@Override
public int hashCode() {
- int result;
- result = (singleModification != null ? singleModification.hashCode() : 0);
- result = 31 * result + (modifications != null ? modifications.hashCode() : 0);
- return result;
+ return commands != null ? commands.hashCode() : 0;
}
- @Override
- public String toString() {
- return "ReplicateCommand{" +
- "cmds=" + (isSingleCommand() ? singleModification : modifications) +
- '}';
- }
-
/**
* Creates a copy of this command, amking a deep copy of any collections but everything else copied shallow.
*
@@ -211,20 +208,32 @@
public ReplicateCommand copy() {
ReplicateCommand clone;
clone = new ReplicateCommand();
- clone.invoker = invoker;
- clone.modifications = modifications == null ? null : new ArrayList<ReplicableCommand>(modifications);
- clone.singleModification = singleModification;
+ clone.interceptorChain = interceptorChain;
+ if (commands != null) {
+ if (commands.size() == 1)
+ clone.commands = Collections.singletonList(commands.get(0));
+ else
+ clone.commands = new ArrayList<ReplicableCommand>(commands);
+ }
return clone;
}
public boolean containsCommandType(Class<? extends ReplicableCommand> aClass) {
- if (isSingleCommand()) {
- return getSingleModification().getClass().equals(aClass);
+ if (commands.size() == 1) {
+ return commands.get(0).getClass().equals(aClass);
} else {
- for (ReplicableCommand command : getModifications()) {
+ for (ReplicableCommand command : getCommands()) {
if (command.getClass().equals(aClass)) return true;
}
}
return false;
}
+
+ @Override
+ public String toString() {
+ return "ReplicateCommand{" +
+ "commands=" + commands +
+ ", cacheName='" + cacheName + '\'' +
+ '}';
+ }
}
\ No newline at end of file
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-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/commands/write/PutKeyValueCommand.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -71,7 +71,9 @@
public Object perform(InvocationContext ctx) throws Throwable {
Object o = null;
MVCCEntry e = ctx.lookupEntry(key);
- if (e.getValue() == null || !putIfAbsent) {
+ if (e.getValue() != null && putIfAbsent) {
+ return e.getValue();
+ } else {
notifier.notifyCacheEntryModified(key, true, ctx);
if (value instanceof Delta) {
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-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/commands/write/RemoveCommand.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -57,13 +57,15 @@
public Object perform(InvocationContext ctx) throws Throwable {
MVCCEntry e = ctx.lookupEntry(key);
- if (e == null || e.isNullEntry()) return null;
+ if (e == null || e.isNullEntry()) return value == null ? null : false;
+ if (value != null && e.getValue() != null && !e.getValue().equals(value))
+ return false;
+
notifier.notifyCacheEntryRemoved(key, true, ctx);
e.setDeleted(true);
e.setValid(false);
notifier.notifyCacheEntryRemoved(key, false, ctx);
- return e.getValue();
-
+ return value == null ? e.getValue() : true;
}
public byte getCommandId() {
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-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/commands/write/ReplaceCommand.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -50,14 +50,14 @@
return visitor.visitReplaceCommand(ctx, this);
}
- public Boolean perform(InvocationContext ctx) throws Throwable {
+ public Object perform(InvocationContext ctx) throws Throwable {
MVCCEntry e = ctx.lookupEntry(key);
- if (e == null || e.isNullEntry()) return false;
+ if (e == null || e.isNullEntry()) return oldValue == null ? null : false;
if (oldValue == null || oldValue.equals(e.getValue())) {
- e.setValue(newValue);
- return true;
+ Object old = e.setValue(newValue);
+ return oldValue == null ? old : true;
}
- return false;
+ return oldValue == null ? null : false;
}
public byte getCommandId() {
Modified: core/branches/flat/src/main/java/org/horizon/container/ReadCommittedEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/container/ReadCommittedEntry.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/container/ReadCommittedEntry.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -59,7 +59,9 @@
}
public Object setValue(Object value) {
- return this.value = value;
+ Object oldValue = this.value;
+ this.value = value;
+ return oldValue;
}
protected static enum Flags {
Modified: core/branches/flat/src/main/java/org/horizon/container/UnsortedDataContainer.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/container/UnsortedDataContainer.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/container/UnsortedDataContainer.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -21,33 +21,47 @@
*/
package org.horizon.container;
+import java.util.AbstractSet;
+import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
- * // TODO: crappy and inefficient - but just a placeholder for now.
+ * The basic container. Accepts null keys.
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
* @since 1.0
*/
public class UnsortedDataContainer<K, V> implements DataContainer<K, V> {
- private final ConcurrentMap<K, V> data = new ConcurrentHashMap<K, V>();
+ private final ConcurrentMap<Object, Object> data = new ConcurrentHashMap<Object, Object>();
+ private static final Object NULL = new Object();
+ @SuppressWarnings("unchecked")
+ private Object maskNull(Object o) {
+ return o == null ? (K) NULL : (K) o;
+ }
+
+ private Object unmaskNull(Object o) {
+ return (o == NULL) ? null : o;
+ }
+
+ @SuppressWarnings("unchecked")
public V get(K k) {
- return data.get(k);
+ return (V) unmaskNull(data.get(maskNull(k)));
}
public void put(K k, V v) {
- data.put(k, v);
+ data.put(maskNull(k), maskNull(v));
}
public boolean containsKey(K k) {
- return data.containsKey(k);
+ return data.containsKey(maskNull(k));
}
+ @SuppressWarnings("unchecked")
public V remove(K k) {
- return data.remove(k);
+ return (V) unmaskNull(data.remove(maskNull(k)));
}
public int size() {
@@ -59,7 +73,7 @@
}
public Set<K> keySet() {
- return data.keySet();
+ return new KeySet();
}
public boolean evict(Object key) {
@@ -69,4 +83,53 @@
public String toString() {
return data.toString();
}
+
+ private class KeySet extends AbstractSet<K> {
+ Set<Object> realSet;
+
+ public KeySet() {
+ this.realSet = data.keySet();
+ }
+
+ public Iterator<K> iterator() {
+ return new KeyIterator(realSet.iterator());
+ }
+
+ public void clear() {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean contains(Object o) {
+ return realSet.contains(maskNull(o));
+ }
+
+ public boolean remove(Object o) {
+ throw new UnsupportedOperationException();
+ }
+
+ public int size() {
+ return realSet.size();
+ }
+ }
+
+ private class KeyIterator implements Iterator<K> {
+ Iterator<Object> realIterator;
+
+ private KeyIterator(Iterator<Object> realIterator) {
+ this.realIterator = realIterator;
+ }
+
+ public boolean hasNext() {
+ return realIterator.hasNext();
+ }
+
+ @SuppressWarnings("unchecked")
+ public K next() {
+ return (K) unmaskNull(realIterator.next());
+ }
+
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/ComponentRegistry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/ComponentRegistry.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/factories/ComponentRegistry.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -13,7 +13,7 @@
import java.util.Map;
/**
- * // TODO: Manik: Document this!
+ * Named cache specific components
*
* @author Manik Surtani
* @since 1.0
@@ -43,8 +43,6 @@
registerComponent(this, ComponentRegistry.class);
registerComponent(configuration, Configuration.class);
registerComponent(new BootstrapFactory(cache, configuration, this), BootstrapFactory.class);
-
- globalComponents.registerNamedComponentRegistry(this, cacheName);
}
catch (Exception e) {
throw new CacheException("Unable to construct a ComponentRegistry!", e);
@@ -103,5 +101,12 @@
globalComponents.start();
}
super.start();
+ globalComponents.registerNamedComponentRegistry(this, cacheName);
}
+
+ @Override
+ public void stop() {
+ if (state.stopAllowed()) globalComponents.unregisterNamedComponentRegistry(cacheName);
+ super.stop();
+ }
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/EmptyConstructorFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/EmptyConstructorFactory.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/factories/EmptyConstructorFactory.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -1,19 +1,23 @@
package org.horizon.factories;
+import org.horizon.commands.RemoteCommandFactory;
import org.horizon.config.ConfigurationException;
import org.horizon.factories.annotations.DefaultFactoryFor;
+import org.horizon.factories.scopes.Scope;
+import org.horizon.factories.scopes.Scopes;
import org.horizon.marshall.Marshaller;
import org.horizon.marshall.VersionAwareMarshaller;
import org.horizon.notifications.CacheManagerNotifier;
import org.horizon.remoting.InboundInvocationHandler;
/**
- * // TODO: Manik: Document this!
+ * Factory for building global-scope components which have default empty constructors
*
* @author Manik Surtani
* @since 1.0
*/
-@DefaultFactoryFor(classes = {InboundInvocationHandler.class, CacheManagerNotifier.class, Marshaller.class})
+@DefaultFactoryFor(classes = {InboundInvocationHandler.class, CacheManagerNotifier.class, Marshaller.class, RemoteCommandFactory.class})
+(a)Scope(Scopes.GLOBAL)
public class EmptyConstructorFactory extends AbstractComponentFactory implements AutoInstantiableFactory {
public <T> T construct(Class<T> componentType) {
try {
Modified: core/branches/flat/src/main/java/org/horizon/factories/GlobalComponentRegistry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/GlobalComponentRegistry.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/factories/GlobalComponentRegistry.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -15,7 +15,7 @@
import java.util.ArrayList;
/**
- * // TODO: Manik: Document this!
+ * A global component registry where shared components are stored.
*
* @author Manik Surtani
* @since 1.0
@@ -25,6 +25,7 @@
public class GlobalComponentRegistry extends AbstractComponentRegistry {
private Log log = LogFactory.getLog(GlobalComponentRegistry.class);
+ private static final String NAMED_REGISTRY_PREFIX = "NamedComponentRegistry:";
/**
* Hook to shut down the cache when the JVM exits.
*/
@@ -96,10 +97,14 @@
}
public ComponentRegistry getNamedComponentRegistry(String name) {
- return getComponent(ComponentRegistry.class, name);
+ return getComponent(ComponentRegistry.class, NAMED_REGISTRY_PREFIX + name);
}
public void registerNamedComponentRegistry(ComponentRegistry componentRegistry, String name) {
- registerComponent(componentRegistry, name);
+ registerComponent(componentRegistry, NAMED_REGISTRY_PREFIX + name);
}
+
+ public void unregisterNamedComponentRegistry(String name) {
+ componentLookup.remove(NAMED_REGISTRY_PREFIX + name);
+ }
}
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/InvalidationInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/InvalidationInterceptor.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/InvalidationInterceptor.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -134,7 +134,7 @@
if (tx == null || !TransactionTable.isValid(tx)) {
// the no-tx case:
//replicate an evict call.
- invalidateAcrossCluster(key, null, isSynchronous(optionOverride), ctx);
+ invalidateAcrossCluster(key, isSynchronous(optionOverride), ctx);
} else {
if (isLocalModeForced(ctx)) ctx.getTransactionContext().addLocalModification(command);
}
@@ -152,7 +152,7 @@
log.debug("Modification list contains a putForExternalRead operation. Not invalidating.");
} else {
try {
- for (Object key : filterVisitor.result) invalidateAcrossCluster(key, null, defaultSynchronous, ctx);
+ for (Object key : filterVisitor.result) invalidateAcrossCluster(key, defaultSynchronous, ctx);
}
catch (Throwable t) {
log.warn("Unable to broadcast evicts as a part of the prepare phase. Rolling back.", t);
@@ -193,7 +193,7 @@
}
- protected void invalidateAcrossCluster(Object fqn, Object workspace, boolean synchronous, InvocationContext ctx) throws Throwable {
+ protected void invalidateAcrossCluster(Object fqn, boolean synchronous, InvocationContext ctx) throws Throwable {
if (!isLocalModeForced(ctx)) {
// increment invalidations counter if statistics maintained
incrementInvalidations();
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-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/base/BaseRpcInterceptor.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -23,6 +23,7 @@
import org.horizon.cluster.ReplicationQueue;
import org.horizon.commands.CommandsFactory;
+import org.horizon.commands.RPCCommand;
import org.horizon.commands.ReplicableCommand;
import org.horizon.config.Option;
import org.horizon.context.InvocationContext;
@@ -82,15 +83,23 @@
}
}
- protected void replicateCall(InvocationContext ctx, ReplicableCommand call, boolean sync, Option o, boolean useOutOfBandMessage) throws Throwable {
+ protected void replicateCall(InvocationContext ctx, RPCCommand call, boolean sync, Option o, boolean useOutOfBandMessage) throws Throwable {
replicateCall(ctx, null, call, sync, o, useOutOfBandMessage);
}
- protected void replicateCall(InvocationContext ctx, ReplicableCommand call, boolean sync, Option o) throws Throwable {
+ protected void replicateCall(InvocationContext ctx, ReplicableCommand call, boolean sync, Option o, boolean useOutOfBandMessage) throws Throwable {
+ replicateCall(ctx, null, commandsFactory.buildReplicateCommand(call), sync, o, useOutOfBandMessage);
+ }
+
+ protected void replicateCall(InvocationContext ctx, RPCCommand call, boolean sync, Option o) throws Throwable {
replicateCall(ctx, null, call, sync, o, false);
}
- protected void replicateCall(InvocationContext ctx, List<Address> recipients, ReplicableCommand c, boolean sync, Option o, boolean useOutOfBandMessage) throws Throwable {
+ protected void replicateCall(InvocationContext ctx, ReplicableCommand call, boolean sync, Option o) throws Throwable {
+ replicateCall(ctx, null, commandsFactory.buildReplicateCommand(call), sync, o, false);
+ }
+
+ protected void replicateCall(InvocationContext ctx, List<Address> recipients, RPCCommand c, boolean sync, Option o, boolean useOutOfBandMessage) throws Throwable {
long syncReplTimeout = configuration.getSyncReplTimeout();
// test for option overrides
@@ -111,15 +120,15 @@
}
}
- replicateCall(recipients, c, sync, true, useOutOfBandMessage, false, syncReplTimeout);
+ replicateCall(recipients, c, sync, useOutOfBandMessage, syncReplTimeout);
}
- protected void replicateCall(List<Address> recipients, ReplicableCommand call, boolean sync, boolean wrapCacheCommandInReplicateMethod, boolean useOutOfBandMessage, boolean isBroadcast, long timeout) throws Throwable {
+ protected void replicateCall(List<Address> recipients, RPCCommand call, boolean sync, boolean useOutOfBandMessage, long timeout) throws Throwable {
if (trace) log.trace("Broadcasting call " + call + " to recipient list " + recipients);
if (!sync && replicationQueue != null) {
if (log.isDebugEnabled()) log.debug("Putting call " + call + " on the replication queue.");
- replicationQueue.add(commandsFactory.buildReplicateCommand(call));
+ replicationQueue.add(call);
} else {
List<Address> callRecipients = recipients;
if (callRecipients == null) {
@@ -128,10 +137,8 @@
log.trace("Setting call recipients to " + callRecipients + " since the original list of recipients passed in is null.");
}
- ReplicableCommand toCall = wrapCacheCommandInReplicateMethod ? commandsFactory.buildReplicateCommand(call) : call;
-
List rsps = rpcManager.invokeRemotely(callRecipients,
- toCall,
+ call,
sync ? ResponseMode.SYNCHRONOUS : ResponseMode.ASYNCHRONOUS, // is synchronised?
timeout,
useOutOfBandMessage
Modified: core/branches/flat/src/main/java/org/horizon/manager/DefaultCacheManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/manager/DefaultCacheManager.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/manager/DefaultCacheManager.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -41,7 +41,6 @@
import java.io.IOException;
import java.io.InputStream;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -265,7 +264,7 @@
throw new NullPointerException("Null arguments not allowed");
if (cacheName.equals(DEFAULT_CACHE_NAME))
throw new IllegalArgumentException("Cache name cannot be used as it is a reserved, internal name");
- if (configurationOverrides.putIfAbsent(cacheName, configurationOverride) != null)
+ if (configurationOverrides.putIfAbsent(cacheName, configurationOverride.clone()) != null)
throw new DuplicateCacheNameException("Cache name [" + cacheName + "] already in use!");
}
@@ -307,11 +306,9 @@
return globalConfiguration.getClusterName();
}
- @SuppressWarnings("unchecked")
public List<Address> getMembers() {
RPCManager rpcManager = globalComponentRegistry.getComponent(RPCManager.class);
- List l = rpcManager == null ? Collections.emptyList() : rpcManager.getMembers();
- return l;
+ return rpcManager == null ? null : rpcManager.getMembers();
}
public Address getAddress() {
Modified: core/branches/flat/src/main/java/org/horizon/marshall/HorizonMarshaller.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/HorizonMarshaller.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/marshall/HorizonMarshaller.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -38,7 +38,6 @@
import org.jboss.util.stream.MarshalledValueInputStream;
import java.io.ByteArrayInputStream;
-import java.io.Externalizable;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
@@ -55,38 +54,32 @@
*/
public class HorizonMarshaller implements Marshaller {
// magic numbers
- protected static final int MAGICNUMBER_METHODCALL = 1;
- protected static final int MAGICNUMBER_FQN = 2;
- protected static final int MAGICNUMBER_GTX = 3;
- protected static final int MAGICNUMBER_JG_ADDRESS = 4;
- protected static final int MAGICNUMBER_ARRAY_LIST = 5;
- protected static final int MAGICNUMBER_INTEGER = 6;
- protected static final int MAGICNUMBER_LONG = 7;
- protected static final int MAGICNUMBER_BOOLEAN = 8;
- protected static final int MAGICNUMBER_STRING = 9;
- protected static final int MAGICNUMBER_DEFAULT_DATA_VERSION = 10;
- protected static final int MAGICNUMBER_LINKED_LIST = 11;
- protected static final int MAGICNUMBER_HASH_MAP = 12;
- protected static final int MAGICNUMBER_TREE_MAP = 13;
- protected static final int MAGICNUMBER_HASH_SET = 14;
- protected static final int MAGICNUMBER_TREE_SET = 15;
- protected static final int MAGICNUMBER_NODEDATA_MARKER = 16;
- protected static final int MAGICNUMBER_NODEDATA_EXCEPTION_MARKER = 17;
- protected static final int MAGICNUMBER_NODEDATA = 18;
- protected static final int MAGICNUMBER_GRAVITATERESULT = 19;
- protected static final int MAGICNUMBER_SHORT = 20;
- protected static final int MAGICNUMBER_IMMUTABLE_MAPCOPY = 21;
- protected static final int MAGICNUMBER_MARSHALLEDVALUE = 22;
- protected static final int MAGICNUMBER_FASTCOPY_HASHMAP = 23;
- protected static final int MAGICNUMBER_ARRAY = 24;
- protected static final int MAGICNUMBER_BYTE = 25;
- protected static final int MAGICNUMBER_CHAR = 26;
- protected static final int MAGICNUMBER_FLOAT = 27;
- protected static final int MAGICNUMBER_DOUBLE = 28;
- protected static final int MAGICNUMBER_OBJECT = 29;
+ protected static final int MAGICNUMBER_GTX = 1;
+ protected static final int MAGICNUMBER_JG_ADDRESS = 2;
+ protected static final int MAGICNUMBER_ARRAY_LIST = 3;
+ protected static final int MAGICNUMBER_INTEGER = 4;
+ protected static final int MAGICNUMBER_LONG = 5;
+ protected static final int MAGICNUMBER_BOOLEAN = 6;
+ protected static final int MAGICNUMBER_STRING = 7;
+ protected static final int MAGICNUMBER_LINKED_LIST = 8;
+ protected static final int MAGICNUMBER_HASH_MAP = 9;
+ protected static final int MAGICNUMBER_TREE_MAP = 10;
+ protected static final int MAGICNUMBER_HASH_SET = 11;
+ protected static final int MAGICNUMBER_TREE_SET = 12;
+ protected static final int MAGICNUMBER_SHORT = 13;
+ protected static final int MAGICNUMBER_IMMUTABLE_MAPCOPY = 14;
+ protected static final int MAGICNUMBER_MARSHALLEDVALUE = 15;
+ protected static final int MAGICNUMBER_FASTCOPY_HASHMAP = 16;
+ protected static final int MAGICNUMBER_ARRAY = 17;
+ protected static final int MAGICNUMBER_BYTE = 18;
+ protected static final int MAGICNUMBER_CHAR = 19;
+ protected static final int MAGICNUMBER_FLOAT = 20;
+ protected static final int MAGICNUMBER_DOUBLE = 21;
+ protected static final int MAGICNUMBER_OBJECT = 22;
+ protected static final int MAGICNUMBER_SINGLETON_LIST = 23;
+ protected static final int MAGICNUMBER_COMMAND = 24;
protected static final int MAGICNUMBER_NULL = 99;
protected static final int MAGICNUMBER_SERIALIZABLE = 100;
-
protected static final int MAGICNUMBER_REF = 101;
public HorizonMarshaller() {
@@ -101,8 +94,9 @@
protected ClassLoader defaultClassLoader;
protected boolean useRefs = false;
- public void init(ClassLoader defaultClassLoader) {
+ public void init(ClassLoader defaultClassLoader, RemoteCommandFactory remoteCommandFactory) {
this.defaultClassLoader = defaultClassLoader;
+ this.remoteCommandFactory = remoteCommandFactory;
}
protected void initLogger() {
@@ -132,10 +126,10 @@
ReplicableCommand command = (ReplicableCommand) o;
if (command.getCommandId() > -1) {
- out.writeByte(MAGICNUMBER_METHODCALL);
+ out.writeByte(MAGICNUMBER_COMMAND);
marshallCommand(command, out, refMap);
} else {
- throw new IllegalArgumentException("MethodCall does not have a valid method id. Was this method call created with MethodCallFactory?");
+ throw new IllegalArgumentException("Command does not have a valid method id!");
}
} else if (o instanceof MarshalledValue) {
out.writeByte(MAGICNUMBER_MARSHALLEDVALUE);
@@ -158,6 +152,9 @@
} else if (o instanceof LinkedList) {
out.writeByte(MAGICNUMBER_LINKED_LIST);
marshallCollection((Collection) o, out, refMap);
+ } else if (o.getClass().getName().equals("java.util.Collections$SingletonList")) {
+ out.writeByte(MAGICNUMBER_SINGLETON_LIST);
+ marshallObject(((List) o).get(0), out, refMap);
} else if (o.getClass().equals(HashMap.class)) {
out.writeByte(MAGICNUMBER_HASH_MAP);
marshallMap((Map) o, out, refMap);
@@ -192,15 +189,6 @@
out.writeByte(MAGICNUMBER_STRING);
if (useRefs) writeReference(out, createReference(o, refMap));
marshallString((String) o, out);
- } else if (o instanceof NodeDataMarker) {
- out.writeByte(MAGICNUMBER_NODEDATA_MARKER);
- ((Externalizable) o).writeExternal(out);
- } else if (o instanceof NodeDataExceptionMarker) {
- out.writeByte(MAGICNUMBER_NODEDATA_EXCEPTION_MARKER);
- ((Externalizable) o).writeExternal(out);
- } else if (o instanceof NodeData) {
- out.writeByte(MAGICNUMBER_NODEDATA);
- ((Externalizable) o).writeExternal(out);
} else if (o instanceof Serializable) {
if (trace) {
log.trace("Warning: using object serialization for " + o.getClass());
@@ -306,7 +294,7 @@
MarshalledValue mv = new MarshalledValue();
mv.readExternal(in);
return mv;
- case MAGICNUMBER_METHODCALL:
+ case MAGICNUMBER_COMMAND:
retVal = unmarshallCommand(in, refMap);
return retVal;
case MAGICNUMBER_GTX:
@@ -323,6 +311,8 @@
return unmarshallArrayList(in, refMap);
case MAGICNUMBER_LINKED_LIST:
return unmarshallLinkedList(in, refMap);
+ case MAGICNUMBER_SINGLETON_LIST:
+ return unmarshallSingletonList(in, refMap);
case MAGICNUMBER_HASH_MAP:
return unmarshallHashMap(in, refMap);
case MAGICNUMBER_TREE_MAP:
@@ -348,18 +338,6 @@
retVal = unmarshallString(in);
if (useRefs) refMap.putReferencedObject(reference, retVal);
return retVal;
- case MAGICNUMBER_NODEDATA_MARKER:
- retVal = new NodeDataMarker();
- ((NodeDataMarker) retVal).readExternal(in);
- return retVal;
- case MAGICNUMBER_NODEDATA_EXCEPTION_MARKER:
- retVal = new NodeDataExceptionMarker();
- ((NodeDataExceptionMarker) retVal).readExternal(in);
- return retVal;
- case MAGICNUMBER_NODEDATA:
- retVal = new NodeData();
- ((NodeData) retVal).readExternal(in);
- return retVal;
default:
if (log.isErrorEnabled()) {
log.error("Unknown Magic Number " + magicNumber);
@@ -421,6 +399,10 @@
return list;
}
+ private List unmarshallSingletonList(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception {
+ return Collections.singletonList(unmarshallObject(in, refMap));
+ }
+
private Map unmarshallHashMap(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception {
Map map = new HashMap();
populateFromStream(in, refMap, map);
Modified: core/branches/flat/src/main/java/org/horizon/marshall/VersionAwareMarshaller.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/VersionAwareMarshaller.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/marshall/VersionAwareMarshaller.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -21,6 +21,7 @@
*/
package org.horizon.marshall;
+import org.horizon.commands.RemoteCommandFactory;
import org.horizon.factories.annotations.Inject;
import org.horizon.io.ByteBuffer;
import org.horizon.io.ExposedByteArrayOutputStream;
@@ -54,9 +55,9 @@
ClassLoader defaultClassLoader;
@Inject
- public void init(ClassLoader loader) {
+ public void init(ClassLoader loader, RemoteCommandFactory remoteCommandFactory) {
defaultMarshaller = new HorizonMarshaller();
- defaultMarshaller.init(loader);
+ defaultMarshaller.init(loader, remoteCommandFactory);
}
protected int getCustomMarshallerVersionInt() {
Modified: core/branches/flat/src/main/java/org/horizon/remoting/InboundInvocationHandler.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/InboundInvocationHandler.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/remoting/InboundInvocationHandler.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -1,6 +1,6 @@
package org.horizon.remoting;
-import org.horizon.commands.ReplicableCommand;
+import org.horizon.commands.RPCCommand;
import org.horizon.factories.scopes.Scope;
import org.horizon.factories.scopes.Scopes;
@@ -20,5 +20,5 @@
* @param command command to invoke
* @return results, if any, from the invocation
*/
- Object handle(ReplicableCommand command);
+ Object handle(RPCCommand command) throws Throwable;
}
Modified: core/branches/flat/src/main/java/org/horizon/remoting/InboundInvocationHandlerImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/InboundInvocationHandlerImpl.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/remoting/InboundInvocationHandlerImpl.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -1,48 +1,49 @@
package org.horizon.remoting;
-import org.horizon.commands.ReplicableCommand;
+import org.horizon.commands.CommandsFactory;
+import org.horizon.commands.RPCCommand;
import org.horizon.factories.ComponentRegistry;
import org.horizon.factories.GlobalComponentRegistry;
+import org.horizon.factories.annotations.Inject;
+import org.horizon.factories.annotations.NonVolatile;
+import org.horizon.factories.scopes.Scope;
+import org.horizon.factories.scopes.Scopes;
import org.horizon.interceptors.InterceptorChain;
import org.horizon.invocation.InvocationContextContainer;
+import org.horizon.logging.Log;
+import org.horizon.logging.LogFactory;
/**
- * // TODO: Manik: Document this!
+ * Sets the cache interceptor chain on an RPCCommand before calling it to perform
*
* @author Manik Surtani
* @since 1.0
*/
+@NonVolatile
+(a)Scope(Scopes.GLOBAL)
public class InboundInvocationHandlerImpl implements InboundInvocationHandler {
- InvocationContextContainer invocationContextContainer;
- ComponentRegistry componentRegistry;
- InterceptorChain interceptorChain;
GlobalComponentRegistry gcr;
+ private static final Log log = LogFactory.getLog(InboundInvocationHandlerImpl.class);
+ @Inject
public void inject(GlobalComponentRegistry gcr) {
this.gcr = gcr;
}
- private ComponentRegistry getNamedCacheComponentRegistry(String name) {
- return gcr.getNamedComponentRegistry(name);
- }
+ public Object handle(RPCCommand cmd) throws Throwable {
+ String cacheName = cmd.getCacheName();
+ ComponentRegistry cr = gcr.getNamedComponentRegistry(cacheName);
+ if (cr == null) {
+ log.info("Cache named {0} does not exist on this cache manager!", cacheName);
+ return null;
+ }
+ InterceptorChain ic = cr.getComponent(InterceptorChain.class);
+ InvocationContextContainer icc = cr.getComponent(InvocationContextContainer.class);
+ CommandsFactory commandsFactory = cr.getComponent(CommandsFactory.class);
- public Object handle(ReplicableCommand command) {
-
- throw new RuntimeException("Implement me!");
-// if (cmd instanceof VisitableCommand) {
-// InvocationContext ctx = invocationContextContainer.get();
-// ctx.setOriginLocal(false);
-// if (!componentRegistry.invocationsAllowed(false)) {
-// return null;
-// }
-// return interceptorChain.invoke(ctx, (VisitableCommand) command);
-// } else {
-// if (trace) log.trace("This is a non-visitable command - so performing directly and not via the invoker.");
-//
-// // need to check cache status for all except buddy replication commands.
-// if (!componentRegistry.invocationsAllowed(false)) return null;
-//
-// return cmd.perform(null);
-// }
+ cmd.setInterceptorChain(ic);
+ // initialize this command with components specific to the intended cache instance
+ commandsFactory.initializeReplicableCommand(cmd);
+ return cmd.perform(icc.get());
}
}
Modified: core/branches/flat/src/main/java/org/horizon/remoting/RPCManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/RPCManager.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/remoting/RPCManager.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -21,7 +21,7 @@
*/
package org.horizon.remoting;
-import org.horizon.commands.ReplicableCommand;
+import org.horizon.commands.RPCCommand;
import org.horizon.factories.annotations.NonVolatile;
import org.horizon.factories.scopes.Scope;
import org.horizon.factories.scopes.Scopes;
@@ -49,7 +49,7 @@
*
* @param recipients a list of Addresses to invoke the call on. If this is null, the call is broadcast to the
* entire cluster.
- * @param cacheCommand the cache command to invoke
+ * @param rpcCommand the cache command to invoke
* @param mode the response mode to use
* @param timeout a timeout after which to throw a replication exception.
* @param usePriorityQueue if true, a priority queue is used to deliver messages. May not be supported by all
@@ -58,14 +58,14 @@
* @return a list of responses from each member contacted.
* @throws Exception in the event of problems.
*/
- List<Object> invokeRemotely(List<Address> recipients, ReplicableCommand cacheCommand, ResponseMode mode, long timeout, boolean usePriorityQueue, ResponseFilter responseFilter) throws Exception;
+ List<Object> invokeRemotely(List<Address> recipients, RPCCommand rpcCommand, ResponseMode mode, long timeout, boolean usePriorityQueue, ResponseFilter responseFilter) throws Exception;
/**
* Invokes an RPC call on other caches in the cluster.
*
* @param recipients a list of Addresses to invoke the call on. If this is null, the call is broadcast to the
* entire cluster.
- * @param cacheCommand the cache command to invoke
+ * @param rpcCommand the cache command to invoke
* @param mode the response mode to use
* @param timeout a timeout after which to throw a replication exception.
* @param usePriorityQueue if true, a priority queue is used to deliver messages. May not be supported by all
@@ -73,20 +73,20 @@
* @return a list of responses from each member contacted.
* @throws Exception in the event of problems.
*/
- List<Object> invokeRemotely(List<Address> recipients, ReplicableCommand cacheCommand, ResponseMode mode, long timeout, boolean usePriorityQueue) throws Exception;
+ List<Object> invokeRemotely(List<Address> recipients, RPCCommand rpcCommand, ResponseMode mode, long timeout, boolean usePriorityQueue) throws Exception;
/**
* Invokes an RPC call on other caches in the cluster.
*
- * @param recipients a list of Addresses to invoke the call on. If this is null, the call is broadcast to the
- * entire cluster.
- * @param cacheCommand the cache command to invoke
- * @param mode the response mode to use
- * @param timeout a timeout after which to throw a replication exception.
+ * @param recipients a list of Addresses to invoke the call on. If this is null, the call is broadcast to the entire
+ * cluster.
+ * @param rpcCommand the cache command to invoke
+ * @param mode the response mode to use
+ * @param timeout a timeout after which to throw a replication exception.
* @return a list of responses from each member contacted.
* @throws Exception in the event of problems.
*/
- List<Object> invokeRemotely(List<Address> recipients, ReplicableCommand cacheCommand, ResponseMode mode, long timeout) throws Exception;
+ List<Object> invokeRemotely(List<Address> recipients, RPCCommand rpcCommand, ResponseMode mode, long timeout) throws Exception;
/**
* @return true if the current Channel is the coordinator of the cluster.
Modified: core/branches/flat/src/main/java/org/horizon/remoting/RPCManagerImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/RPCManagerImpl.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/remoting/RPCManagerImpl.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -3,7 +3,7 @@
import org.horizon.annotations.MBean;
import org.horizon.annotations.ManagedAttribute;
import org.horizon.annotations.ManagedOperation;
-import org.horizon.commands.ReplicableCommand;
+import org.horizon.commands.RPCCommand;
import org.horizon.config.GlobalConfiguration;
import org.horizon.factories.KnownComponentNames;
import org.horizon.factories.annotations.ComponentName;
@@ -54,16 +54,16 @@
t.stop();
}
- public List<Object> invokeRemotely(List<Address> recipients, ReplicableCommand cacheCommand, ResponseMode mode, long timeout, boolean usePriorityQueue, ResponseFilter responseFilter) throws Exception {
- return t.invokeRemotely(recipients, cacheCommand, mode, timeout, usePriorityQueue, responseFilter);
+ public List<Object> invokeRemotely(List<Address> recipients, RPCCommand rpcCommand, ResponseMode mode, long timeout, boolean usePriorityQueue, ResponseFilter responseFilter) throws Exception {
+ return t.invokeRemotely(recipients, rpcCommand, mode, timeout, usePriorityQueue, responseFilter);
}
- public List<Object> invokeRemotely(List<Address> recipients, ReplicableCommand cacheCommand, ResponseMode mode, long timeout, boolean usePriorityQueue) throws Exception {
- return t.invokeRemotely(recipients, cacheCommand, mode, timeout, usePriorityQueue, null);
+ public List<Object> invokeRemotely(List<Address> recipients, RPCCommand rpcCommand, ResponseMode mode, long timeout, boolean usePriorityQueue) throws Exception {
+ return t.invokeRemotely(recipients, rpcCommand, mode, timeout, usePriorityQueue, null);
}
- public List<Object> invokeRemotely(List<Address> recipients, ReplicableCommand cacheCommand, ResponseMode mode, long timeout) throws Exception {
- return t.invokeRemotely(recipients, cacheCommand, mode, timeout, false, null);
+ public List<Object> invokeRemotely(List<Address> recipients, RPCCommand rpcCommand, ResponseMode mode, long timeout) throws Exception {
+ return t.invokeRemotely(recipients, rpcCommand, mode, timeout, false, null);
}
public boolean isCoordinator() {
@@ -119,4 +119,9 @@
double ration = (double) replicationCount.get() / totalCount * 100d;
return NumberFormat.getInstance().format(ration) + "%";
}
+
+ // mainly for unit testing
+ public void setTransport(Transport transport) {
+ this.t = transport;
+ }
}
Modified: core/branches/flat/src/main/java/org/horizon/remoting/transport/Transport.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/transport/Transport.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/main/java/org/horizon/remoting/transport/Transport.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -1,6 +1,6 @@
package org.horizon.remoting.transport;
-import org.horizon.commands.ReplicableCommand;
+import org.horizon.commands.RPCCommand;
import org.horizon.config.GlobalConfiguration;
import org.horizon.factories.annotations.NonVolatile;
import org.horizon.factories.scopes.Scope;
@@ -44,7 +44,7 @@
*
* @param recipients a list of Addresses to invoke the call on. If this is null, the call is broadcast to the
* entire cluster.
- * @param cacheCommand the cache command to invoke
+ * @param rpcCommand the cache command to invoke
* @param mode the response mode to use
* @param timeout a timeout after which to throw a replication exception.
* @param usePriorityQueue if true, a priority queue is used to deliver messages. May not be supported by all
@@ -53,7 +53,7 @@
* @return a list of responses from each member contacted.
* @throws Exception in the event of problems.
*/
- List<Object> invokeRemotely(List<Address> recipients, ReplicableCommand cacheCommand, ResponseMode mode, long timeout, boolean usePriorityQueue, ResponseFilter responseFilter) throws Exception;
+ List<Object> invokeRemotely(List<Address> recipients, RPCCommand rpcCommand, ResponseMode mode, long timeout, boolean usePriorityQueue, ResponseFilter responseFilter) throws Exception;
/**
* @return true if the current Channel is the coordinator of the cluster.
Added: core/branches/flat/src/test/java/org/horizon/BaseReplicatedTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/BaseReplicatedTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/BaseReplicatedTest.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -0,0 +1,68 @@
+package org.horizon;
+
+import org.horizon.config.Configuration;
+import org.horizon.config.GlobalConfiguration;
+import org.horizon.manager.CacheManager;
+import org.horizon.manager.DefaultCacheManager;
+import org.horizon.util.TestingUtil;
+import org.testng.annotations.AfterMethod;
+
+import java.util.LinkedList;
+import java.util.List;
+
+public abstract class BaseReplicatedTest {
+ 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 addCacheManager() {
+ 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 void assertClusterSize(String message, int size) {
+ for (CacheManager cm : cacheManagerThreadLocal.get()) {
+ assert cm.getMembers() != null && cm.getMembers().size() == size : message;
+ }
+ }
+
+ @AfterMethod
+ public void cleanupThreadLocals() {
+ TestingUtil.killCacheManagers(cacheManagerThreadLocal.get().toArray(new CacheManager[cacheManagerThreadLocal.get().size()]));
+ cacheManagerThreadLocal.get().clear();
+ }
+
+}
Modified: core/branches/flat/src/test/java/org/horizon/BasicTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/BasicTest.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/test/java/org/horizon/BasicTest.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -22,8 +22,10 @@
package org.horizon;
import org.horizon.config.Configuration;
+import org.horizon.config.GlobalConfiguration;
import org.horizon.logging.Log;
import org.horizon.logging.LogFactory;
+import org.horizon.manager.CacheManager;
import org.horizon.manager.DefaultCacheManager;
import org.horizon.manager.NamedCacheNotFoundException;
import org.horizon.util.TestingUtil;
@@ -31,6 +33,8 @@
@Test(groups = "functional")
public class BasicTest {
+ public static final Log log = LogFactory.getLog(BasicTest.class);
+
public void basicTest() throws Exception {
// create a cache manager
Configuration c = new Configuration(); // LOCAL mode
@@ -61,25 +65,18 @@
}
}
- public static final Log log = LogFactory.getLog(BasicTest.class);
-
public void testBasicReplication() throws NamedCacheNotFoundException {
Configuration configuration = new Configuration();
configuration.setCacheMode(Configuration.CacheMode.REPL_SYNC);
- DefaultCacheManager firstManager = new DefaultCacheManager(configuration);
- DefaultCacheManager secondManager = new DefaultCacheManager(configuration);
+ CacheManager firstManager = new DefaultCacheManager(GlobalConfiguration.getClusteredDefault(), configuration);
+ CacheManager secondManager = new DefaultCacheManager(GlobalConfiguration.getClusteredDefault(), configuration);
try {
- firstManager.start();
- secondManager.start();
+ CacheSPI firstCache = (CacheSPI) firstManager.getCache();
+ CacheSPI secondCache = (CacheSPI) secondManager.getCache();
+ TestingUtil.blockUntilViewsReceived(60000, firstManager, secondManager);
- CacheSPI firstCache = (CacheSPI) firstManager.getCache("test");
- CacheSPI secondCache = (CacheSPI) secondManager.getCache("test");
-
- TestingUtil.blockUntilViewReceived(secondCache, 2, 3000);
-
-
firstCache.put("key", "value");
assert secondCache.get("key").equals("value");
@@ -90,16 +87,38 @@
assert secondCache.get("key") == null;
}
finally {
- firstManager.stop();
- secondManager.stop();
+ TestingUtil.killCacheManagers(firstManager, secondManager);
}
}
public void concurrentMapMethodTest() {
+ CacheManager cm = null;
+ Cache<String, String> c = null;
+ try {
+ cm = new DefaultCacheManager();
+ c = cm.getCache();
- }
+ assert c.putIfAbsent("A", "B") == null;
+ assert c.putIfAbsent("A", "C").equals("B");
+ assert c.get("A").equals("B");
- public void transactionalTest() {
+ assert !c.remove("A", "C");
+ assert c.containsKey("A");
+ assert c.remove("A", "B");
+ assert !c.containsKey("A");
+ c.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 c.replace("A", "X").equals("C");
+ assert c.replace("X", "A") == null;
+ assert !c.containsKey("X");
+ } finally {
+ TestingUtil.killCacheManagers(cm);
+ }
}
}
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-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -5,7 +5,7 @@
import org.horizon.Cache;
import org.horizon.CacheSPI;
import org.horizon.UnitTestCacheFactory;
-import org.horizon.commands.ReplicableCommand;
+import org.horizon.commands.RPCCommand;
import org.horizon.commands.write.PutKeyValueCommand;
import org.horizon.commands.write.RemoveCommand;
import org.horizon.config.Configuration;
@@ -118,7 +118,7 @@
// specify what we expectWithTx called on the mock Rpc Manager. For params we don't care about, just use ANYTHING.
// setting the mock object to expectWithTx the "sync" param to be false.
- expect(rpcManager.invokeRemotely(anyAddresses(), (ReplicableCommand) anyObject(), eq(ResponseMode.ASYNCHRONOUS), anyLong(), anyBoolean())).andReturn(null);
+ expect(rpcManager.invokeRemotely(anyAddresses(), (RPCCommand) anyObject(), eq(ResponseMode.ASYNCHRONOUS), anyLong(), anyBoolean())).andReturn(null);
replay(rpcManager);
@@ -162,7 +162,7 @@
List<Address> memberList = originalRpcManager.getMembers();
expect(barfingRpcManager.getMembers()).andReturn(memberList).anyTimes();
expect(barfingRpcManager.getAddress()).andReturn(originalRpcManager.getAddress()).anyTimes();
- expect(barfingRpcManager.invokeRemotely(anyAddresses(), (ReplicableCommand) anyObject(), anyResponseMode(), anyLong(), anyBoolean())).andThrow(new RuntimeException("Barf!")).anyTimes();
+ expect(barfingRpcManager.invokeRemotely(anyAddresses(), (RPCCommand) anyObject(), anyResponseMode(), anyLong(), anyBoolean())).andThrow(new RuntimeException("Barf!")).anyTimes();
replay(barfingRpcManager);
TestingUtil.extractComponentRegistry(cache1).registerComponent(barfingRpcManager, RPCManager.class);
Modified: core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -6,79 +6,172 @@
*/
package org.horizon.replication;
+import static org.easymock.EasyMock.*;
+import org.horizon.BaseReplicatedTest;
import org.horizon.Cache;
-import org.horizon.UnitTestCacheManager;
+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 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.Collections;
+import java.util.LinkedList;
+import java.util.List;
+
/**
* @author <a href="mailto:manik@jboss.org">Manik Surtani (manik(a)jboss.org)</a>
*/
-@Test(groups = {"functional", "jgroups"})
-public class SyncReplTest {
- private ThreadLocal<Cache<Object, Object>[]> cachesTL = new ThreadLocal<Cache<Object, Object>[]>();
+@Test(groups = "functional", sequential = true)
+public class SyncReplTest extends BaseReplicatedTest {
+ Cache cache1, cache2;
+ String k = "key", v = "value";
@BeforeMethod(alwaysRun = true)
public void setUp() {
- System.out.println("*** In setUp()");
- Cache<Object, Object>[] caches = new Cache[2];
- Configuration configuration = new Configuration();
- configuration.setCacheMode(Configuration.CacheMode.REPL_SYNC);
- caches[0] = new UnitTestCacheManager(configuration).createCache("test");
- caches[1] = new UnitTestCacheManager(configuration).createCache("test");
- cachesTL.set(caches);
- TestingUtil.blockUntilViewsReceived(caches, 5000);
- System.out.println("*** Finished setUp()");
- }
+ CacheManager cm1 = addCacheManager();
+ CacheManager cm2 = addCacheManager();
- @AfterMethod(alwaysRun = true)
- public void tearDown() {
- Cache<Object, Object>[] caches = cachesTL.get();
- if (caches != null) TestingUtil.killCaches(caches);
- cachesTL.set(null);
+ Configuration replSync = new Configuration();
+ replSync.setCacheMode(Configuration.CacheMode.REPL_SYNC);
+
+ cm1.defineCache("replSync", replSync);
+ cm2.defineCache("replSync", replSync);
+
+ cache1 = cm1.getCache("replSync");
+ cache2 = cm2.getCache("replSync");
+
+ TestingUtil.blockUntilViewsReceived(60000, true, cm1, cm2);
}
public void testBasicOperation() {
- Cache<Object, Object>[] caches = cachesTL.get();
assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
- String k = "key", v = "value";
+ assertNull("Should be null", cache1.get(k));
+ assertNull("Should be null", cache2.get(k));
- assertNull("Should be null", caches[0].get(k));
- assertNull("Should be null", caches[1].get(k));
+ cache1.put(k, v);
- caches[0].put(k, v);
+ assertEquals(v, cache1.get(k));
+ assertEquals("Should have replicated", v, cache2.get(k));
- assertEquals(v, caches[0].get(k));
- assertEquals("Should have replicated", v, caches[1].get(k));
+ cache2.remove(k);
+ assert cache1.isEmpty();
+ assert cache2.isEmpty();
}
- @SuppressWarnings("unchecked")
- public void testSyncRepl() {
- Cache<Object, Object>[] caches = cachesTL.get();
+ public void testMultpleCachesOnSharedTransport() {
assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
+ assert cache1.isEmpty();
+ assert cache2.isEmpty();
- caches[0].getConfiguration().setSyncCommitPhase(true);
- caches[1].getConfiguration().setSyncCommitPhase(true);
+ 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");
- caches[0].put("age", 38);
- assertEquals("Value should be set", 38, caches[0].get("age"));
- assertEquals("Value should have replicated", 38, caches[1].get("age"));
+ 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);
}
- private void assertClusterSize(String message, int size) {
- Cache<Object, Object>[] caches = cachesTL.get();
- for (Cache c : caches) {
- assertClusterSize(message, size, c);
- }
+ public void testReplicateToNonExistentCache() {
+ assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
+ 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");
+
+ 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);
+
+ managers.get(0).getCache("newCache").get(k).equals("value2");
}
- private void assertClusterSize(String message, int size, Cache c) {
- assertEquals(message, size, c.getCacheManager().getMembers().size());
+ 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");
+
+ // replace the transport with a mock object
+ Transport mockTransport = createMock(Transport.class);
+ Address mockAddressOne = createNiceMock(Address.class);
+ Address mockAddressTwo = createNiceMock(Address.class);
+ List<Address> addresses = new LinkedList<Address>();
+ addresses.add(mockAddressOne);
+ addresses.add(mockAddressTwo);
+ expect(mockTransport.getAddress()).andReturn(mockAddressOne).anyTimes();
+ expect(mockTransport.getMembers()).andReturn(addresses).anyTimes();
+ replay(mockAddressOne, mockAddressTwo);
+
+ // this is shared by all caches managed by the cache manager
+ originalTransport = TestingUtil.extractComponent(asyncCache1, Transport.class);
+ rpcManager = (RPCManagerImpl) TestingUtil.extractComponent(asyncCache1, RPCManager.class);
+ rpcManager.setTransport(mockTransport);
+
+ expect(mockTransport.invokeRemotely((List<Address>) anyObject(), (RPCCommand) anyObject(), eq(ResponseMode.SYNCHRONOUS),
+ anyLong(), anyBoolean(), (ResponseFilter) anyObject()))
+ .andReturn(Collections.emptyList()).once();
+
+ replay(mockTransport);
+ // check that the replication call was sync
+ cache1.put("k", "v");
+
+ // reset to test for async
+ reset(mockTransport);
+ expect(mockTransport.getAddress()).andReturn(mockAddressOne).anyTimes();
+ expect(mockTransport.getMembers()).andReturn(addresses).anyTimes();
+ expect(mockTransport.invokeRemotely((List<Address>) anyObject(), (RPCCommand) anyObject(), eq(ResponseMode.ASYNCHRONOUS),
+ anyLong(), anyBoolean(), (ResponseFilter) anyObject()))
+ .andReturn(Collections.emptyList()).once();
+
+ replay(mockTransport);
+ asyncCache1.put("k", "v");
+ // check that the replication call was async
+ verify(mockTransport);
+ } finally {
+ // replace original transport
+ if (rpcManager != null) rpcManager.setTransport(originalTransport);
+ }
}
}
Modified: core/branches/flat/src/test/java/org/horizon/util/internals/ReplicationListener.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/util/internals/ReplicationListener.java 2009-01-27 23:06:53 UTC (rev 7604)
+++ core/branches/flat/src/test/java/org/horizon/util/internals/ReplicationListener.java 2009-01-28 14:34:08 UTC (rev 7605)
@@ -128,9 +128,9 @@
Class<? extends ReplicableCommand> replicableCommandClass = it.next();
if (realOne.containsCommandType(replicableCommandClass)) {
it.remove();
- } else if (realOne.getSingleModification() instanceof PrepareCommand) //explicit transaction
+ } else if (realOne.getSingleCommand() instanceof PrepareCommand) //explicit transaction
{
- PrepareCommand prepareCommand = (PrepareCommand) realOne.getSingleModification();
+ PrepareCommand prepareCommand = (PrepareCommand) realOne.getSingleCommand();
if (prepareCommand.containsModificationType(replicableCommandClass)) {
it.remove();
}
15 years, 11 months
JBoss Cache SVN: r7604 - in core/trunk/src: test/java/org/jboss/cache/transaction and 1 other directory.
by jbosscache-commits@lists.jboss.org
Author: emmartins
Date: 2009-01-27 18:06:53 -0500 (Tue, 27 Jan 2009)
New Revision: 7604
Modified:
core/trunk/src/main/java/org/jboss/cache/transaction/TransactionTable.java
core/trunk/src/test/java/org/jboss/cache/transaction/MarkAsRollbackTest.java
Log:
final solution regarding issue JBCACHE-1468
Modified: core/trunk/src/main/java/org/jboss/cache/transaction/TransactionTable.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/transaction/TransactionTable.java 2009-01-27 18:01:32 UTC (rev 7603)
+++ core/trunk/src/main/java/org/jboss/cache/transaction/TransactionTable.java 2009-01-27 23:06:53 UTC (rev 7604)
@@ -359,14 +359,33 @@
}
/**
- * Returns true of tx's status is ACTIVE or PREPARING
+ * Returns true if transaction is STATUS_MARKED_ROLLBACK, false otherwise
+ */
+ public static boolean isMarkedAsRollback(Transaction tx)
+ {
+ if (tx == null) return false;
+ int status;
+ try
+ {
+ status = tx.getStatus();
+ return status == Status.STATUS_MARKED_ROLLBACK;
+ }
+ catch (SystemException e)
+ {
+ return false;
+ }
+ }
+
+
+ /**
+ * Returns true of tx's status is ACTIVE or PREPARING or MARKED_ROLLBACK
*
* @param tx
* @return true if the tx is active or preparing
*/
public static boolean isValid(Transaction tx)
{
- return isActive(tx) || isPreparing(tx);
+ return isActive(tx) || isPreparing(tx) || isMarkedAsRollback(tx);
}
/**
Modified: core/trunk/src/test/java/org/jboss/cache/transaction/MarkAsRollbackTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/transaction/MarkAsRollbackTest.java 2009-01-27 18:01:32 UTC (rev 7603)
+++ core/trunk/src/test/java/org/jboss/cache/transaction/MarkAsRollbackTest.java 2009-01-27 23:06:53 UTC (rev 7604)
@@ -2,6 +2,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.jboss.cache.CacheException;
import org.jboss.cache.CacheSPI;
import org.jboss.cache.Fqn;
import org.jboss.cache.UnitTestCacheFactory;
@@ -51,7 +52,7 @@
TestingUtil.killCaches(cache);
}
}
-
+
public void testMarkAsRollbackBeforeMods() throws Exception
{
Configuration c = new Configuration();
@@ -68,9 +69,9 @@
cache.put(fqn, "k", "v");
assert false : "Should have failed";
}
- catch (IllegalStateException expected)
+ catch (CacheException expected)
{
-
+ assert expected.getCause() instanceof RollbackException : "exception wrapped and thrown should be RollbackException. Exception class "+expected.getCause().getClass();
}
try
{
15 years, 11 months
JBoss Cache SVN: r7603 - in core/branches/flat/src: main/java/org/horizon/config and 18 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2009-01-27 13:01:32 -0500 (Tue, 27 Jan 2009)
New Revision: 7603
Added:
core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTMTest.java
core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTMTest.java
Removed:
core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTM.java
core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTM.java
Modified:
core/branches/flat/src/main/java/org/horizon/CacheDelegate.java
core/branches/flat/src/main/java/org/horizon/ComponentStatus.java
core/branches/flat/src/main/java/org/horizon/config/Configuration.java
core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserImpl.java
core/branches/flat/src/main/java/org/horizon/factories/AbstractComponentRegistry.java
core/branches/flat/src/main/java/org/horizon/factories/ComponentRegistry.java
core/branches/flat/src/main/java/org/horizon/factories/GlobalComponentRegistry.java
core/branches/flat/src/main/java/org/horizon/interceptors/TxInterceptor.java
core/branches/flat/src/main/java/org/horizon/lifecycle/Lifecycle.java
core/branches/flat/src/main/java/org/horizon/manager/CacheManager.java
core/branches/flat/src/main/java/org/horizon/manager/DefaultCacheManager.java
core/branches/flat/src/main/java/org/horizon/notifications/CacheNotifierImpl.java
core/branches/flat/src/main/java/org/horizon/remoting/transport/Transport.java
core/branches/flat/src/main/java/org/horizon/tree/TreeStructureSupport.java
core/branches/flat/src/main/java/org/horizon/util/ReflectionUtil.java
core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java
core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java
core/branches/flat/src/test/java/org/horizon/api/CacheSPITest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.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/NodeMoveAPITest.java
core/branches/flat/src/test/java/org/horizon/manager/CacheManagerXmlConfigurationTest.java
core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java
core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java
core/branches/flat/src/test/java/org/horizon/util/internals/ViewChangeListener.java
Log:
More fixes
Modified: core/branches/flat/src/main/java/org/horizon/CacheDelegate.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/CacheDelegate.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/CacheDelegate.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -188,15 +188,15 @@
invoker.invoke(buildCtx(), command);
}
- public Set keySet() {
+ public Set<K> keySet() {
throw new UnsupportedOperationException("Go away");
}
- public Collection values() {
+ public Collection<V> values() {
throw new UnsupportedOperationException("Go away");
}
- public Set entrySet() {
+ public Set<Map.Entry<K, V>> entrySet() {
throw new UnsupportedOperationException("Go away");
}
Modified: core/branches/flat/src/main/java/org/horizon/ComponentStatus.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/ComponentStatus.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/ComponentStatus.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -94,13 +94,7 @@
}
public boolean needToDestroyFailedCache() {
- if (this == ComponentStatus.FAILED) {
- log.debug("need to call destroy() since current state is " +
- this);
- return true;
- }
-
- return false;
+ return this == ComponentStatus.FAILED;
}
public boolean startAllowed() {
@@ -122,8 +116,6 @@
switch (this) {
case INSTANTIATED:
case DESTROYED:
- log.debug("start() called while current state is " +
- this + " -- call create() first");
return true;
default:
return false;
@@ -176,13 +168,7 @@
}
public boolean needStopBeforeDestroy() {
- if (this == ComponentStatus.STARTED) {
- log.warn("destroy() called while current state is " +
- this + " -- call stop() first");
- return true;
- }
-
- return false;
+ return this == ComponentStatus.STARTED;
}
public boolean allowInvocations() {
Modified: core/branches/flat/src/main/java/org/horizon/config/Configuration.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/Configuration.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/config/Configuration.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -133,8 +133,6 @@
private long stateRetrievalTimeout = 10000;
private IsolationLevel isolationLevel = IsolationLevel.READ_COMMITTED;
@Dynamic
- private boolean lockParentForChildInsertRemove = false;
- @Dynamic
private EvictionConfig evictionConfig = null;
private String transactionManagerLookupClass = null;
private CacheLoaderConfig cacheLoaderConfig = null;
@@ -309,17 +307,6 @@
}
}
- /**
- * Sets whether inserting or removing a node requires a write lock on the node's parent (when pessimistic locking is
- * used.)
- * <p/>
- * The default value is <code>false</code>
- */
- public void setLockParentForChildInsertRemove(boolean lockParentForChildInsertRemove) {
- testImmutability("lockParentForChildInsertRemove");
- this.lockParentForChildInsertRemove = lockParentForChildInsertRemove;
- }
-
public void setUseLazyDeserialization(boolean useLazyDeserialization) {
testImmutability("useLazyDeserialization");
this.useLazyDeserialization = useLazyDeserialization;
@@ -383,16 +370,6 @@
return isolationLevel;
}
- /**
- * Gets whether inserting or removing a node requires a write lock on the node's parent (when pessimistic locking is
- * used.)
- * <p/>
- * The default value is <code>false</code>
- */
- public boolean isLockParentForChildInsertRemove() {
- return lockParentForChildInsertRemove;
- }
-
public String getTransactionManagerLookupClass() {
return transactionManagerLookupClass;
}
@@ -454,7 +431,6 @@
if (fetchInMemoryState != that.fetchInMemoryState) return false;
if (inactiveOnStartup != that.inactiveOnStartup) return false;
if (lockAcquisitionTimeout != that.lockAcquisitionTimeout) return false;
- if (lockParentForChildInsertRemove != that.lockParentForChildInsertRemove) return false;
if (replQueueInterval != that.replQueueInterval) return false;
if (replQueueMaxElements != that.replQueueMaxElements) return false;
if (stateRetrievalTimeout != that.stateRetrievalTimeout) return false;
@@ -490,7 +466,6 @@
result = 31 * result + (inactiveOnStartup ? 1 : 0);
result = 31 * result + (int) (stateRetrievalTimeout ^ (stateRetrievalTimeout >>> 32));
result = 31 * result + (isolationLevel != null ? isolationLevel.hashCode() : 0);
- result = 31 * result + (lockParentForChildInsertRemove ? 1 : 0);
result = 31 * result + (evictionConfig != null ? evictionConfig.hashCode() : 0);
result = 31 * result + (transactionManagerLookupClass != null ? transactionManagerLookupClass.hashCode() : 0);
result = 31 * result + (cacheLoaderConfig != null ? cacheLoaderConfig.hashCode() : 0);
Modified: core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserImpl.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserImpl.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -39,8 +39,8 @@
// the root element, representing the <horizon /> tag
Element rootElement;
- // root element builder that deals with
- private RootElementBuilder rootElementBuilder;
+ GlobalConfiguration gc;
+ Map<String, Configuration> namedCaches;
/**
* Constructs a new parser
@@ -86,40 +86,60 @@
public Configuration parseDefaultConfiguration() throws ConfigurationException {
assertInitialized();
- Element defaultElement = getSingleElementInCoreNS("default", rootElement);
- defaultElement.normalize();
- return parseConfiguration(defaultElement);
+ if (gc == null) {
+ Element defaultElement = getSingleElementInCoreNS("default", rootElement);
+ // there may not be a <default /> element!
+ if (defaultElement == null) {
+ return new Configuration();
+ } else {
+ defaultElement.normalize();
+ return parseConfiguration(defaultElement);
+ }
+ } else {
+ return gc.getDefaultConfiguration();
+ }
}
public Map<String, Configuration> parseNamedConfigurations() throws ConfigurationException {
assertInitialized();
- Set<Element> elements = getAllElementsInCoreNS("namedCache", rootElement);
- if (elements.isEmpty()) return Collections.emptyMap();
- Map<String, Configuration> namedConfigurations = new HashMap<String, Configuration>(elements.size(), 1.0f);
- for (Element e : elements) {
- String configurationName = getAttributeValue(e, "name");
- if (namedConfigurations.containsKey(configurationName))
- throw new DuplicateCacheNameException("Named cache " + configurationName + " is declared more than once!");
- namedConfigurations.put(configurationName, parseConfiguration(e));
+ // there may not be any namedCache elements!
+ if (namedCaches == null) {
+ Set<Element> elements = getAllElementsInCoreNS("namedCache", rootElement);
+ if (elements.isEmpty()) return Collections.emptyMap();
+ namedCaches = new HashMap<String, Configuration>(elements.size(), 1.0f);
+ for (Element e : elements) {
+ String configurationName = getAttributeValue(e, "name");
+ if (namedCaches.containsKey(configurationName)) {
+ namedCaches = null;
+ throw new DuplicateCacheNameException("Named cache " + configurationName + " is declared more than once!");
+ }
+ namedCaches.put(configurationName, parseConfiguration(e));
+ }
}
- return namedConfigurations;
+ return namedCaches;
}
public GlobalConfiguration parseGlobalConfiguration() {
assertInitialized();
- Element globalElement = getSingleElementInCoreNS("global", rootElement);
- globalElement.normalize();
- GlobalConfiguration gc = new GlobalConfiguration();
+ if (gc == null) {
+ Element globalElement = getSingleElementInCoreNS("global", rootElement);
+ Configuration defaultConfig = parseDefaultConfiguration();
+ gc = new GlobalConfiguration();
+ gc.setDefaultConfiguration(defaultConfig);
+ // there may not be a <global /> element in the config!!
+ if (globalElement != null) {
+ globalElement.normalize();
+ configureAsyncListenerExecutor(getSingleElementInCoreNS("asyncListenerExecutor", globalElement), gc);
+ configureAsyncSerializationExecutor(getSingleElementInCoreNS("asyncSerializationExecutor", globalElement), gc);
+ configureEvictionScheduledExecutor(getSingleElementInCoreNS("evictionScheduledExecutor", globalElement), gc);
+ configureReplicationQueueScheduledExecutor(getSingleElementInCoreNS("replicationQueueScheduledExecutor", globalElement), gc);
+ configureTransport(getSingleElementInCoreNS("transport", globalElement), gc);
+ configureShutdown(getSingleElementInCoreNS("shutdown", globalElement), gc);
+ configureSerialization(getSingleElementInCoreNS("serialization", globalElement), gc);
+ }
+ }
- configureAsyncListenerExecutor(getSingleElementInCoreNS("asyncListenerExecutor", globalElement), gc);
- configureAsyncSerializationExecutor(getSingleElementInCoreNS("asyncSerializationExecutor", globalElement), gc);
- configureEvictionScheduledExecutor(getSingleElementInCoreNS("evictionScheduledExecutor", globalElement), gc);
- configureReplicationQueueScheduledExecutor(getSingleElementInCoreNS("replicationQueueScheduledExecutor", globalElement), gc);
- configureTransport(getSingleElementInCoreNS("transport", globalElement), gc);
- configureShutdown(getSingleElementInCoreNS("shutdown", globalElement), gc);
- configureSerialization(getSingleElementInCoreNS("serialization", globalElement), gc);
-
return gc;
}
@@ -142,41 +162,6 @@
throw new ConfigurationException("Parser not initialized. Please invoke initialize() first, or use a constructor that initializes the parser.");
}
- /**
- * Parses an XML file and returns a new configuration. For looking up the file, {@link org.horizon.util.FileLookup}
- * is used.
- *
- * @see org.horizon.util.FileLookup
- */
-// public Configuration parseFile(String filename) {
-// InputStream is = new FileLookup().lookupFile(filename);
-// if (is == null) {
-// throw new ConfigurationException("Unable to find config file " + filename + " either in classpath or on the filesystem!");
-// }
-// return parseStream(is);
-// }
-
- /**
- * Similar to {@link #parseFile(String)}, just that it does not create the input stream.
- */
-// public Configuration parseStream(InputStream configStream) {
-// readRoot(configStream);
-// return processElements(false);
-// }
-//
-// public Configuration parseElement() {
-// rootElement.normalize();
-// return processElements(false);
-// }
-//
-// public Configuration parseElementIgnoringRoot() {
-// rootElement.normalize();
-// return processElements(true);
-// }
- public boolean isValidating() {
- return rootElementBuilder.isValidating();
- }
-
void configureClustering(Element e, Configuration config) {
if (e == null) return; //we might not have this configured
// there are 2 attribs - mode and clusterName
@@ -308,9 +293,6 @@
void configureLocking(Element element, Configuration config) {
String isolationLevel = getAttributeValue(element, "isolationLevel");
if (existsAttribute(isolationLevel)) config.setIsolationLevel(IsolationLevel.valueOf(isolationLevel));
- String lockParentForChildInsertRemove = getAttributeValue(element, "lockParentForChildInsertRemove");
- if (existsAttribute(lockParentForChildInsertRemove))
- config.setLockParentForChildInsertRemove(getBoolean(lockParentForChildInsertRemove));
String lockAcquisitionTimeout = getAttributeValue(element, "lockAcquisitionTimeout");
if (existsAttribute(lockAcquisitionTimeout)) config.setLockAcquisitionTimeout(getLong(lockAcquisitionTimeout));
String writeSkewCheck = getAttributeValue(element, "writeSkewCheck");
@@ -405,10 +387,6 @@
return getSingleElementInCoreNS(elementName, rootElement);
}
- private void readRoot(InputStream config) {
- rootElement = rootElementBuilder.readRoot(config);
- }
-
/**
* Tests whether the element passed in is a modern (3.0) config element rather than a legacy one.
*
Modified: core/branches/flat/src/main/java/org/horizon/factories/AbstractComponentRegistry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/AbstractComponentRegistry.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/factories/AbstractComponentRegistry.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -197,7 +197,7 @@
getLog().trace("Registering component {0} under name {1}", c, name);
componentLookup.put(name, c);
}
- c.nonVolatile = component.getClass().isAnnotationPresent(NonVolatile.class);
+ c.nonVolatile = ReflectionUtil.isAnnotationPresent(component.getClass(), NonVolatile.class);
addComponentDependencies(c);
// inject dependencies for this component
c.injectDependencies();
Modified: core/branches/flat/src/main/java/org/horizon/factories/ComponentRegistry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/ComponentRegistry.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/factories/ComponentRegistry.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -2,6 +2,7 @@
import org.horizon.CacheException;
import org.horizon.CacheSPI;
+import org.horizon.ComponentStatus;
import org.horizon.config.Configuration;
import org.horizon.config.ConfigurationException;
import org.horizon.factories.scopes.ScopeDetector;
@@ -95,4 +96,12 @@
Scopes componentScope = ScopeDetector.detectScope(clazz);
return componentScope == Scopes.GLOBAL;
}
+
+ @Override
+ public void start() {
+ if (globalComponents.getState() != ComponentStatus.STARTED || globalComponents.getState() != ComponentStatus.STARTING) {
+ globalComponents.start();
+ }
+ super.start();
+ }
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/GlobalComponentRegistry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/GlobalComponentRegistry.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/factories/GlobalComponentRegistry.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -4,6 +4,7 @@
import org.horizon.config.GlobalConfiguration;
import static org.horizon.config.GlobalConfiguration.ShutdownHookBehavior.DEFAULT;
import static org.horizon.config.GlobalConfiguration.ShutdownHookBehavior.REGISTER;
+import org.horizon.factories.annotations.NonVolatile;
import org.horizon.factories.scopes.Scope;
import org.horizon.factories.scopes.Scopes;
import org.horizon.logging.Log;
@@ -20,6 +21,7 @@
* @since 1.0
*/
@Scope(Scopes.GLOBAL)
+@NonVolatile
public class GlobalComponentRegistry extends AbstractComponentRegistry {
private Log log = LogFactory.getLog(GlobalComponentRegistry.class);
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/TxInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/TxInterceptor.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/TxInterceptor.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -38,8 +38,8 @@
import org.horizon.factories.context.ContextFactory;
import org.horizon.invocation.InvocationContextContainer;
import org.horizon.lock.LockManager;
+import org.horizon.manager.CacheManager;
import org.horizon.notifications.CacheNotifier;
-import org.horizon.remoting.RPCManager;
import org.horizon.remoting.ReplicationException;
import org.horizon.transaction.GlobalTransaction;
import org.horizon.transaction.TransactionTable;
@@ -68,11 +68,11 @@
*/
public class TxInterceptor extends BaseTransactionalContextInterceptor {
protected CommandsFactory commandsFactory;
- protected RPCManager rpcManager;
private CacheNotifier notifier;
private InvocationContextContainer invocationContextContainer;
private ComponentRegistry componentRegistry;
private ContextFactory contextFactory;
+ private CacheManager cacheManager;
/**
* List <Transaction>that we have registered for
@@ -87,12 +87,12 @@
private boolean statsEnabled;
@Inject
- public void intialize(RPCManager rpcManager, ContextFactory contextFactory,
+ public void intialize(CacheManager cacheManager, ContextFactory contextFactory,
CacheNotifier notifier, InvocationContextContainer icc,
CommandsFactory factory, ComponentRegistry componentRegistry, LockManager lockManager) {
this.contextFactory = contextFactory;
this.commandsFactory = factory;
- this.rpcManager = rpcManager;
+ this.cacheManager = cacheManager;
this.notifier = notifier;
this.invocationContextContainer = icc;
this.componentRegistry = componentRegistry;
@@ -129,7 +129,7 @@
return null;
}
try {
- if (trace) log.trace("(" + rpcManager.getAddress() + ") call on command [" + command + "]");
+ if (trace) log.trace("(" + cacheManager.getAddress() + ") call on command [" + command + "]");
GlobalTransaction gtx = ctx.getGlobalTransaction();
Transaction ltx = txTable.getLocalTransaction(gtx, true);
// disconnect if we have a current tx associated
@@ -172,7 +172,7 @@
return null;
}
try {
- if (trace) log.trace("(" + rpcManager.getAddress() + ") call on command [" + command + "]");
+ if (trace) log.trace("(" + cacheManager.getAddress() + ") call on command [" + command + "]");
GlobalTransaction gtx = ctx.getGlobalTransaction();
Transaction ltx = txTable.getLocalTransaction(gtx);
if (ltx == null) {
@@ -433,7 +433,7 @@
// --------------------------------------------------------------
protected PrepareCommand buildPrepareCommand(GlobalTransaction gtx, List modifications, boolean onePhaseCommit) {
- return commandsFactory.buildPrepareCommand(gtx, modifications, rpcManager.getAddress(), onePhaseCommit);
+ return commandsFactory.buildPrepareCommand(gtx, modifications, cacheManager.getAddress(), onePhaseCommit);
}
/**
Modified: core/branches/flat/src/main/java/org/horizon/lifecycle/Lifecycle.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/lifecycle/Lifecycle.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/lifecycle/Lifecycle.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -22,7 +22,7 @@
package org.horizon.lifecycle;
/**
- * // TODO: MANIK: Document this
+ * Lifecycle interface that defines the lifecycle of components
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
* @since 1.0
Modified: core/branches/flat/src/main/java/org/horizon/manager/CacheManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/manager/CacheManager.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/manager/CacheManager.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -1,8 +1,10 @@
package org.horizon.manager;
import org.horizon.Cache;
+import org.horizon.ComponentStatus;
import org.horizon.config.Configuration;
import org.horizon.config.DuplicateCacheNameException;
+import org.horizon.factories.annotations.NonVolatile;
import org.horizon.factories.scopes.Scope;
import org.horizon.factories.scopes.Scopes;
import org.horizon.lifecycle.Lifecycle;
@@ -49,6 +51,7 @@
* @since 1.0
*/
@Scope(Scopes.GLOBAL)
+@NonVolatile
public interface CacheManager extends Lifecycle, Listenable {
/**
* Defines a named cache. Named caches can be defined by using this method, in which case the configuration passed
@@ -94,4 +97,8 @@
List<Address> getMembers();
Address getAddress();
+
+ ComponentStatus getStatus();
+
+ boolean isCoordinator();
}
Modified: core/branches/flat/src/main/java/org/horizon/manager/DefaultCacheManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/manager/DefaultCacheManager.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/manager/DefaultCacheManager.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -22,7 +22,7 @@
package org.horizon.manager;
import org.horizon.Cache;
-import org.horizon.CacheSPI;
+import org.horizon.ComponentStatus;
import org.horizon.config.Configuration;
import org.horizon.config.ConfigurationException;
import org.horizon.config.DuplicateCacheNameException;
@@ -31,6 +31,9 @@
import org.horizon.config.parsing.XmlConfigurationParserImpl;
import org.horizon.factories.DefaultCacheFactory;
import org.horizon.factories.GlobalComponentRegistry;
+import org.horizon.factories.annotations.NonVolatile;
+import org.horizon.factories.scopes.Scope;
+import org.horizon.factories.scopes.Scopes;
import org.horizon.lifecycle.Lifecycle;
import org.horizon.notifications.CacheManagerNotifier;
import org.horizon.remoting.RPCManager;
@@ -82,6 +85,8 @@
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
* @since 1.0
*/
+(a)Scope(Scopes.GLOBAL)
+@NonVolatile
public class DefaultCacheManager implements CacheManager {
public static final String DEFAULT_CACHE_NAME = "org.jboss.starobrno.manager.DefaultCacheManager.DEFAULT_CACHE_NAME";
protected GlobalConfiguration globalConfiguration;
@@ -229,16 +234,18 @@
public DefaultCacheManager(InputStream configurationStream, boolean start) throws IOException {
try {
initialize(new XmlConfigurationParserImpl(configurationStream));
- }
- catch (RuntimeException re) {
+ } catch (ConfigurationException ce) {
+ throw ce;
+ } catch (RuntimeException re) {
throw new ConfigurationException(re);
}
if (start) start();
}
private void initialize(XmlConfigurationParser initializedParser) {
- this.globalConfiguration = initializedParser.parseGlobalConfiguration();
+ globalConfiguration = initializedParser.parseGlobalConfiguration();
configurationOverrides.putAll(initializedParser.parseNamedConfigurations());
+ globalComponentRegistry = new GlobalComponentRegistry(globalConfiguration, this);
}
/**
@@ -312,6 +319,11 @@
return rpcManager == null ? null : rpcManager.getAddress();
}
+ public boolean isCoordinator() {
+ RPCManager rpcManager = globalComponentRegistry.getComponent(RPCManager.class);
+ return rpcManager != null && rpcManager.isCoordinator();
+ }
+
private Cache createCache(String cacheName) {
Configuration c = globalConfiguration.getDefaultConfiguration().clone();
if (!cacheName.equals(DEFAULT_CACHE_NAME)) {
@@ -330,9 +342,7 @@
}
public void start() {
- // get a hold of the "default" cache to start this?
- CacheSPI defaultCache = (CacheSPI) getCache();
- globalComponentRegistry = defaultCache.getComponentRegistry().getGlobalComponentRegistry();
+ // nothing to do
}
public void stop() {
@@ -347,6 +357,7 @@
}
if (defaultCache != null) defaultCache.stop();
+ globalComponentRegistry.stop();
}
public void addListener(Object listener) {
@@ -363,4 +374,8 @@
CacheManagerNotifier notifier = globalComponentRegistry.getComponent(CacheManagerNotifier.class);
return notifier.getListeners();
}
+
+ public ComponentStatus getStatus() {
+ return globalComponentRegistry.getState();
+ }
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/CacheNotifierImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/CacheNotifierImpl.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/notifications/CacheNotifierImpl.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -40,6 +40,7 @@
import org.horizon.notifications.annotation.*;
import org.horizon.notifications.event.*;
import static org.horizon.notifications.event.Event.Type.*;
+import org.horizon.util.ReflectionUtil;
import org.horizon.util.concurrent.WithinThreadExecutor;
import javax.transaction.Transaction;
@@ -183,13 +184,12 @@
* @return true if callbacks on this class should use the syncProcessor; false if it should use the asyncProcessor.
*/
private static boolean testListenerClassValidity(Class<?> listenerClass) {
- Listener cl = listenerClass.getAnnotation(Listener.class);
- if (cl == null)
+ Listener l = ReflectionUtil.getAnnotation(listenerClass, Listener.class);
+ if (l == null)
throw new IncorrectCacheListenerException("Cache listener class MUST be annotated with org.horizon.notifications.annotation.Listener");
if (!Modifier.isPublic(listenerClass.getModifiers()))
throw new IncorrectCacheListenerException("Cache listener class MUST be public!");
- return cl.sync();
-
+ return l.sync();
}
private static void testListenerMethodValidity(Method m, Class allowedParameter, String annotationName) {
Modified: core/branches/flat/src/main/java/org/horizon/remoting/transport/Transport.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/transport/Transport.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/remoting/transport/Transport.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -2,6 +2,9 @@
import org.horizon.commands.ReplicableCommand;
import org.horizon.config.GlobalConfiguration;
+import org.horizon.factories.annotations.NonVolatile;
+import org.horizon.factories.scopes.Scope;
+import org.horizon.factories.scopes.Scopes;
import org.horizon.lifecycle.Lifecycle;
import org.horizon.marshall.Marshaller;
import org.horizon.notifications.CacheManagerNotifier;
@@ -20,6 +23,8 @@
* @author Manik Surtani
* @since 1.0
*/
+(a)Scope(Scopes.GLOBAL)
+@NonVolatile
public interface Transport extends Lifecycle {
/**
Modified: core/branches/flat/src/main/java/org/horizon/tree/TreeStructureSupport.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/TreeStructureSupport.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/tree/TreeStructureSupport.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -59,14 +59,10 @@
if (!fqn.isRoot()) {
if (!exists(parent)) createNodeInCache(parent);
AtomicMap<Object, Fqn> parentStructure = getStructure(parent);
- if (!cache.getConfiguration().isLockParentForChildInsertRemove()) {
- cache.getInvocationContext().getOptionOverrides().setSuppressLocking(true);
- }
+ // don't lock parents for child insert/removes!
+ cache.getInvocationContext().getOptionOverrides().setSuppressLocking(true);
parentStructure.put(fqn.getLastElement(), fqn);
-// updateStructure(parent, parentStructure);
}
-// FastCopyHashMap<Object, Fqn> structure = new FastCopyHashMap<Object, Fqn>();
-// cache.put(structureKey, structure);
cache.getAtomicMap(structureKey);
cache.getAtomicMap(dataKey);
return true;
Modified: core/branches/flat/src/main/java/org/horizon/util/ReflectionUtil.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/ReflectionUtil.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/util/ReflectionUtil.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -182,4 +182,16 @@
if (superclass == null) return null; // no where else to look
return getAnnotation(superclass, ann);
}
+
+ /**
+ * Tests whether an annotation is present on a class. The order tested is: <ul> <li>The class itself</li> <li>All
+ * implemented interfaces</li> <li>Any superclasses</li> </ul>
+ *
+ * @param clazz class to test
+ * @param annotation annotation to look for
+ * @return true if the annotation is found, false otherwise
+ */
+ public static boolean isAnnotationPresent(Class clazz, Class<? extends Annotation> annotation) {
+ return getAnnotation(clazz, annotation) != null;
+ }
}
Modified: core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -18,6 +18,7 @@
import org.horizon.interceptors.base.CommandInterceptor;
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;
@@ -131,6 +132,26 @@
}
/**
+ * 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.
*
@@ -194,7 +215,7 @@
while (System.currentTimeMillis() < failTime) {
sleepThread(100);
- if (isCacheViewComplete(cache, groupSize, barfIfTooManyMembersInView)) {
+ if (isCacheViewComplete(cache.getCacheManager().getMembers(), cache.getCacheManager().getAddress(), groupSize, barfIfTooManyMembersInView)) {
return;
}
}
@@ -218,7 +239,7 @@
int memberCount = caches.length;
for (int i = 0; i < memberCount; i++) {
- if (!isCacheViewComplete(caches[i], memberCount, barfIfTooManyMembers)) {
+ if (!isCacheViewComplete(caches[i].getCacheManager().getMembers(), caches[i].getCacheManager().getAddress(), memberCount, barfIfTooManyMembers)) {
return false;
}
}
@@ -241,6 +262,19 @@
return areCacheViewsComplete(c);
}
+ 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
@@ -277,19 +311,17 @@
* @param memberCount
*/
public static boolean isCacheViewComplete(Cache c, int memberCount) {
- return isCacheViewComplete(c, memberCount, true);
+ return isCacheViewComplete(c.getCacheManager().getMembers(), c.getCacheManager().getAddress(), memberCount, true);
}
- public static boolean isCacheViewComplete(Cache c, int memberCount, boolean barfIfTooManyMembers) {
- CacheSPI cache = (CacheSPI) c;
- List members = cache.getCacheManager().getMembers();
+ 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(cache.getCacheManager().getAddress());
+ sb.append(address);
sb.append(" had ");
sb.append(members.size());
sb.append(" members; expecting ");
Modified: core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -23,7 +23,7 @@
* @author <a href="mailto:manik@jboss.org">Manik Surtani</a>
*/
-@Test(groups = {"functional", "pessimistic"})
+@Test(groups = "functional", sequential = true)
public abstract class CacheAPITest {
private ThreadLocal<CacheSPI<String, String>> cacheTL = new ThreadLocal<CacheSPI<String, String>>();
@@ -71,7 +71,7 @@
public void testGetMembersInLocalMode() {
CacheSPI<String, String> cache = cacheTL.get();
- assert cache.getRPCManager().getAddress() == null : "Cache members should be null if running in LOCAL mode";
+ assert cache.getCacheManager().getAddress() == null : "Cache members should be null if running in LOCAL mode";
}
public void testConvenienceMethods() {
Modified: core/branches/flat/src/test/java/org/horizon/api/CacheSPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/CacheSPITest.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/test/java/org/horizon/api/CacheSPITest.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -1,87 +1,80 @@
package org.horizon.api;
-import org.horizon.CacheSPI;
-import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
import org.horizon.config.Configuration.CacheMode;
+import org.horizon.config.GlobalConfiguration;
+import org.horizon.manager.CacheManager;
+import org.horizon.manager.DefaultCacheManager;
import org.horizon.util.TestingUtil;
-import org.horizon.util.internals.ViewChangeListener;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
-import java.util.concurrent.TimeUnit;
-@Test(groups = {"functional", "pessimistic"})
+@Test(groups = "functional")
public class CacheSPITest {
- private ThreadLocal<CacheSPI<Object, Object>> cache1TL = new ThreadLocal<CacheSPI<Object, Object>>();
- private ThreadLocal<CacheSPI<Object, Object>> cache2TL = new ThreadLocal<CacheSPI<Object, Object>>();
+ private ThreadLocal<CacheManager> cacheManager1TL = new ThreadLocal<CacheManager>();
+ private ThreadLocal<CacheManager> cacheManager2TL = new ThreadLocal<CacheManager>();
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
+ GlobalConfiguration gc = GlobalConfiguration.getClusteredDefault();
+ Configuration conf = new Configuration();
+ conf.setCacheMode(CacheMode.REPL_SYNC);
- Configuration conf1 = new Configuration();
- conf1.setCacheMode(CacheMode.REPL_SYNC);
-
- Configuration conf2 = conf1.clone();
-
- CacheSPI<Object, Object> cache1 = (CacheSPI<Object, Object>) new UnitTestCacheFactory<Object, Object>().createCache(conf1, false);
- CacheSPI<Object, Object> cache2 = (CacheSPI<Object, Object>) new UnitTestCacheFactory<Object, Object>().createCache(conf2, false);
- cache1TL.set(cache1);
- cache2TL.set(cache2);
+ cacheManager1TL.set(new DefaultCacheManager(gc, conf, false));
+ cacheManager2TL.set(new DefaultCacheManager(gc, conf, false));
}
@AfterMethod(alwaysRun = true)
public void tearDown() throws Exception {
- CacheSPI<Object, Object> cache1 = cache1TL.get();
- CacheSPI<Object, Object> cache2 = cache2TL.get();
-
- TestingUtil.killCaches(cache1, cache2);
-
- cache1TL.set(null);
- cache2TL.set(null);
-
+ TestingUtil.killCacheManagers(cacheManager1TL.get(), cacheManager2TL.get());
+ cacheManager1TL.set(null);
+ cacheManager2TL.set(null);
}
public void testGetMembers() throws Exception {
- CacheSPI<Object, Object> cache1 = cache1TL.get();
- CacheSPI<Object, Object> cache2 = cache2TL.get();
+ CacheManager cm1 = cacheManager1TL.get();
+ CacheManager cm2 = cacheManager2TL.get();
- cache1.start();
- List memb1 = cache1.getRPCManager().getMembers();
+ cm1.start();
+ cm1.getCache(); // this will make sure any lazy components are started.
+ List memb1 = cm1.getMembers();
assert 1 == memb1.size();
Object coord = memb1.get(0);
- cache2.start();
- memb1 = cache1.getRPCManager().getMembers();
- TestingUtil.blockUntilViewsReceived(5000, false, cache1, cache2);
- List memb2 = cache2.getRPCManager().getMembers();
+ cm2.start();
+ cm2.getCache(); // this will make sure any lazy components are started.
+ TestingUtil.blockUntilViewsReceived(50000, true, cm1, cm2);
+ memb1 = cm1.getMembers();
+ List memb2 = cm2.getMembers();
assert 2 == memb1.size();
- assert memb1 == memb2;
+ assert memb1.equals(memb2);
- cache1.stop();
- TestingUtil.blockUntilViewsReceived(5000, false, cache2);
- memb2 = cache2.getRPCManager().getMembers();
+ cm1.stop();
+ TestingUtil.blockUntilViewsReceived(50000, false, cm2);
+ memb2 = cm2.getMembers();
assert 1 == memb2.size();
assert !coord.equals(memb2.get(0));
}
public void testIsCoordinator() throws Exception {
- CacheSPI<Object, Object> cache1 = cache1TL.get();
- CacheSPI<Object, Object> cache2 = cache2TL.get();
+ CacheManager cm1 = cacheManager1TL.get();
+ CacheManager cm2 = cacheManager2TL.get();
- cache1.start();
- assert cache1.getRPCManager().isCoordinator();
+ cm1.start();
+ cm1.getCache(); // this will make sure any lazy components are started.
+ assert cm1.isCoordinator();
- cache2.start();
- assert cache1.getRPCManager().isCoordinator();
- assert !cache2.getRPCManager().isCoordinator();
- ViewChangeListener viewChangeListener = new ViewChangeListener(cache2);
- cache1.stop();
+ cm2.start();
+ cm2.getCache(); // this will make sure any lazy components are started.
+ assert cm1.isCoordinator();
+ assert !cm2.isCoordinator();
+ cm1.stop();
// wait till cache2 gets the view change notification
- assert viewChangeListener.waitForViewChange(60, TimeUnit.SECONDS) : "Should have received a view change!";
- assert cache2.getRPCManager().isCoordinator();
+ TestingUtil.blockUntilViewsReceived(50000, false, cm2);
+ assert cm2.isCoordinator();
}
}
\ No newline at end of file
Deleted: core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTM.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTM.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTM.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -1,108 +0,0 @@
-package org.horizon.api.batch;
-
-import org.horizon.Cache;
-import org.horizon.UnitTestCacheFactory;
-import org.horizon.config.Configuration;
-import org.horizon.transaction.DummyTransactionManagerLookup;
-import org.horizon.util.TestingUtil;
-import org.testng.annotations.Test;
-
-import javax.transaction.TransactionManager;
-
-
-@Test(groups = {"functional", "transaction"})
-public class BatchWithTM extends AbstractBatchTest {
- public void testBatchWithOngoingTM() throws Exception {
- Cache<String, String> cache = null;
- try {
- cache = createCache();
- TransactionManager tm = 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"));
-
- cache.endBatch(false); // should be a no op
- assert "v".equals(cache.get("k"));
- assert "v2".equals(cache.get("k2"));
- }
- finally {
- TestingUtil.killCaches(cache);
- }
- }
-
- public void testBatchWithoutOngoingTMSuspension() throws Exception {
- Cache<String, String> cache = null;
- try {
- cache = createCache();
- TransactionManager tm = 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;
-
- 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 getOnDifferentThread(cache, "k") == null;
- assert getOnDifferentThread(cache, "k2") == null;
-
- cache.endBatch(true); // should be a no op
-
- assert "v".equals(getOnDifferentThread(cache, "k"));
- assert "v2".equals(getOnDifferentThread(cache, "k2"));
- }
- finally {
- TestingUtil.killCaches(cache);
- }
- }
-
- public void testBatchRollback() throws Exception {
- Cache<String, String> cache = null;
- try {
- cache = createCache();
- TransactionManager tm = getTransactionManager(cache);
- cache.startBatch();
- cache.put("k", "v");
- cache.put("k2", "v2");
-
- assert getOnDifferentThread(cache, "k") == null;
- assert getOnDifferentThread(cache, "k2") == null;
-
- cache.endBatch(false);
-
- assert getOnDifferentThread(cache, "k") == null;
- assert getOnDifferentThread(cache, "k2") == null;
- }
- finally {
- TestingUtil.killCaches(cache);
- }
- }
-
- private TransactionManager getTransactionManager(Cache<String, String> c) {
- return c.getConfiguration().getRuntimeConfig().getTransactionManager();
- }
-
- private Cache<String, String> createCache() {
- UnitTestCacheFactory<String, String> cf = new UnitTestCacheFactory<String, String>();
- 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);
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTMTest.java (from rev 7598, core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTM.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTMTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTMTest.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -0,0 +1,108 @@
+package org.horizon.api.batch;
+
+import org.horizon.Cache;
+import org.horizon.UnitTestCacheFactory;
+import org.horizon.config.Configuration;
+import org.horizon.transaction.DummyTransactionManagerLookup;
+import org.horizon.util.TestingUtil;
+import org.testng.annotations.Test;
+
+import javax.transaction.TransactionManager;
+
+
+@Test(groups = {"functional", "transaction"})
+public class BatchWithTMTest extends AbstractBatchTest {
+ public void testBatchWithOngoingTM() throws Exception {
+ Cache<String, String> cache = null;
+ try {
+ cache = createCache();
+ TransactionManager tm = 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"));
+
+ cache.endBatch(false); // should be a no op
+ assert "v".equals(cache.get("k"));
+ assert "v2".equals(cache.get("k2"));
+ }
+ finally {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testBatchWithoutOngoingTMSuspension() throws Exception {
+ Cache<String, String> cache = null;
+ try {
+ cache = createCache();
+ TransactionManager tm = 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;
+
+ 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 getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
+
+ cache.endBatch(true); // should be a no op
+
+ assert "v".equals(getOnDifferentThread(cache, "k"));
+ assert "v2".equals(getOnDifferentThread(cache, "k2"));
+ }
+ finally {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testBatchRollback() throws Exception {
+ Cache<String, String> cache = null;
+ try {
+ cache = createCache();
+ TransactionManager tm = getTransactionManager(cache);
+ cache.startBatch();
+ cache.put("k", "v");
+ cache.put("k2", "v2");
+
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
+
+ cache.endBatch(false);
+
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
+ }
+ finally {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ private TransactionManager getTransactionManager(Cache<String, String> c) {
+ return c.getConfiguration().getRuntimeConfig().getTransactionManager();
+ }
+
+ private Cache<String, String> createCache() {
+ UnitTestCacheFactory<String, String> cf = new UnitTestCacheFactory<String, String>();
+ 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);
+ }
+}
Property changes on: core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTMTest.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Deleted: core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTM.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTM.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTM.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -1,120 +0,0 @@
-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.testng.annotations.Test;
-
-@Test(groups = "functional")
-public class BatchWithoutTM extends AbstractBatchTest {
- public void testBatchWithoutCfg() {
- Cache<String, String> cache = null;
- 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
- }
- }
- finally {
- TestingUtil.killCaches(cache);
- }
- }
-
- public void testEndBatchWithoutStartBatch() {
- Cache<String, String> cache = null;
- try {
- cache = createCache(true);
- cache.endBatch(true);
- cache.endBatch(false);
- // should not fail.
- }
- finally {
- TestingUtil.killCaches(cache);
- }
- }
-
- 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);
-
- assert "v".equals(cache.get("k"));
- assert "v2".equals(cache.get("k2"));
- }
- finally {
- TestingUtil.killCaches(cache);
- }
- }
-
- 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.endBatch(true);
-
- assert "v".equals(getOnDifferentThread(cache, "k"));
- }
- finally {
- TestingUtil.killCaches(cache);
- }
- }
-
- public void testBatchRollback() throws Exception {
- Cache<String, String> cache = null;
- try {
- cache = createCache(true);
- cache.startBatch();
- cache.put("k", "v");
- cache.put("k2", "v2");
-
- assert getOnDifferentThread(cache, "k") == null;
- assert getOnDifferentThread(cache, "k2") == null;
-
- cache.endBatch(false);
-
- assert getOnDifferentThread(cache, "k") == null;
- assert getOnDifferentThread(cache, "k2") == null;
- }
- finally {
- TestingUtil.killCaches(cache);
- }
- }
-
- private Cache<String, String> createCache(boolean enableBatch) {
- UnitTestCacheFactory<String, String> cf = new UnitTestCacheFactory<String, String>();
- Configuration c = new Configuration();
- c.setInvocationBatchingEnabled(enableBatch);
- return cf.createCache(c);
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTMTest.java (from rev 7598, core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTM.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTMTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTMTest.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -0,0 +1,120 @@
+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.testng.annotations.Test;
+
+@Test(groups = "functional")
+public class BatchWithoutTMTest extends AbstractBatchTest {
+ public void testBatchWithoutCfg() {
+ Cache<String, String> cache = null;
+ 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
+ }
+ }
+ finally {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testEndBatchWithoutStartBatch() {
+ Cache<String, String> cache = null;
+ try {
+ cache = createCache(true);
+ cache.endBatch(true);
+ cache.endBatch(false);
+ // should not fail.
+ }
+ finally {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ 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);
+
+ assert "v".equals(cache.get("k"));
+ assert "v2".equals(cache.get("k2"));
+ }
+ finally {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ 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.endBatch(true);
+
+ assert "v".equals(getOnDifferentThread(cache, "k"));
+ }
+ finally {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testBatchRollback() throws Exception {
+ Cache<String, String> cache = null;
+ try {
+ cache = createCache(true);
+ cache.startBatch();
+ cache.put("k", "v");
+ cache.put("k2", "v2");
+
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
+
+ cache.endBatch(false);
+
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
+ }
+ finally {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ private Cache<String, String> createCache(boolean enableBatch) {
+ UnitTestCacheFactory<String, String> cf = new UnitTestCacheFactory<String, String>();
+ Configuration c = new Configuration();
+ c.setInvocationBatchingEnabled(enableBatch);
+ return cf.createCache(c);
+ }
+}
Property changes on: core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTMTest.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
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-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -1,7 +1,6 @@
package org.horizon.api.mvcc;
import org.horizon.Cache;
-import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
import org.horizon.invocation.InvocationContextContainer;
import org.horizon.lock.IsolationLevel;
@@ -9,6 +8,8 @@
import org.horizon.lock.TimeoutException;
import org.horizon.logging.Log;
import org.horizon.logging.LogFactory;
+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;
@@ -22,7 +23,7 @@
/**
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
*/
-@Test(groups = {"functional", "mvcc"})
+@Test(groups = {"functional", "mvcc"}, sequential = true)
public abstract class LockTestBase {
protected boolean repeatableRead = true;
protected boolean lockParentForChildInsertRemove = false;
@@ -41,13 +42,12 @@
@BeforeMethod
public void setUp() {
LockTestBaseTL tl = new LockTestBaseTL();
- tl.cache = new UnitTestCacheFactory<String, String>().createCache(new Configuration(), false);
- tl.cache.getConfiguration().setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- tl.cache.getConfiguration().setIsolationLevel(repeatableRead ? IsolationLevel.REPEATABLE_READ : IsolationLevel.READ_COMMITTED);
- tl.cache.getConfiguration().setLockParentForChildInsertRemove(lockParentForChildInsertRemove);
- // reduce lock acquisition timeout so this doesn't take forever to run
- tl.cache.getConfiguration().setLockAcquisitionTimeout(200); // 200 ms
- tl.cache.start();
+ Configuration defaultCfg = new Configuration();
+ defaultCfg.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ defaultCfg.setIsolationLevel(repeatableRead ? IsolationLevel.REPEATABLE_READ : IsolationLevel.READ_COMMITTED);
+ defaultCfg.setLockAcquisitionTimeout(200); // 200 ms
+ CacheManager cm = new DefaultCacheManager(defaultCfg);
+ tl.cache = cm.getCache();
tl.lockManager = TestingUtil.extractComponentRegistry(tl.cache).getComponent(LockManager.class);
tl.icc = TestingUtil.extractComponentRegistry(tl.cache).getComponent(InvocationContextContainer.class);
tl.tm = TestingUtil.extractComponentRegistry(tl.cache).getComponent(TransactionManager.class);
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-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -1,16 +1,17 @@
package org.horizon.api.mvcc.repeatable_read;
import org.horizon.Cache;
-import org.horizon.UnitTestCacheFactory;
import org.horizon.api.mvcc.LockAssert;
import org.horizon.config.Configuration;
import org.horizon.invocation.InvocationContextContainer;
import org.horizon.lock.IsolationLevel;
import org.horizon.lock.LockManager;
+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.AfterTest;
+import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import javax.transaction.SystemException;
@@ -22,24 +23,25 @@
@Test(groups = {"functional", "mvcc"}, sequential = true)
public class WriteSkewTest {
- protected Cache<String, String> cache;
protected TransactionManager tm;
protected LockManager lockManager;
protected InvocationContextContainer icc;
- protected boolean repeatableRead = true;
+ protected CacheManager cacheManager;
+ protected Cache cache;
- @BeforeMethod
+ @BeforeTest
public void setUp() {
- cache = new UnitTestCacheFactory<String, String>().createCache(new Configuration(), false);
- cache.getConfiguration().setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- cache.getConfiguration().setIsolationLevel(repeatableRead ? IsolationLevel.REPEATABLE_READ : IsolationLevel.READ_COMMITTED);
- // reduce lock acquisition timeout so this doesn't take forever to run
- cache.getConfiguration().setLockAcquisitionTimeout(200); // 200 ms
+ Configuration c = new Configuration();
+ c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ c.setLockAcquisitionTimeout(200);
+ c.setIsolationLevel(IsolationLevel.REPEATABLE_READ);
+
+ cacheManager = new DefaultCacheManager(c);
}
- @AfterMethod
+ @AfterTest
public void tearDown() {
- TestingUtil.killCaches(cache);
+ TestingUtil.killCacheManagers(cacheManager);
}
private void postStart() {
@@ -53,104 +55,100 @@
}
public void testDontCheckWriteSkew() throws Exception {
- cache.getConfiguration().setWriteSkewCheck(false);
- cache.start();
+ Configuration noWriteSkewCheck = new Configuration();
+ noWriteSkewCheck.setWriteSkewCheck(false);
+ cacheManager.defineCache("noWriteSkewCheck", noWriteSkewCheck);
+ cache = cacheManager.getCache("noWriteSkewCheck");
postStart();
doTest(true);
}
public void testCheckWriteSkew() throws Exception {
- cache.getConfiguration().setWriteSkewCheck(true);
- cache.start();
+ Configuration writeSkewCheck = new Configuration();
+ writeSkewCheck.setWriteSkewCheck(true);
+ cacheManager.defineCache("writeSkewCheck", writeSkewCheck);
+ cache = cacheManager.getCache("writeSkewCheck");
postStart();
doTest(false);
}
private void doTest(final boolean allowWriteSkew) throws Exception {
- if (repeatableRead) {
- cache.put("k", "v");
- final Set<Exception> w1exceptions = new HashSet<Exception>();
- final Set<Exception> w2exceptions = new HashSet<Exception>();
- final CountDownLatch w1Signal = new CountDownLatch(1);
- final CountDownLatch w2Signal = new CountDownLatch(1);
- final CountDownLatch threadSignal = new CountDownLatch(2);
+ cache.put("k", "v");
+ final Set<Exception> w1exceptions = new HashSet<Exception>();
+ final Set<Exception> w2exceptions = new HashSet<Exception>();
+ final CountDownLatch w1Signal = new CountDownLatch(1);
+ final CountDownLatch w2Signal = new CountDownLatch(1);
+ final CountDownLatch threadSignal = new CountDownLatch(2);
- Thread w1 = new Thread("Writer-1") {
- public void run() {
- boolean didCoundDown = false;
- try {
- tm.begin();
- assert "v".equals(cache.get("k"));
- threadSignal.countDown();
- didCoundDown = true;
- w1Signal.await();
- cache.put("k", "v2");
- tm.commit();
- }
- catch (Exception e) {
- w1exceptions.add(e);
- }
- finally {
- if (!didCoundDown) threadSignal.countDown();
- }
+ Thread w1 = new Thread("Writer-1") {
+ public void run() {
+ boolean didCoundDown = false;
+ try {
+ tm.begin();
+ assert "v".equals(cache.get("k"));
+ threadSignal.countDown();
+ didCoundDown = true;
+ w1Signal.await();
+ cache.put("k", "v2");
+ tm.commit();
}
- };
+ catch (Exception e) {
+ w1exceptions.add(e);
+ }
+ finally {
+ if (!didCoundDown) threadSignal.countDown();
+ }
+ }
+ };
- Thread w2 = new Thread("Writer-2") {
- public void run() {
- boolean didCoundDown = false;
- try {
- tm.begin();
- assert "v".equals(cache.get("k"));
- threadSignal.countDown();
- didCoundDown = true;
- w2Signal.await();
- cache.put("k", "v3");
- tm.commit();
- }
- catch (Exception e) {
- w2exceptions.add(e);
- // the exception will be thrown when doing a cache.put(). We should make sure we roll back the tx to release locks.
- if (!allowWriteSkew) {
- try {
- tm.rollback();
- }
- catch (SystemException e1) {
- // do nothing.
- }
+ Thread w2 = new Thread("Writer-2") {
+ public void run() {
+ boolean didCoundDown = false;
+ try {
+ tm.begin();
+ assert "v".equals(cache.get("k"));
+ threadSignal.countDown();
+ didCoundDown = true;
+ w2Signal.await();
+ cache.put("k", "v3");
+ tm.commit();
+ }
+ catch (Exception e) {
+ w2exceptions.add(e);
+ // the exception will be thrown when doing a cache.put(). We should make sure we roll back the tx to release locks.
+ if (!allowWriteSkew) {
+ try {
+ tm.rollback();
}
+ catch (SystemException e1) {
+ // do nothing.
+ }
}
- finally {
- if (!didCoundDown) threadSignal.countDown();
- }
}
- };
+ finally {
+ if (!didCoundDown) threadSignal.countDown();
+ }
+ }
+ };
- w1.start();
- w2.start();
+ w1.start();
+ w2.start();
- threadSignal.await();
- // now. both txs have read.
- // let tx1 start writing
- w1Signal.countDown();
- w1.join();
+ threadSignal.await();
+ // now. both txs have read.
+ // let tx1 start writing
+ w1Signal.countDown();
+ w1.join();
- w2Signal.countDown();
- w2.join();
+ w2Signal.countDown();
+ w2.join();
- if (allowWriteSkew) {
- // should have no exceptions!!
- throwExceptions(w1exceptions, w2exceptions);
- assert w2exceptions.size() == 0;
- assert w1exceptions.size() == 0;
- assert "v3".equals(cache.get("k")) : "W2 should have overwritten W1's work!";
- } else {
- // there should be a single exception from w2.
- assert w2exceptions.size() == 1;
- throwExceptions(w1exceptions);
- assert w1exceptions.size() == 0;
- assert "v2".equals(cache.get("k")) : "W2 should NOT have overwritten W1's work!";
- }
+ if (allowWriteSkew) {
+ // should have no exceptions!!
+ throwExceptions(w1exceptions, w2exceptions);
+ assert w2exceptions.size() == 0;
+ assert w1exceptions.size() == 0;
+ assert "v3".equals(cache.get("k")) : "W2 should have overwritten W1's work!";
assertNoLocks();
}
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-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -556,7 +556,6 @@
Cache<Object, Object> cache = tree.getCache();
assert TreeStructureSupport.isLocked(cache, C);
- assert !cache.getConfiguration().isLockParentForChildInsertRemove() || TreeStructureSupport.isLocked(cache, A_B);
assert TreeStructureSupport.isLocked(cache, A_B_C);
}
@@ -565,7 +564,6 @@
Cache<Object, Object> cache = tree.getCache();
// /a/b, /c, /c/e, /a/b/c and /a/b/c/e should all be locked.
- assert !cache.getConfiguration().isLockParentForChildInsertRemove() || TreeStructureSupport.isLocked(cache, A_B);
assert TreeStructureSupport.isLocked(cache, C);
assert TreeStructureSupport.isLocked(cache, C_E);
assert TreeStructureSupport.isLocked(cache, A_B_C);
Modified: core/branches/flat/src/test/java/org/horizon/manager/CacheManagerXmlConfigurationTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/manager/CacheManagerXmlConfigurationTest.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/test/java/org/horizon/manager/CacheManagerXmlConfigurationTest.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -3,9 +3,12 @@
import org.horizon.Cache;
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;
+import javax.transaction.TransactionManager;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -29,29 +32,29 @@
Cache c = cm.getCache();
assert c.getConfiguration().getConcurrencyLevel() == 100;
assert c.getConfiguration().getLockAcquisitionTimeout() == 1000;
- assert c.getConfiguration().getRuntimeConfig().getTransactionManager() == null;
- assert c.getConfiguration().getRuntimeConfig().getRPCManager() == null;
+ assert TestingUtil.extractComponent(c, TransactionManager.class) == null;
+ assert TestingUtil.extractComponent(c, RPCManager.class) != null : "This should not be null, since a shared RPC manager should be present";
// test the "transactional" cache
c = cm.getCache("transactional");
assert c.getConfiguration().getConcurrencyLevel() == 100;
assert c.getConfiguration().getLockAcquisitionTimeout() == 1000;
- assert c.getConfiguration().getRuntimeConfig().getTransactionManager() != null;
- assert c.getConfiguration().getRuntimeConfig().getRPCManager() == null;
+ assert TestingUtil.extractComponent(c, TransactionManager.class) != null;
+ assert TestingUtil.extractComponent(c, RPCManager.class) != null : "This should not be null, since a shared RPC manager should be present";
// test the "replicated" cache
c = cm.getCache("syncRepl");
assert c.getConfiguration().getConcurrencyLevel() == 100;
assert c.getConfiguration().getLockAcquisitionTimeout() == 1000;
- assert c.getConfiguration().getRuntimeConfig().getTransactionManager() == null;
- assert c.getConfiguration().getRuntimeConfig().getRPCManager() != null;
+ assert TestingUtil.extractComponent(c, TransactionManager.class) == null;
+ assert TestingUtil.extractComponent(c, RPCManager.class) != null : "This should not be null, since a shared RPC manager should be present";
// test the "txSyncRepl" cache
c = cm.getCache("txSyncRepl");
assert c.getConfiguration().getConcurrencyLevel() == 100;
assert c.getConfiguration().getLockAcquisitionTimeout() == 1000;
- assert c.getConfiguration().getRuntimeConfig().getTransactionManager() != null;
- assert c.getConfiguration().getRuntimeConfig().getRPCManager() != null;
+ assert TestingUtil.extractComponent(c, TransactionManager.class) != null;
+ assert TestingUtil.extractComponent(c, RPCManager.class) != null : "This should not be null, since a shared RPC manager should be present";
}
public void testNamedCacheXMLClashingNames() throws IOException {
@@ -78,9 +81,10 @@
try {
cm = new DefaultCacheManager(bais);
assert false : "Should fail";
- }
- catch (DuplicateCacheNameException expected) {
+ } catch (Throwable expected) {
+ System.out.println("Blah");
+
}
}
Modified: core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -55,7 +55,6 @@
cfg.setCacheMode(Configuration.CacheMode.LOCAL);
cfg.setConcurrencyLevel(2000);
cfg.setLockAcquisitionTimeout(120000);
- cfg.setLockParentForChildInsertRemove(true);
cfg.setIsolationLevel(IsolationLevel.READ_COMMITTED);
Cache c = new UnitTestCacheFactory().createCache(cfg);
cache = new TreeCacheImpl(c);
Modified: core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -68,7 +68,7 @@
cache1.start();
cache2.start();
- TestingUtil.blockUntilViewsReceived(60000, cache1, cache2);
+ TestingUtil.blockUntilViewsReceived(10000, cache1, cache2);
cache1.put("k", "v");
}
Modified: core/branches/flat/src/test/java/org/horizon/util/internals/ViewChangeListener.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/util/internals/ViewChangeListener.java 2009-01-27 17:21:19 UTC (rev 7602)
+++ core/branches/flat/src/test/java/org/horizon/util/internals/ViewChangeListener.java 2009-01-27 18:01:32 UTC (rev 7603)
@@ -1,6 +1,6 @@
package org.horizon.util.internals;
-import org.horizon.Cache;
+import org.horizon.manager.CacheManager;
import org.horizon.notifications.annotation.Listener;
import org.horizon.notifications.annotation.ViewChanged;
import org.horizon.notifications.event.ViewChangedEvent;
@@ -31,9 +31,9 @@
*
* @param cache cache to listen on for view change events
*/
- public ViewChangeListener(Cache cache) {
+ public ViewChangeListener(CacheManager cacheManager) {
this.latch = new CountDownLatch(1);
- cache.addListener(this);
+ cacheManager.addListener(this);
}
@ViewChanged
15 years, 11 months
JBoss Cache SVN: r7601 - core/branches/flat/src/test/java/org/horizon/config/parsing.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2009-01-27 06:33:48 -0500 (Tue, 27 Jan 2009)
New Revision: 7601
Removed:
core/branches/flat/src/test/java/org/horizon/config/parsing/XMLFileParsingTest.java
Log:
More parser tests
Deleted: 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-01-27 11:33:18 UTC (rev 7600)
+++ core/branches/flat/src/test/java/org/horizon/config/parsing/XMLFileParsingTest.java 2009-01-27 11:33:48 UTC (rev 7601)
@@ -1,164 +0,0 @@
-package org.horizon.config.parsing;
-
-import org.horizon.config.Configuration;
-import org.horizon.config.GlobalConfiguration;
-import org.horizon.lock.IsolationLevel;
-import org.testng.annotations.Test;
-
-import java.io.IOException;
-import java.util.Map;
-
-@Test(groups = "unit")
-public class XmlFileParsingTest {
- public void testNamedCacheFile() throws IOException {
- XmlConfigurationParser parser = new XmlConfigurationParserImpl("configs/named-cache-test.xml");
-
- GlobalConfiguration gc = parser.parseGlobalConfiguration();
-
- assert gc.getAsyncListenerExecutorFactoryClass().equals("org.horizon.executors.DefaultExecutorFactory");
- assert gc.getAsyncListenerExecutorProperties().getProperty("maxThreads").equals("5");
- assert gc.getAsyncListenerExecutorProperties().getProperty("threadNamePrefix").equals("AsyncListenerThread");
-
- assert gc.getAsyncSerializationExecutorFactoryClass().equals("org.horizon.executors.DefaultExecutorFactory");
- assert gc.getAsyncSerializationExecutorProperties().getProperty("maxThreads").equals("25");
- assert gc.getAsyncSerializationExecutorProperties().getProperty("threadNamePrefix").equals("AsyncSerializationThread");
-
- assert gc.getEvictionScheduledExecutorFactoryClass().equals("org.horizon.executors.DefaultScheduledExecutorFactory");
- assert gc.getEvictionScheduledExecutorProperties().getProperty("threadNamePrefix").equals("EvictionThread");
-
- assert gc.getReplicationQueueScheduledExecutorFactoryClass().equals("org.horizon.executors.DefaultScheduledExecutorFactory");
- assert gc.getReplicationQueueScheduledExecutorProperties().getProperty("threadNamePrefix").equals("ReplicationQueueThread");
-
- assert gc.getTransportClass().equals("org.horizon.remoting.transport.jgroups.JGroupsTransport");
- assert gc.getTransportProperties().isEmpty();
-
- assert gc.getMarshallerClass().equals("org.horizon.marshall.VersionAwareMarshaller");
- assert gc.getMarshallVersionString().equals("1.0");
- assert gc.getObjectOutputStreamPoolSize() == 100;
- assert gc.getObjectInputStreamPoolSize() == 100;
-
- Configuration defaultConfiguration = parser.parseDefaultConfiguration();
-
- assert defaultConfiguration.getLockAcquisitionTimeout() == 1000;
- assert defaultConfiguration.getConcurrencyLevel() == 100;
- assert defaultConfiguration.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
-
- Map<String, Configuration> namedCaches = parser.parseNamedConfigurations();
-
- Configuration c = namedCaches.get("transactional");
-
- assert c.getTransactionManagerLookupClass().equals("org.horizon.transaction.GenericTransactionManagerLookup");
-
- c = namedCaches.get("syncRepl");
-
- assert c.getCacheMode() == Configuration.CacheMode.REPL_SYNC;
- assert c.isFetchInMemoryState();
- assert c.getStateRetrievalTimeout() == 15000;
- assert c.getSyncReplTimeout() == 15000;
-
- c = namedCaches.get("asyncRepl");
-
- assert c.getCacheMode() == Configuration.CacheMode.REPL_ASYNC;
- assert !c.isUseReplQueue();
- assert !c.isUseAsyncSerialization();
- assert c.isFetchInMemoryState();
- assert c.getStateRetrievalTimeout() == 15000;
-
- c = namedCaches.get("asyncReplQueue");
-
- assert c.getCacheMode() == Configuration.CacheMode.REPL_ASYNC;
- assert c.isUseReplQueue();
- assert c.isUseAsyncSerialization();
- assert c.isFetchInMemoryState();
- assert c.getStateRetrievalTimeout() == 15000;
-
- c = namedCaches.get("txSyncRepl");
-
- assert c.getTransactionManagerLookupClass().equals("org.horizon.transaction.GenericTransactionManagerLookup");
- assert c.getCacheMode() == Configuration.CacheMode.REPL_SYNC;
- assert c.isFetchInMemoryState();
- assert c.getStateRetrievalTimeout() == 15000;
- assert c.getSyncReplTimeout() == 15000;
-
- c = namedCaches.get("overriding");
-
- assert c.getTransactionManagerLookupClass() == null;
- assert c.getCacheMode() == Configuration.CacheMode.LOCAL;
- assert c.getLockAcquisitionTimeout() == 20000;
- assert c.getConcurrencyLevel() == 1000;
- assert c.getIsolationLevel() == IsolationLevel.REPEATABLE_READ;
- }
-
- public void testConfigurationMerging() throws IOException {
- XmlConfigurationParser parser = new XmlConfigurationParserImpl("configs/named-cache-test.xml");
- Configuration defaultCfg = parser.parseDefaultConfiguration();
- Map<String, Configuration> namedCaches = parser.parseNamedConfigurations();
-
- Configuration c = defaultCfg.clone();
- c.applyOverrides(namedCaches.get("transactional"));
-
- assert c.getCacheMode() == Configuration.CacheMode.LOCAL;
- assert c.getTransactionManagerLookupClass().equals("org.horizon.transaction.GenericTransactionManagerLookup");
- assert c.getLockAcquisitionTimeout() == 1000;
- assert c.getConcurrencyLevel() == 100;
- assert c.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
-
- c = defaultCfg.clone();
- c.applyOverrides(namedCaches.get("syncRepl"));
-
- assert c.getTransactionManagerLookupClass() == null;
- assert c.getCacheMode() == Configuration.CacheMode.REPL_SYNC;
- assert c.isFetchInMemoryState();
- assert c.getStateRetrievalTimeout() == 15000;
- assert c.getSyncReplTimeout() == 15000;
- assert c.getLockAcquisitionTimeout() == 1000;
- assert c.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
- assert c.getConcurrencyLevel() == 100;
-
- c = defaultCfg.clone();
- c.applyOverrides(namedCaches.get("asyncRepl"));
-
- assert c.getTransactionManagerLookupClass() == null;
- assert c.getCacheMode() == Configuration.CacheMode.REPL_ASYNC;
- assert !c.isUseReplQueue();
- assert !c.isUseAsyncSerialization();
- assert c.isFetchInMemoryState();
- assert c.getStateRetrievalTimeout() == 15000;
- assert c.getLockAcquisitionTimeout() == 1000;
- assert c.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
- assert c.getConcurrencyLevel() == 100;
-
- c = defaultCfg.clone();
- c.applyOverrides(namedCaches.get("asyncReplQueue"));
-
- assert c.getTransactionManagerLookupClass() == null;
- assert c.getCacheMode() == Configuration.CacheMode.REPL_ASYNC;
- assert c.isUseReplQueue();
- assert c.isUseAsyncSerialization();
- assert c.isFetchInMemoryState();
- assert c.getStateRetrievalTimeout() == 15000;
- assert c.getLockAcquisitionTimeout() == 1000;
- assert c.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
- assert c.getConcurrencyLevel() == 100;
-
- c = defaultCfg.clone();
- c.applyOverrides(namedCaches.get("txSyncRepl"));
- assert c.getTransactionManagerLookupClass().equals("org.horizon.transaction.GenericTransactionManagerLookup");
- assert c.getCacheMode() == Configuration.CacheMode.REPL_SYNC;
- assert c.isFetchInMemoryState();
- assert c.getStateRetrievalTimeout() == 15000;
- assert c.getSyncReplTimeout() == 15000;
- assert c.getLockAcquisitionTimeout() == 1000;
- assert c.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
- assert c.getConcurrencyLevel() == 100;
-
- c = defaultCfg.clone();
- c.applyOverrides(namedCaches.get("overriding"));
-
- assert c.getTransactionManagerLookupClass() == null;
- assert c.getCacheMode() == Configuration.CacheMode.LOCAL;
- assert c.getLockAcquisitionTimeout() == 20000;
- assert c.getConcurrencyLevel() == 1000;
- assert c.getIsolationLevel() == IsolationLevel.REPEATABLE_READ;
- }
-}
15 years, 11 months
JBoss Cache SVN: r7600 - core/branches/flat/src/test/resources/configs.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2009-01-27 06:33:18 -0500 (Tue, 27 Jan 2009)
New Revision: 7600
Modified:
core/branches/flat/src/test/resources/configs/named-cache-test.xml
Log:
More parser tests
Modified: core/branches/flat/src/test/resources/configs/named-cache-test.xml
===================================================================
--- core/branches/flat/src/test/resources/configs/named-cache-test.xml 2009-01-27 11:32:29 UTC (rev 7599)
+++ core/branches/flat/src/test/resources/configs/named-cache-test.xml 2009-01-27 11:33:18 UTC (rev 7600)
@@ -65,4 +65,8 @@
</clustering>
</namedCache>
+ <namedCache name="overriding">
+ <locking isolationLevel="REPEATABLE_READ" concurrencyLevel="1000" lockAcquisitionTimeout="20000" />
+ </namedCache>
+
</horizon>
15 years, 11 months
JBoss Cache SVN: r7599 - in core/branches/flat/src: test/java/org/horizon/config/parsing and 1 other directory.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2009-01-27 06:32:29 -0500 (Tue, 27 Jan 2009)
New Revision: 7599
Added:
core/branches/flat/src/test/java/org/horizon/config/parsing/XMLFileParsingTest.java
Modified:
core/branches/flat/src/main/java/org/horizon/config/Configuration.java
core/branches/flat/src/test/java/org/horizon/config/parsing/ConfigurationParserTest.java
core/branches/flat/src/test/java/org/horizon/config/parsing/XmlFileParsingTest.java
Log:
More parser tests
Modified: core/branches/flat/src/main/java/org/horizon/config/Configuration.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/Configuration.java 2009-01-27 01:51:15 UTC (rev 7598)
+++ core/branches/flat/src/main/java/org/horizon/config/Configuration.java 2009-01-27 11:32:29 UTC (rev 7599)
@@ -131,7 +131,7 @@
private boolean inactiveOnStartup = false;
@Dynamic
private long stateRetrievalTimeout = 10000;
- private IsolationLevel isolationLevel = IsolationLevel.REPEATABLE_READ;
+ private IsolationLevel isolationLevel = IsolationLevel.READ_COMMITTED;
@Dynamic
private boolean lockParentForChildInsertRemove = false;
@Dynamic
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-01-27 01:51:15 UTC (rev 7598)
+++ core/branches/flat/src/test/java/org/horizon/config/parsing/ConfigurationParserTest.java 2009-01-27 11:32:29 UTC (rev 7599)
@@ -134,28 +134,6 @@
assert !c.isUseReplQueue();
}
- /*
-
- <loaders passivation="true" shared="true" preload="true">
- <loader class="org.horizon.loader.JDBCCacheLoader" async="true" fetchPersistentState="true"
- ignoreModifications="false" purgeOnStartup="false">
- <properties>
- horizon.jdbc.datasource=HorizonDS
- horizon.jdbc.table.name=horizon
- horizon.jdbc.table.create=true
- horizon.jdbc.table.drop=false
- </properties>
- <singletonStore enabled="true" class="org.horizon.loader.SingletonStoreCacheLoader">
- <properties>
- horizon.singletonStore.pushStateWhenCoordinator=true
- horizon.singletonStore.pushStateWhenCoordinatorTimeout=20000
- </properties>
- </singletonStore>
- </loader>
- </loaders>
-
- */
-
public void testCacheLoaders() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<loaders passivation=\"true\" shared=\"true\" preload=\"true\">\n" +
Added: core/branches/flat/src/test/java/org/horizon/config/parsing/XMLFileParsingTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/config/parsing/XMLFileParsingTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/config/parsing/XMLFileParsingTest.java 2009-01-27 11:32:29 UTC (rev 7599)
@@ -0,0 +1,164 @@
+package org.horizon.config.parsing;
+
+import org.horizon.config.Configuration;
+import org.horizon.config.GlobalConfiguration;
+import org.horizon.lock.IsolationLevel;
+import org.testng.annotations.Test;
+
+import java.io.IOException;
+import java.util.Map;
+
+@Test(groups = "unit")
+public class XmlFileParsingTest {
+ public void testNamedCacheFile() throws IOException {
+ XmlConfigurationParser parser = new XmlConfigurationParserImpl("configs/named-cache-test.xml");
+
+ GlobalConfiguration gc = parser.parseGlobalConfiguration();
+
+ assert gc.getAsyncListenerExecutorFactoryClass().equals("org.horizon.executors.DefaultExecutorFactory");
+ assert gc.getAsyncListenerExecutorProperties().getProperty("maxThreads").equals("5");
+ assert gc.getAsyncListenerExecutorProperties().getProperty("threadNamePrefix").equals("AsyncListenerThread");
+
+ assert gc.getAsyncSerializationExecutorFactoryClass().equals("org.horizon.executors.DefaultExecutorFactory");
+ assert gc.getAsyncSerializationExecutorProperties().getProperty("maxThreads").equals("25");
+ assert gc.getAsyncSerializationExecutorProperties().getProperty("threadNamePrefix").equals("AsyncSerializationThread");
+
+ assert gc.getEvictionScheduledExecutorFactoryClass().equals("org.horizon.executors.DefaultScheduledExecutorFactory");
+ assert gc.getEvictionScheduledExecutorProperties().getProperty("threadNamePrefix").equals("EvictionThread");
+
+ assert gc.getReplicationQueueScheduledExecutorFactoryClass().equals("org.horizon.executors.DefaultScheduledExecutorFactory");
+ assert gc.getReplicationQueueScheduledExecutorProperties().getProperty("threadNamePrefix").equals("ReplicationQueueThread");
+
+ assert gc.getTransportClass().equals("org.horizon.remoting.transport.jgroups.JGroupsTransport");
+ assert gc.getTransportProperties().isEmpty();
+
+ assert gc.getMarshallerClass().equals("org.horizon.marshall.VersionAwareMarshaller");
+ assert gc.getMarshallVersionString().equals("1.0");
+ assert gc.getObjectOutputStreamPoolSize() == 100;
+ assert gc.getObjectInputStreamPoolSize() == 100;
+
+ Configuration defaultConfiguration = parser.parseDefaultConfiguration();
+
+ assert defaultConfiguration.getLockAcquisitionTimeout() == 1000;
+ assert defaultConfiguration.getConcurrencyLevel() == 100;
+ assert defaultConfiguration.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
+
+ Map<String, Configuration> namedCaches = parser.parseNamedConfigurations();
+
+ Configuration c = namedCaches.get("transactional");
+
+ assert c.getTransactionManagerLookupClass().equals("org.horizon.transaction.GenericTransactionManagerLookup");
+
+ c = namedCaches.get("syncRepl");
+
+ assert c.getCacheMode() == Configuration.CacheMode.REPL_SYNC;
+ assert c.isFetchInMemoryState();
+ assert c.getStateRetrievalTimeout() == 15000;
+ assert c.getSyncReplTimeout() == 15000;
+
+ c = namedCaches.get("asyncRepl");
+
+ assert c.getCacheMode() == Configuration.CacheMode.REPL_ASYNC;
+ assert !c.isUseReplQueue();
+ assert !c.isUseAsyncSerialization();
+ assert c.isFetchInMemoryState();
+ assert c.getStateRetrievalTimeout() == 15000;
+
+ c = namedCaches.get("asyncReplQueue");
+
+ assert c.getCacheMode() == Configuration.CacheMode.REPL_ASYNC;
+ assert c.isUseReplQueue();
+ assert c.isUseAsyncSerialization();
+ assert c.isFetchInMemoryState();
+ assert c.getStateRetrievalTimeout() == 15000;
+
+ c = namedCaches.get("txSyncRepl");
+
+ assert c.getTransactionManagerLookupClass().equals("org.horizon.transaction.GenericTransactionManagerLookup");
+ assert c.getCacheMode() == Configuration.CacheMode.REPL_SYNC;
+ assert c.isFetchInMemoryState();
+ assert c.getStateRetrievalTimeout() == 15000;
+ assert c.getSyncReplTimeout() == 15000;
+
+ c = namedCaches.get("overriding");
+
+ assert c.getTransactionManagerLookupClass() == null;
+ assert c.getCacheMode() == Configuration.CacheMode.LOCAL;
+ assert c.getLockAcquisitionTimeout() == 20000;
+ assert c.getConcurrencyLevel() == 1000;
+ assert c.getIsolationLevel() == IsolationLevel.REPEATABLE_READ;
+ }
+
+ public void testConfigurationMerging() throws IOException {
+ XmlConfigurationParser parser = new XmlConfigurationParserImpl("configs/named-cache-test.xml");
+ Configuration defaultCfg = parser.parseDefaultConfiguration();
+ Map<String, Configuration> namedCaches = parser.parseNamedConfigurations();
+
+ Configuration c = defaultCfg.clone();
+ c.applyOverrides(namedCaches.get("transactional"));
+
+ assert c.getCacheMode() == Configuration.CacheMode.LOCAL;
+ assert c.getTransactionManagerLookupClass().equals("org.horizon.transaction.GenericTransactionManagerLookup");
+ assert c.getLockAcquisitionTimeout() == 1000;
+ assert c.getConcurrencyLevel() == 100;
+ assert c.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
+
+ c = defaultCfg.clone();
+ c.applyOverrides(namedCaches.get("syncRepl"));
+
+ assert c.getTransactionManagerLookupClass() == null;
+ assert c.getCacheMode() == Configuration.CacheMode.REPL_SYNC;
+ assert c.isFetchInMemoryState();
+ assert c.getStateRetrievalTimeout() == 15000;
+ assert c.getSyncReplTimeout() == 15000;
+ assert c.getLockAcquisitionTimeout() == 1000;
+ assert c.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
+ assert c.getConcurrencyLevel() == 100;
+
+ c = defaultCfg.clone();
+ c.applyOverrides(namedCaches.get("asyncRepl"));
+
+ assert c.getTransactionManagerLookupClass() == null;
+ assert c.getCacheMode() == Configuration.CacheMode.REPL_ASYNC;
+ assert !c.isUseReplQueue();
+ assert !c.isUseAsyncSerialization();
+ assert c.isFetchInMemoryState();
+ assert c.getStateRetrievalTimeout() == 15000;
+ assert c.getLockAcquisitionTimeout() == 1000;
+ assert c.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
+ assert c.getConcurrencyLevel() == 100;
+
+ c = defaultCfg.clone();
+ c.applyOverrides(namedCaches.get("asyncReplQueue"));
+
+ assert c.getTransactionManagerLookupClass() == null;
+ assert c.getCacheMode() == Configuration.CacheMode.REPL_ASYNC;
+ assert c.isUseReplQueue();
+ assert c.isUseAsyncSerialization();
+ assert c.isFetchInMemoryState();
+ assert c.getStateRetrievalTimeout() == 15000;
+ assert c.getLockAcquisitionTimeout() == 1000;
+ assert c.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
+ assert c.getConcurrencyLevel() == 100;
+
+ c = defaultCfg.clone();
+ c.applyOverrides(namedCaches.get("txSyncRepl"));
+ assert c.getTransactionManagerLookupClass().equals("org.horizon.transaction.GenericTransactionManagerLookup");
+ assert c.getCacheMode() == Configuration.CacheMode.REPL_SYNC;
+ assert c.isFetchInMemoryState();
+ assert c.getStateRetrievalTimeout() == 15000;
+ assert c.getSyncReplTimeout() == 15000;
+ assert c.getLockAcquisitionTimeout() == 1000;
+ assert c.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
+ assert c.getConcurrencyLevel() == 100;
+
+ c = defaultCfg.clone();
+ c.applyOverrides(namedCaches.get("overriding"));
+
+ assert c.getTransactionManagerLookupClass() == null;
+ assert c.getCacheMode() == Configuration.CacheMode.LOCAL;
+ assert c.getLockAcquisitionTimeout() == 20000;
+ assert c.getConcurrencyLevel() == 1000;
+ assert c.getIsolationLevel() == IsolationLevel.REPEATABLE_READ;
+ }
+}
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-01-27 01:51:15 UTC (rev 7598)
+++ core/branches/flat/src/test/java/org/horizon/config/parsing/XmlFileParsingTest.java 2009-01-27 11:32:29 UTC (rev 7599)
@@ -2,6 +2,7 @@
import org.horizon.config.Configuration;
import org.horizon.config.GlobalConfiguration;
+import org.horizon.lock.IsolationLevel;
import org.testng.annotations.Test;
import java.io.IOException;
@@ -40,6 +41,7 @@
assert defaultConfiguration.getLockAcquisitionTimeout() == 1000;
assert defaultConfiguration.getConcurrencyLevel() == 100;
+ assert defaultConfiguration.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
Map<String, Configuration> namedCaches = parser.parseNamedConfigurations();
@@ -78,6 +80,85 @@
assert c.getStateRetrievalTimeout() == 15000;
assert c.getSyncReplTimeout() == 15000;
+ c = namedCaches.get("overriding");
+ assert c.getTransactionManagerLookupClass() == null;
+ assert c.getCacheMode() == Configuration.CacheMode.LOCAL;
+ assert c.getLockAcquisitionTimeout() == 20000;
+ assert c.getConcurrencyLevel() == 1000;
+ assert c.getIsolationLevel() == IsolationLevel.REPEATABLE_READ;
}
+
+ public void testConfigurationMerging() throws IOException {
+ XmlConfigurationParser parser = new XmlConfigurationParserImpl("configs/named-cache-test.xml");
+ Configuration defaultCfg = parser.parseDefaultConfiguration();
+ Map<String, Configuration> namedCaches = parser.parseNamedConfigurations();
+
+ Configuration c = defaultCfg.clone();
+ c.applyOverrides(namedCaches.get("transactional"));
+
+ assert c.getCacheMode() == Configuration.CacheMode.LOCAL;
+ assert c.getTransactionManagerLookupClass().equals("org.horizon.transaction.GenericTransactionManagerLookup");
+ assert c.getLockAcquisitionTimeout() == 1000;
+ assert c.getConcurrencyLevel() == 100;
+ assert c.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
+
+ c = defaultCfg.clone();
+ c.applyOverrides(namedCaches.get("syncRepl"));
+
+ assert c.getTransactionManagerLookupClass() == null;
+ assert c.getCacheMode() == Configuration.CacheMode.REPL_SYNC;
+ assert c.isFetchInMemoryState();
+ assert c.getStateRetrievalTimeout() == 15000;
+ assert c.getSyncReplTimeout() == 15000;
+ assert c.getLockAcquisitionTimeout() == 1000;
+ assert c.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
+ assert c.getConcurrencyLevel() == 100;
+
+ c = defaultCfg.clone();
+ c.applyOverrides(namedCaches.get("asyncRepl"));
+
+ assert c.getTransactionManagerLookupClass() == null;
+ assert c.getCacheMode() == Configuration.CacheMode.REPL_ASYNC;
+ assert !c.isUseReplQueue();
+ assert !c.isUseAsyncSerialization();
+ assert c.isFetchInMemoryState();
+ assert c.getStateRetrievalTimeout() == 15000;
+ assert c.getLockAcquisitionTimeout() == 1000;
+ assert c.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
+ assert c.getConcurrencyLevel() == 100;
+
+ c = defaultCfg.clone();
+ c.applyOverrides(namedCaches.get("asyncReplQueue"));
+
+ assert c.getTransactionManagerLookupClass() == null;
+ assert c.getCacheMode() == Configuration.CacheMode.REPL_ASYNC;
+ assert c.isUseReplQueue();
+ assert c.isUseAsyncSerialization();
+ assert c.isFetchInMemoryState();
+ assert c.getStateRetrievalTimeout() == 15000;
+ assert c.getLockAcquisitionTimeout() == 1000;
+ assert c.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
+ assert c.getConcurrencyLevel() == 100;
+
+ c = defaultCfg.clone();
+ c.applyOverrides(namedCaches.get("txSyncRepl"));
+ assert c.getTransactionManagerLookupClass().equals("org.horizon.transaction.GenericTransactionManagerLookup");
+ assert c.getCacheMode() == Configuration.CacheMode.REPL_SYNC;
+ assert c.isFetchInMemoryState();
+ assert c.getStateRetrievalTimeout() == 15000;
+ assert c.getSyncReplTimeout() == 15000;
+ assert c.getLockAcquisitionTimeout() == 1000;
+ assert c.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
+ assert c.getConcurrencyLevel() == 100;
+
+ c = defaultCfg.clone();
+ c.applyOverrides(namedCaches.get("overriding"));
+
+ assert c.getTransactionManagerLookupClass() == null;
+ assert c.getCacheMode() == Configuration.CacheMode.LOCAL;
+ assert c.getLockAcquisitionTimeout() == 20000;
+ assert c.getConcurrencyLevel() == 1000;
+ assert c.getIsolationLevel() == IsolationLevel.REPEATABLE_READ;
+ }
}
15 years, 11 months