[jbosscache-commits] JBoss Cache SVN: r7486 - in core/branches/flat/src: main/java/org/horizon and 29 other directories.
jbosscache-commits at lists.jboss.org
jbosscache-commits at lists.jboss.org
Fri Jan 16 09:44:15 EST 2009
Author: manik.surtani at jboss.com
Date: 2009-01-16 09:44:15 -0500 (Fri, 16 Jan 2009)
New Revision: 7486
Added:
core/branches/flat/src/main/java/org/horizon/CacheStatus.java
core/branches/flat/src/main/java/org/horizon/Version.java
core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoader.java
core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoaderConfig.java
core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreCacheLoader.java
core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreDefaultConfig.java
core/branches/flat/src/main/java/org/horizon/lock/IsolationLevel.java
core/branches/flat/src/main/java/org/horizon/tree/NodeNotExistsException.java
core/branches/flat/src/main/java/org/horizon/tree/NodeNotValidException.java
core/branches/flat/src/test/java/org/horizon/
core/branches/flat/src/test/java/org/horizon/BasicTest.java
core/branches/flat/src/test/java/org/horizon/UnitTestCacheFactory.java
core/branches/flat/src/test/java/org/horizon/UnitTestCacheManager.java
core/branches/flat/src/test/java/org/horizon/api/
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/batch/AbstractBatchTest.java
core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTM.java
core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTM.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/LockAssert.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/CacheAPIMVCCTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/ReadCommittedLockTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/CacheAPIMVCCTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/RepeatableReadLockTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeLockSupport.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java
core/branches/flat/src/test/java/org/horizon/api/tree/TreeStructureHashCodeTest.java
core/branches/flat/src/test/java/org/horizon/factories/
core/branches/flat/src/test/java/org/horizon/profiling/
core/branches/flat/src/test/java/org/horizon/profiling/AbstractProfileTest.java
core/branches/flat/src/test/java/org/horizon/profiling/MemConsumptionTest.java
core/branches/flat/src/test/java/org/horizon/profiling/ProfileTest.java
core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java
core/branches/flat/src/test/java/org/horizon/profiling/testinternals/Generator.java
core/branches/flat/src/test/java/org/horizon/replication/
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
core/branches/flat/src/test/java/org/horizon/tx/
core/branches/flat/src/test/java/org/horizon/tx/LocalModeTxTest.java
Removed:
core/branches/flat/src/main/java/org/horizon/eviction/FIFOPolicyTest.java
core/branches/flat/src/main/java/org/jboss/
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/batch/AbstractBatchTest.java
core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTM.java
core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTM.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/LockAssert.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/CacheAPIMVCCTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/ReadCommittedLockTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/CacheAPIMVCCTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/RepeatableReadLockTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeLockSupport.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java
core/branches/flat/src/test/java/org/horizon/api/tree/TreeStructureHashCodeTest.java
core/branches/flat/src/test/java/org/horizon/factories/scopes/
core/branches/flat/src/test/java/org/horizon/profiling/AbstractProfileTest.java
core/branches/flat/src/test/java/org/horizon/profiling/MemConsumptionTest.java
core/branches/flat/src/test/java/org/horizon/profiling/ProfileTest.java
core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java
core/branches/flat/src/test/java/org/horizon/profiling/testinternals/Generator.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
core/branches/flat/src/test/java/org/horizon/tx/LocalModeTxTest.java
core/branches/flat/src/test/java/org/jboss/starobrno/BasicTest.java
core/branches/flat/src/test/java/org/jboss/starobrno/UnitTestCacheFactory.java
core/branches/flat/src/test/java/org/jboss/starobrno/UnitTestCacheManager.java
core/branches/flat/src/test/java/org/jboss/starobrno/api/
core/branches/flat/src/test/java/org/jboss/starobrno/factories/
core/branches/flat/src/test/java/org/jboss/starobrno/profiling/
core/branches/flat/src/test/java/org/jboss/starobrno/replication/
core/branches/flat/src/test/java/org/jboss/starobrno/tx/
Modified:
core/branches/flat/src/main/java/org/horizon/cluster/ReplicationQueue.java
core/branches/flat/src/main/java/org/horizon/config/Configuration.java
core/branches/flat/src/main/java/org/horizon/config/EvictionConfig.java
core/branches/flat/src/main/java/org/horizon/config/Option.java
core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserJBC3.java
core/branches/flat/src/main/java/org/horizon/factories/InterceptorChainFactory.java
core/branches/flat/src/main/java/org/horizon/interceptors/CacheStoreInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/InvalidationInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/LockingInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/base/JmxStatsCommandInterceptor.java
core/branches/flat/src/main/java/org/horizon/jmx/PlatformMBeanServerRegistration.java
core/branches/flat/src/main/java/org/horizon/loader/CacheLoaderManager.java
core/branches/flat/src/main/java/org/horizon/marshall/CommandAwareRpcDispatcher.java
core/branches/flat/src/main/java/org/horizon/notifications/NotifierImpl.java
core/branches/flat/src/main/java/org/horizon/notifications/event/EventImpl.java
core/branches/flat/src/main/java/org/horizon/remoting/RPCManagerImpl.java
core/branches/flat/src/main/java/org/horizon/tree/Fqn.java
core/branches/flat/src/test/java/org/horizon/profiling/testinternals/TaskRunner.java
Log:
Removed deprecated methods, fixed compilation issues
Copied: core/branches/flat/src/main/java/org/horizon/CacheStatus.java (from rev 7484, core/branches/flat/src/main/java/org/jboss/cache/CacheStatus.java)
===================================================================
--- core/branches/flat/src/main/java/org/horizon/CacheStatus.java (rev 0)
+++ core/branches/flat/src/main/java/org/horizon/CacheStatus.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,211 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.horizon;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * Various states that an object that has a four stage lifecycle
+ * (i.e. <code>create()</code>, <code>start()</code>, <code>stop()</code>
+ * and <code>destroy()</code>) might be in.
+ *
+ * @author <a href="brian.stansberry at jboss.com">Brian Stansberry</a>
+ * @version $Revision$
+ */
+public enum CacheStatus
+{
+ /**
+ * Object has been instantiated, but create() has not been called.
+ */
+ INSTANTIATED,
+ /**
+ * The <code>create()</code> method has been called but not yet completed.
+ */
+ CREATING,
+ /**
+ * The <code>create()</code> method has been completed but
+ * <code>start()</code> has not been called.
+ */
+ CREATED,
+ /**
+ * The <code>start()</code> method has been called but has not yet completed.
+ */
+ STARTING,
+ /**
+ * The <code>start()</code> method has completed.
+ */
+ STARTED,
+ /**
+ * The <code>stop()</code> method has been called but has not yet completed.
+ */
+ STOPPING,
+ /**
+ * The <code>stop()</code> method has completed but <code>destroy()</code>
+ * has not yet been called. Conceptually equivalent to {@link #CREATED}.
+ */
+ STOPPED,
+ /**
+ * The <code>destroy()</code> method has been called but has not yet completed.
+ */
+ DESTROYING,
+ /**
+ * The <code>destroy()</code> method has completed.
+ * Conceptually equivalent to {@link #INSTANTIATED}.
+ */
+ DESTROYED,
+ /**
+ * A failure occurred during the execution of <code>create()</code>,
+ * <code>start()</code>, <code>stop()</code> or <code>destroy()</code>.
+ * The next logical transition is to call <code>destroy()</code>.
+ */
+ FAILED;
+
+ private static final Log log = LogFactory.getLog(CacheStatus.class);
+
+ public boolean createAllowed()
+ {
+ switch (this)
+ {
+ case CREATING:
+ case CREATED:
+ case STARTING:
+ case STARTED:
+ case STOPPED:
+ case FAILED:
+ case STOPPING:
+ case DESTROYING:
+ return false;
+ default:
+ return true;
+ }
+ }
+
+ public boolean needToDestroyFailedCache()
+ {
+ if (this == CacheStatus.FAILED)
+ {
+ log.debug("need to call destroy() since current state is " +
+ this);
+ return true;
+ }
+
+ return false;
+ }
+
+ public boolean startAllowed()
+ {
+ switch (this)
+ {
+ case INSTANTIATED:
+ case DESTROYED:
+ case STARTING:
+ case STARTED:
+ case FAILED:
+ case STOPPING:
+ case DESTROYING:
+ return false;
+ default:
+ return true;
+ }
+ }
+
+ public boolean needCreateBeforeStart()
+ {
+ switch (this)
+ {
+ case INSTANTIATED:
+ case DESTROYED:
+ log.debug("start() called while current state is " +
+ this + " -- call create() first");
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ public boolean stopAllowed()
+ {
+ switch (this)
+ {
+ case INSTANTIATED:
+ case CREATED:
+ case STOPPED:
+ case DESTROYED:
+ log.debug("Ignoring call to stop() as current state is " + this);
+ return false;
+ case CREATING:
+ case STARTING:
+ case STOPPING:
+ case DESTROYING:
+ log.warn("Ignoring call to stop() as current state is " + this);
+ return false;
+ case FAILED:
+ case STARTED:
+ default:
+ return true;
+ }
+
+ }
+
+ public boolean destroyAllowed()
+ {
+ switch (this)
+ {
+ case INSTANTIATED:
+ case DESTROYED:
+ log.debug("Ignoring call to destroy() as current state is " + this);
+ return false;
+ case CREATING:
+ case STARTING:
+ case STOPPING:
+ case DESTROYING:
+ log.warn("Ignoring call to destroy() as current state iswhile cache is " + this);
+ return false;
+ case STARTED:
+ // stop first
+ return false;
+ case CREATED:
+ case STOPPED:
+ case FAILED:
+ default:
+ return true;
+ }
+ }
+
+ public boolean needStopBeforeDestroy()
+ {
+ if (this == CacheStatus.STARTED)
+ {
+ log.warn("destroy() called while current state is " +
+ this + " -- call stop() first");
+ return true;
+ }
+
+ return false;
+ }
+
+ public boolean allowInvocations()
+ {
+ return (this == CacheStatus.STARTED);
+ }
+}
Property changes on: core/branches/flat/src/main/java/org/horizon/CacheStatus.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Copied: core/branches/flat/src/main/java/org/horizon/Version.java (from rev 7484, core/branches/flat/src/main/java/org/jboss/cache/Version.java)
===================================================================
--- core/branches/flat/src/main/java/org/horizon/Version.java (rev 0)
+++ core/branches/flat/src/main/java/org/horizon/Version.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,152 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.horizon;
+
+import net.jcip.annotations.Immutable;
+
+/**
+ * Contains version information about this release of JBoss Cache.
+ *
+ * @author Bela Ban
+ * @version $Id$
+ */
+ at Immutable
+public class Version
+{
+ public static final String version = "1.0.0.SNAPSHOT";
+ public static final String codename = "Starobrno";
+ public static final String projectName = "Horizon";
+ static final byte[] version_id = {'0', '1', '0', '0', 'S'};
+ private static final int MAJOR_SHIFT = 11;
+ private static final int MINOR_SHIFT = 6;
+ private static final int MAJOR_MASK = 0x00f800;
+ private static final int MINOR_MASK = 0x0007c0;
+ private static final int PATCH_MASK = 0x00003f;
+
+ /**
+ * Prints version information.
+ */
+ public static void main(String[] args)
+ {
+ System.out.println(projectName);
+ System.out.println();
+ System.out.println("\nVersion: \t" + version);
+ System.out.println("Codename: \t" + codename);
+ //System.out.println("CVS: \t" + cvs);
+ System.out.println("History: \t(see http://jira.jboss.com/jira/browse/JBCACHE for details)\n");
+ }
+
+ /**
+ * Returns version information as a string.
+ */
+ public static String printVersion()
+ {
+ return projectName + " '" + codename + "' " + version;
+ }
+
+ public static String printVersionId(byte[] v, int len)
+ {
+ StringBuilder sb = new StringBuilder();
+ if (v != null)
+ {
+ if (len <= 0)
+ len = v.length;
+ for (int i = 0; i < len; i++)
+ sb.append((char) v[i]);
+ }
+ return sb.toString();
+ }
+
+ public static String printVersionId(byte[] v)
+ {
+ StringBuilder sb = new StringBuilder();
+ if (v != null)
+ {
+ for (byte aV : v) sb.append((char) aV);
+ }
+ return sb.toString();
+ }
+
+
+ public static boolean compareTo(byte[] v)
+ {
+ if (v == null)
+ return false;
+ if (v.length < version_id.length)
+ return false;
+ for (int i = 0; i < version_id.length; i++)
+ {
+ if (version_id[i] != v[i])
+ return false;
+ }
+ return true;
+ }
+
+ public static int getLength()
+ {
+ return version_id.length;
+ }
+
+ public static short getVersionShort()
+ {
+ return getVersionShort(version);
+ }
+
+ public static short getVersionShort(String versionString)
+ {
+ if (versionString == null)
+ throw new IllegalArgumentException("versionString is null");
+
+ // Special cases for version prior to 1.2.4.SP2
+ if ("1.2.4".equals(versionString))
+ return 124;
+ else if ("1.2.4.SP1".equals(versionString))
+ return 1241;
+
+ String parts[] = versionString.split("[\\.\\-]");
+ int a = 0;
+ int b = 0;
+ int c = 0;
+ if (parts.length > 0)
+ a = Integer.parseInt(parts[0]);
+ if (parts.length > 1)
+ b = Integer.parseInt(parts[1]);
+ if (parts.length > 2)
+ c = Integer.parseInt(parts[2]);
+ return encodeVersion(a, b, c);
+ }
+
+ public static short encodeVersion(int major, int minor, int patch)
+ {
+ return (short) ((major << MAJOR_SHIFT)
+ + (minor << MINOR_SHIFT)
+ + patch);
+ }
+
+ public static String decodeVersion(short version)
+ {
+ int major = (version & MAJOR_MASK) >> MAJOR_SHIFT;
+ int minor = (version & MINOR_MASK) >> MINOR_SHIFT;
+ int patch = (version & PATCH_MASK);
+ return major + "." + minor + "." + patch;
+ }
+}
Property changes on: core/branches/flat/src/main/java/org/horizon/Version.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
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-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/cluster/ReplicationQueue.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -85,7 +85,7 @@
this.commandsFactory = commandsFactory;
// this is checked again in Start
- enabled = configuration.isUseReplQueue() && (configuration.getBuddyReplicationConfig() == null || !configuration.getBuddyReplicationConfig().isEnabled());
+ enabled = configuration.isUseReplQueue();
}
/**
@@ -97,7 +97,7 @@
long interval = configuration.getReplQueueInterval();
this.max_elements = configuration.getReplQueueMaxElements();
// check again
- enabled = configuration.isUseReplQueue() && (configuration.getBuddyReplicationConfig() == null || !configuration.getBuddyReplicationConfig().isEnabled());
+ enabled = configuration.isUseReplQueue();
if (enabled)
{
if (interval > 0)
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-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/config/Configuration.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -629,15 +629,6 @@
return replQueueInterval;
}
- /**
- * @deprecated use isExposeManagementStatistics()
- */
- @Deprecated
- public boolean getExposeManagementStatistics()
- {
- return exposeManagementStatistics;
- }
-
public boolean isExposeManagementStatistics()
{
return exposeManagementStatistics;
Modified: core/branches/flat/src/main/java/org/horizon/config/EvictionConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/EvictionConfig.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/config/EvictionConfig.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -50,8 +50,6 @@
@Dynamic
private List<EvictionCacheConfig> evictionCacheConfigs;
private EvictionCacheConfig defaultEvictionCacheConfig;
- @Deprecated
- private String defaultEvictionPolicyClass;
public EvictionConfig()
{
@@ -100,33 +98,6 @@
// this.defaultEvictionCacheConfig.setEventQueueSizeIfUnset(EVENT_QUEUE_SIZE_DEFAULT);
}
- /**
- * @deprecated use {@link #getDefaultEvictionRegionConfig()} instead.
- */
- @Deprecated
- public String getDefaultEvictionPolicyClass()
- {
- return defaultEvictionPolicyClass;
- }
-
- /**
- * Creates an EvictionRegionConfig for the
- * {@link #getDefaultEvictionPolicyClass()} default eviction policy class}. Throws a
- * {@link ConfigurationException} if
- * {@link #setDefaultEvictionPolicyClass(String) a default eviction policy class}
- * has not been set.
- *
- * @throws ConfigurationException if a
- * {@link #setDefaultEvictionPolicyClass(String) a default eviction policy class}
- * has not been set or there is a problem instantiating the configuration.
- * @deprecated the default region is now created when this instance is constructed. Use {@link #getDefaultEvictionRegionConfig()} instead.
- */
- @Deprecated
- public EvictionCacheConfig createDefaultEvictionRegionConfig()
- {
- return getDefaultEvictionRegionConfig();
- }
-
public List<EvictionCacheConfig> getEvictionCacheConfigs()
{
return evictionCacheConfigs;
@@ -203,24 +174,6 @@
this.wakeupInterval = timeUnit.toMillis(wakeupInterval);
}
- /**
- * @deprecated Use {@link #getWakeupIntervalSeconds()}.
- */
- @Deprecated
- public int getWakeupIntervalSeconds()
- {
- return (int) TimeUnit.MILLISECONDS.toSeconds(wakeupInterval);
- }
-
- /**
- * @deprecated Use {@link #setWakeupInterval(long)}.
- */
- @Deprecated
- public void setWakeupIntervalSeconds(int wakeupIntervalSeconds)
- {
- setWakeupInterval(wakeupIntervalSeconds, TimeUnit.SECONDS);
- }
-
public boolean equals(Object o)
{
if (this == o) return true;
@@ -281,13 +234,4 @@
// if (config == null) return; // no op
// config.setDefaults(defaultEvictionCacheConfig);
}
-
- /**
- * @deprecated set these attributes on the default eviction region config.
- */
- @Deprecated
- public void setDefaultEventQueueSize(int queueSize)
- {
- defaultEvictionCacheConfig.setEventQueueSize(queueSize);
- }
}
Modified: core/branches/flat/src/main/java/org/horizon/config/Option.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/Option.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/config/Option.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -28,7 +28,7 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
* @since 1.3.0
*/
-public class Option implements Cloneable
+public class Option
{
private boolean failSilently;
private boolean cacheModeLocal;
@@ -199,17 +199,6 @@
}
/**
- * @see #copy()
- * @deprecated this method may disappear in future, please use copy() instead.
- */
- @Override
- @Deprecated
- public Option clone() throws CloneNotSupportedException
- {
- return (Option) super.clone();
- }
-
- /**
* @return a new Option instance with all fields shallow-copied.
*/
public Option copy()
Modified: core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserJBC3.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserJBC3.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserJBC3.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -24,7 +24,6 @@
import org.horizon.lock.IsolationLevel;
import org.horizon.config.*;
import org.horizon.config.Configuration.CacheMode;
-import org.horizon.config.parsing.element.BuddyElementParser;
import org.horizon.config.parsing.element.CustomInterceptorsElementParser;
import org.horizon.config.parsing.element.EvictionElementParser;
import org.horizon.config.parsing.element.LoadersElementParser;
@@ -195,7 +194,6 @@
}
String cn = getAttributeValue(e, "clusterName");
if (existsAttribute(cn)) config.setClusterName(cn);
- configureBuddyReplication(getSingleElementInCoreNS("buddy", e));
configureStateRetrieval(getSingleElementInCoreNS("stateRetrieval", e));
configureTransport(getSingleElementInCoreNS("jgroupsConfig", e));
}
@@ -267,14 +265,6 @@
config.setInvocationBatchingEnabled(enabled);
}
- private void configureBuddyReplication(Element element)
- {
- if (element == null) return;//buddy config might not exist, expect that
- BuddyElementParser buddyElementParser = new BuddyElementParser();
- BuddyReplicationConfig brConfig = buddyElementParser.parseBuddyElement(element);
- config.setBuddyReplicationConfig(brConfig);
- }
-
private void configureCacheLoaders(Element element)
{
if (element == null) return; //null cache loaders are allowed
Deleted: core/branches/flat/src/main/java/org/horizon/eviction/FIFOPolicyTest.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/FIFOPolicyTest.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/eviction/FIFOPolicyTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,147 +0,0 @@
-package org.horizon.eviction;
-
-import org.horizon.lock.IsolationLevel;
-import org.horizon.CacheSPI;
-import org.jboss.starobrno.UnitTestCacheFactory;
-import org.horizon.config.Configuration;
-import org.horizon.config.EvictionCacheConfig;
-import org.horizon.config.EvictionConfig;
-import org.horizon.eviction.algorithms.fifo.FIFOAlgorithmConfig;
-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 java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author Mircea.Markus at jboss.com
- */
- at Test(groups = "functional")
-public class FIFOPolicyTest
-{
- CacheSPI<Object, Object> cache;
- final String CACHE_NAME = "test";
- Throwable t1_ex, t2_ex;
- volatile boolean isTrue;
- int maxNodes = 5;
-
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
- initCaches();
- t1_ex = t2_ex = null;
- isTrue = true;
- }
-
- private void log(String s)
- {
- System.out.println("---log :" + s);
- }
-
- void initCaches() throws Exception
- {
-
- Configuration config = new Configuration();
- EvictionConfig evConfig = new EvictionConfig();
- evConfig.setWakeupInterval(-1);//external thread
- config.setEvictionConfig(evConfig);
- config.setCacheMode(Configuration.CacheMode.LOCAL);
- FIFOAlgorithmConfig algorithmConfig = new FIFOAlgorithmConfig(maxNodes);
- EvictionCacheConfig ecc = new EvictionCacheConfig(2000000, algorithmConfig, EvictionConfig.EVICTION_ACTION_CLASS_DEFAULT);
- config.addEvictionCacheConfig(this.CACHE_NAME, ecc);
- config.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- config.setIsolationLevel(IsolationLevel.REPEATABLE_READ);
- cache = (CacheSPI<Object, Object>) new UnitTestCacheFactory<Object, Object>().createCache(config, true);
- }
-
- @AfterMethod(alwaysRun = true)
- public void tearDown() throws Exception
- {
- TestingUtil.killCaches(cache);
- cache = null;
- }
-
- public void testEviction()
- {
- String rootStr = "root";
- for (int i = 0; i < 10; i++)
- {
- String str = rootStr + i;
- try
- {
- cache.put(str, str);
- }
- catch (Exception e)
- {
- fail("Failed to insert data" + e);
- e.printStackTrace();
- }
- }
- cache.getEvictionManager().runEviction();
-
- try
- {
- String val = (String) cache.get(rootStr + "3");
- assertNull("DataNode should be empty ", val);
- assertNull(cache.get(rootStr + "1"));
- assertNull(cache.get(rootStr + "2"));
- assertNull(cache.get(rootStr + "0"));
- assertNull(cache.get(rootStr + "4"));
-
- assertNotNull(cache.get(rootStr + "5"));
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Failed to get" + e);
- }
- }
-
- public void testNodeVisited() throws InterruptedException
- {
- String rootStr = "root";
- List<Object> keysToBeEvicted = new ArrayList<Object>();
- for (int i = 0; i < 5; i++) keysToBeEvicted.add(rootStr + i);
- EvictionWatcher watcher = new EvictionWatcher(cache, keysToBeEvicted);
-
- for (int i = 0; i < 10; i++)
- {
- String str = rootStr + i;
- try
- {
- cache.put(str, str);
- }
- catch (Exception e)
- {
- fail("Failed to insert data" + e);
- e.printStackTrace();
- }
- }
-
- cache.getEvictionManager().runEviction();
-
- assert watcher.allNodesEvicted();
-
- try
- {
- for (int i = 0; i < 5; i++)
- {
- assertNull(cache.get(rootStr + i));
- }
- for (int i = 5; i < 10; i++)
- {
- assertNotNull(cache.get(rootStr + i));
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- fail("Failed to evict" + e);
- }
- }
-
-}
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-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/factories/InterceptorChainFactory.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -44,18 +44,6 @@
@DefaultFactoryFor(classes = InterceptorChain.class)
public class InterceptorChainFactory extends ComponentFactory
{
- /**
- * Note - this method used to return a singleton instance, and since 2.1.0 returns a new instance. The method is
- * deprecated and you should use the no-arg constructor to create a new instance of this factory.
- *
- * @return a NEW instance of this class.
- */
- @Deprecated
- public static InterceptorChainFactory getInstance()
- {
- return new InterceptorChainFactory();
- }
-
private CommandInterceptor createInterceptor(Class<? extends CommandInterceptor> clazz) throws IllegalAccessException, InstantiationException
{
CommandInterceptor chainedInterceptor = componentRegistry.getComponent(clazz);
@@ -97,7 +85,7 @@
interceptorChain.appendIntereceptor(createInterceptor(InvocationContextInterceptor.class));
// load the cache management interceptor next
- if (configuration.getExposeManagementStatistics())
+ if (configuration.isExposeManagementStatistics())
interceptorChain.appendIntereceptor(createInterceptor(CacheMgmtInterceptor.class));
// load the tx interceptor
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/CacheStoreInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/CacheStoreInterceptor.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/CacheStoreInterceptor.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -21,20 +21,7 @@
*/
package org.horizon.interceptors;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-
-import javax.transaction.SystemException;
-import javax.transaction.TransactionManager;
-
import org.apache.commons.logging.LogFactory;
-import org.horizon.jmx.annotations.ManagedAttribute;
-import org.horizon.jmx.annotations.ManagedOperation;
import org.horizon.commands.AbstractVisitor;
import org.horizon.commands.VisitableCommand;
import org.horizon.commands.tx.CommitCommand;
@@ -50,12 +37,24 @@
import org.horizon.factories.annotations.Inject;
import org.horizon.factories.annotations.Start;
import org.horizon.interceptors.base.JmxStatsCommandInterceptor;
+import org.horizon.jmx.annotations.ManagedAttribute;
+import org.horizon.jmx.annotations.ManagedOperation;
import org.horizon.loader.CacheLoader;
import org.horizon.loader.CacheLoaderManager;
import org.horizon.loader.Modification;
import org.horizon.loader.Modification.ModificationType;
import org.horizon.transaction.GlobalTransaction;
+import javax.transaction.SystemException;
+import javax.transaction.TransactionManager;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
/**
* Writes modifications back to the store on the way out: stores modifications back
* through the CacheLoader, either after each method call (no TXs), or at TX commit.
@@ -94,7 +93,7 @@
{
// this should only happen after the CacheLoaderManager has started, since the CacheLoaderManager only creates the CacheLoader instance in its @Start method.
loader = loaderManager.getCacheLoader();
- this.setStatisticsEnabled(configuration.getExposeManagementStatistics());
+ this.setStatisticsEnabled(configuration.isExposeManagementStatistics());
}
/**
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-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/InvalidationInterceptor.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -74,7 +74,7 @@
@Start
private void initTxMap()
{
- this.setStatisticsEnabled(configuration.getExposeManagementStatistics());
+ this.setStatisticsEnabled(configuration.isExposeManagementStatistics());
}
@Override
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/LockingInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/LockingInterceptor.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/LockingInterceptor.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -23,7 +23,6 @@
import org.horizon.lock.IsolationLevel;
import org.horizon.commands.read.GetKeyValueCommand;
-import org.horizon.commands.read.GravitateDataCommand;
import org.horizon.commands.read.SizeCommand;
import org.horizon.commands.tx.CommitCommand;
import org.horizon.commands.tx.PrepareCommand;
@@ -237,21 +236,6 @@
}
}
- @Override
- public Object visitGravitateDataCommand(InvocationContext ctx, GravitateDataCommand command) throws Throwable
- {
- try
- {
- entryFactory.wrapEntryForReading(ctx, command.getKey(), true);
- return invokeNextInterceptor(ctx, command);
- }
- finally
- {
- doAfterCall(ctx);
- }
- }
-
-
@SuppressWarnings("unchecked")
private void doAfterCall(InvocationContext ctx)
{
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/base/JmxStatsCommandInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/base/JmxStatsCommandInterceptor.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/base/JmxStatsCommandInterceptor.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -41,7 +41,7 @@
@Start
public void checkStatisticsUsed()
{
- setStatisticsEnabled(configuration.getExposeManagementStatistics());
+ setStatisticsEnabled(configuration.isExposeManagementStatistics());
}
/**
Modified: core/branches/flat/src/main/java/org/horizon/jmx/PlatformMBeanServerRegistration.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/jmx/PlatformMBeanServerRegistration.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/jmx/PlatformMBeanServerRegistration.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -63,7 +63,7 @@
if (cache == null)
throw new IllegalStateException("The cache should had been injected before a call to this method");
Configuration config = cache.getConfiguration();
- if (config.getExposeManagementStatistics())
+ if (config.isExposeManagementStatistics())
{
JmxRegistrationManager jmxRegistrationManager = new JmxRegistrationManager(cache);
jmxRegistrationManager.registerAllMBeans();
@@ -81,7 +81,7 @@
// After the first call the cache will become null, so we guard this
if (cache == null) return;
Configuration config = cache.getConfiguration();
- if (config.getExposeManagementStatistics())
+ if (config.isExposeManagementStatistics())
{
JmxRegistrationManager jmxRegistrationManager = new JmxRegistrationManager(cache);
jmxRegistrationManager.unregisterAllMBeans();
Modified: core/branches/flat/src/main/java/org/horizon/loader/CacheLoaderManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/CacheLoaderManager.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/loader/CacheLoaderManager.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -317,7 +317,6 @@
public void preload(String key) throws CacheException
{
- cache.getInvocationContext().getOptionOverrides().setSkipDataGravitation(true);
cache.getInvocationContext().getOptionOverrides().setSkipCacheStatusCheck(true);
// 1. Load the attributes first
// but this will go down the entire damn chain!! :S
Copied: core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoader.java (from rev 7484, core/branches/flat/src/main/java/org/jboss/cache/loader/ClusteredCacheLoader.java)
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoader.java (rev 0)
+++ core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoader.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,411 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.horizon.loader;
+
+import net.jcip.annotations.ThreadSafe;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.horizon.CacheStatus;
+import org.horizon.commands.CommandsFactory;
+import org.horizon.commands.DataCommand;
+import org.horizon.config.CacheLoaderConfig.IndividualCacheLoaderConfig;
+import org.horizon.factories.annotations.Inject;
+import org.horizon.lock.StripedLock;
+import org.horizon.tree.Fqn;
+import org.jgroups.Address;
+import org.jgroups.blocks.RspFilter;
+
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A cache loader that consults other members in the cluster for values. Does
+ * not propagate update methods since replication should take care of this. A
+ * <code>timeout</code> property is required, a <code>long</code> that
+ * specifies in milliseconds how long to wait for results before returning a
+ * null.
+ *
+ * @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
+ * // TODO implement me!!
+ */
+ at ThreadSafe
+public class ClusteredCacheLoader extends AbstractCacheLoader
+{
+ private static final Log log = LogFactory.getLog(ClusteredCacheLoader.class);
+ private static final boolean trace = log.isTraceEnabled();
+ private StripedLock lock = new StripedLock();
+ private ClusteredCacheLoaderConfig config;
+ private CommandsFactory commandsFactory;
+
+ /**
+ * A test to check whether the cache is in its started state. If not, calls should not be made as the channel may
+ * not have properly started, blocks due to state transfers may be in progress, etc.
+ *
+ * @return true if the cache is in its STARTED state.
+ */
+ protected boolean isCacheReady()
+ {
+ return cache.getCacheStatus() == CacheStatus.STARTED;
+ }
+
+ @Inject
+ public void setCommandsFactory(CommandsFactory commandsFactory)
+ {
+ this.commandsFactory = commandsFactory;
+ }
+
+ /**
+ * Sets the configuration.
+ * A property <code>timeout</code> is used as the timeout value.
+ */
+ public void setConfig(IndividualCacheLoaderConfig base)
+ {
+// if (base instanceof ClusteredCacheLoaderConfig)
+// {
+// this.config = (ClusteredCacheLoaderConfig) base;
+// }
+// else
+// {
+// config = new ClusteredCacheLoaderConfig(base);
+// }
+ }
+
+ public IndividualCacheLoaderConfig getConfig()
+ {
+ return config;
+ }
+
+ public Object get(Object key)
+ {
+ return null; // TODO: Manik: Customise this generated block
+ }
+
+ public boolean exists(Object key)
+ {
+ return false; // TODO: Manik: Customise this generated block
+ }
+
+ public Object put(Object key, Object value)
+ {
+ return null; // TODO: Manik: Customise this generated block
+ }
+
+ public void clear()
+ {
+ // TODO: Manik: Customise this generated block
+ }
+
+ public Object remove(Object key)
+ {
+ return null; // TODO: Manik: Customise this generated block
+ }
+
+ public List getAllEntries()
+ {
+ return null; // TODO: Manik: Customise this generated block
+ }
+
+ public Set getChildrenNames(Fqn fqn) throws Exception
+ {
+ if (!isCacheReady() || !cache.getInvocationContext().isOriginLocal()) return Collections.emptySet();
+ lock.acquireLock(fqn, true);
+// try
+// {
+// GetChildrenNamesCommand command = commandsFactory.buildGetChildrenNamesCommand(fqn);
+// Object resp = callRemote(command);
+// return (Set) resp;
+// }
+// finally
+// {
+// lock.releaseLock(fqn);
+// }
+ throw new RuntimeException("Implement me");
+ }
+
+ @SuppressWarnings("deprecation")
+ private Object callRemote(DataCommand dataCommand) throws Exception
+ {
+ if (trace) log.trace("cache=" + cache.getLocalAddress() + "; calling with " + dataCommand);
+// ClusteredGetCommand clusteredGet = commandsFactory.buildClusteredGetCommand(false, dataCommand);
+ List resps;
+ // JBCACHE-1186
+// resps = cache.getRPCManager().callRemoteMethods(null, clusteredGet, GroupRequest.GET_ALL, config.getTimeout(), new ResponseValidityFilter(cache.getMembers(), cache.getLocalAddress()), false);
+
+// if (resps == null)
+// {
+// if (log.isInfoEnabled())
+// log.info("No replies to call " + dataCommand + ". Perhaps we're alone in the cluster?");
+// throw new ReplicationException("No replies to call " + dataCommand + ". Perhaps we're alone in the cluster?");
+// }
+// else
+// {
+// // test for and remove exceptions
+// Iterator i = resps.iterator();
+// Object result = null;
+// while (i.hasNext())
+// {
+// Object o = i.next();
+// if (o instanceof Exception)
+// {
+// if (log.isDebugEnabled())
+// log.debug("Found remote exception among responses - removing from responses list", (Exception) o);
+// }
+// else if (o != null)
+// {
+// // keep looping till we find a FOUND answer.
+// List<Boolean> clusteredGetResp = (List<Boolean>) o;
+// // found?
+// if (clusteredGetResp.get(0))
+// {
+// result = clusteredGetResp.get(1);
+// break;
+// }
+// }
+// else if (!cache.getConfiguration().isUseRegionBasedMarshalling())
+// {
+// throw new IllegalStateException("Received unexpected null response to " + clusteredGet);
+// }
+// // else region was inactive on peer;
+// // keep looping to see if anyone else responded
+// }
+//
+// if (trace) log.trace("got responses " + resps);
+// return result;
+// }
+ throw new RuntimeException("Implement me");
+ }
+
+ public Map get(Fqn name) throws Exception
+ {
+ return get0(name);
+ }
+
+ protected Map get0(Fqn name) throws Exception
+ {
+ // DON'T make a remote call if this is a remote call in the first place - leads to deadlocks - JBCACHE-1103
+ if (!isCacheReady() || !cache.getInvocationContext().isOriginLocal()) return Collections.emptyMap();
+ lock.acquireLock(name, true);
+// try
+// {
+// GetDataMapCommand command = commandsFactory.buildGetDataMapCommand(name);
+// Object resp = callRemote(command);
+// return (Map) resp;
+// }
+// finally
+// {
+// lock.releaseLock(name);
+// }
+ throw new RuntimeException("Implement me");
+ }
+
+ public boolean exists(Fqn name) throws Exception
+ {
+ // DON'T make a remote call if this is a remote call in the first place - leads to deadlocks - JBCACHE-1103
+ if (!isCacheReady() || !cache.getInvocationContext().isOriginLocal()) return false;
+
+ lock.acquireLock(name, false);
+// try
+// {
+// ExistsCommand command = commandsFactory.buildExistsNodeCommand(name);
+// Object resp = callRemote(command);
+// return resp != null && (Boolean) resp;
+// }
+// finally
+// {
+// lock.releaseLock(name);
+// }
+ throw new RuntimeException("Implement me");
+ }
+
+ public Object put(Fqn name, Object key, Object value) throws Exception
+ {
+ // DON'T make a remote call if this is a remote call in the first place - leads to deadlocks - JBCACHE-1103
+ if (!isCacheReady() || !cache.getInvocationContext().isOriginLocal()) return null;
+ lock.acquireLock(name, true);
+ try
+ {
+// NodeSPI n = cache.peek(name, false);
+// if (n == null)
+// {
+// GetKeyValueCommand command = commandsFactory.buildGetKeyValueCommand(name, key, true);
+// return callRemote(command);
+// }
+// else
+// {
+// // dont bother with a remote call
+// return n.getDirect(key);
+// }
+ }
+ finally
+ {
+ lock.releaseLock(name);
+ }
+ throw new RuntimeException("Implement me");
+ }
+
+ /**
+ * Does nothing; replication handles put.
+ */
+ public void put(Fqn name, Map attributes) throws Exception
+ {
+ }
+
+ /**
+ * Does nothing; replication handles put.
+ */
+// @Override
+// public void put(List<Modification> modifications) throws Exception
+// {
+// }
+
+ /**
+ * Fetches the remove value, does not remove. Replication handles
+ * removal.
+ */
+ public Object remove(Fqn name, Object key) throws Exception
+ {
+ // DON'T make a remote call if this is a remote call in the first place - leads to deadlocks - JBCACHE-1103
+ if (!isCacheReady() || !cache.getInvocationContext().isOriginLocal()) return false;
+ lock.acquireLock(name, true);
+ try
+ {
+// NodeSPI n = cache.peek(name, true);
+// if (n == null)
+// {
+// GetKeyValueCommand command = commandsFactory.buildGetKeyValueCommand(name, key, true);
+// return callRemote(command);
+// }
+// else
+// {
+// // dont bother with a remote call
+// return n.getDirect(key);
+// }
+ }
+ finally
+ {
+ lock.releaseLock(name);
+ }
+ throw new RuntimeException("Implement me");
+ }
+
+ /**
+ * Does nothing; replication handles removal.
+ */
+ public void remove(Fqn name) throws Exception
+ {
+ // do nothing
+ }
+
+ /**
+ * Does nothing; replication handles removal.
+ */
+ public void removeData(Fqn name) throws Exception
+ {
+ }
+
+ /**
+ * Does nothing.
+ */
+// @Override
+// public void prepare(Object tx, List modifications, boolean one_phase) throws Exception
+// {
+// }
+
+ /**
+ * Does nothing.
+ */
+// @Override
+// public void commit(Object tx) throws Exception
+// {
+// }
+
+ /**
+ * Does nothing.
+ */
+ @Override
+ public void rollback(Object tx)
+ {
+ }
+
+// @Override
+// public void loadEntireState(ObjectOutputStream os) throws Exception
+// {
+// //intentional no-op
+// }
+
+// @Override
+ public void loadState(Fqn subtree, ObjectOutputStream os) throws Exception
+ {
+ // intentional no-op
+ }
+
+// @Override
+// public void storeEntireState(ObjectInputStream is) throws Exception
+// {
+// // intentional no-op
+// }
+
+// @Override
+ public void storeState(Fqn subtree, ObjectInputStream is) throws Exception
+ {
+ // intentional no-op
+ }
+
+ public static class ResponseValidityFilter implements RspFilter
+ {
+ private int numValidResponses = 0;
+ private List<Address> pendingResponders;
+
+ public ResponseValidityFilter(List<Address> expected, Address localAddress)
+ {
+ this.pendingResponders = new ArrayList<Address>(expected);
+ // We'll never get a response from ourself
+ this.pendingResponders.remove(localAddress);
+ }
+
+ public boolean isAcceptable(Object object, Address address)
+ {
+ pendingResponders.remove(address);
+
+ if (object instanceof List)
+ {
+ List response = (List) object;
+ Boolean foundResult = (Boolean) response.get(0);
+ if (foundResult) numValidResponses++;
+ }
+ // always return true to make sure a response is logged by the JGroups RpcDispatcher.
+ return true;
+ }
+
+ public boolean needMoreResponses()
+ {
+ return numValidResponses < 1 && pendingResponders.size() > 0;
+ }
+
+ }
+
+}
Property changes on: core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoader.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Copied: core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoaderConfig.java (from rev 7484, core/branches/flat/src/main/java/org/jboss/cache/loader/ClusteredCacheLoaderConfig.java)
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoaderConfig.java (rev 0)
+++ core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoaderConfig.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,104 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.horizon.loader;
+
+
+import org.horizon.config.CacheLoaderConfig.IndividualCacheLoaderConfig;
+import org.horizon.config.Dynamic;
+
+import java.util.Properties;
+
+public class ClusteredCacheLoaderConfig extends IndividualCacheLoaderConfig
+{
+ /**
+ * The serialVersionUID
+ */
+ private static final long serialVersionUID = -3425487656984237468L;
+
+ @Dynamic
+ private long timeout = 10000;
+
+ public ClusteredCacheLoaderConfig()
+ {
+ setClassName(ClusteredCacheLoader.class.getName());
+ }
+
+ /**
+ * For use by {@link org.horizon.loader.ClusteredCacheLoader}.
+ *
+ * @param base generic config object created by XML parsing.
+ */
+ ClusteredCacheLoaderConfig(IndividualCacheLoaderConfig base)
+ {
+ setClassName(ClusteredCacheLoader.class.getName());
+ populateFromBaseConfig(base);
+ }
+
+ public long getTimeout()
+ {
+ return timeout;
+ }
+
+ public void setTimeout(long timeout)
+ {
+ testImmutability("timeout");
+ this.timeout = timeout;
+ }
+
+ @Override
+ public void setProperties(Properties props)
+ {
+ super.setProperties(props);
+ try
+ {
+ timeout = Long.valueOf(props.getProperty("timeout"));
+ }
+ catch (Exception e)
+ {
+ log.info("Using default value for config property 'timeout' - " + timeout);
+ }
+ }
+
+ @Override
+ public boolean equals(Object obj)
+ {
+ if (obj instanceof ClusteredCacheLoaderConfig && equalsExcludingProperties(obj))
+ {
+ ClusteredCacheLoaderConfig other = (ClusteredCacheLoaderConfig) obj;
+ return (this.timeout == other.timeout);
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return 31 * hashCodeExcludingProperties() + (int) timeout;
+ }
+
+ @Override
+ public ClusteredCacheLoaderConfig clone() throws CloneNotSupportedException
+ {
+ return (ClusteredCacheLoaderConfig) super.clone();
+ }
+
+}
\ No newline at end of file
Property changes on: core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoaderConfig.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Copied: core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreCacheLoader.java (from rev 7484, core/branches/flat/src/main/java/org/jboss/cache/loader/SingletonStoreCacheLoader.java)
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreCacheLoader.java (rev 0)
+++ core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreCacheLoader.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,595 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.horizon.loader;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.horizon.config.CacheLoaderConfig;
+import org.horizon.config.CacheLoaderConfig.IndividualCacheLoaderConfig.SingletonStoreConfig;
+import org.horizon.notifications.annotation.CacheListener;
+import org.horizon.notifications.annotation.CacheStarted;
+import org.horizon.notifications.annotation.CacheStopped;
+import org.horizon.notifications.annotation.ViewChanged;
+import org.horizon.notifications.event.Event;
+import org.horizon.notifications.event.ViewChangedEvent;
+import org.horizon.tree.Fqn;
+import org.jgroups.Address;
+import org.jgroups.View;
+
+import java.io.ObjectInputStream;
+import java.util.Map;
+import java.util.Vector;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+/**
+ * SingletonStoreCacheLoader is a delegating cache loader used for situations when only one node should interact with
+ * the underlying store. The coordinator of the cluster will be responsible for the underlying CacheLoader.
+ * SingletonStoreCacheLoader is a simply facade to a real CacheLoader implementation. It always delegates reads to the
+ * real CacheLoader.
+ * <p/>
+ * Writes are forwarded only if this SingletonStoreCacheLoader is currently the cordinator. This avoid having all
+ * CacheLoaders in a cluster writing the same data to the same underlying store. Although not incorrect (e.g. a DB
+ * will just discard additional INSERTs for the same key, and throw an exception), this will avoid a lot of
+ * redundant work.<br/>
+ * <p/>
+ * Whenever the current coordinator dies (or leaves), the second in line will take over. That SingletonStoreCacheLoader
+ * will then pass writes through to its underlying CacheLoader. Optionally, when a new coordinator takes over the
+ * Singleton, it can push the in-memory state to the cache cacheLoader, within a time constraint.
+ *
+ * @author Bela Ban
+ * @author <a href="mailto:galder.zamarreno at jboss.com">Galder Zamarreno</a>
+ */
+public class SingletonStoreCacheLoader extends AbstractDelegatingCacheLoader
+{
+ /**
+ * Log instance.
+ */
+ private static final Log log = LogFactory.getLog(SingletonStoreCacheLoader.class);
+ private static final boolean trace = log.isTraceEnabled();
+
+ /**
+ * Name of thread that should pushing in-memory state to cache loader.
+ */
+ private static final String THREAD_NAME = "InMemoryToCacheLoaderPusher";
+
+ /**
+ * Configuration for the SingletonStoreCacheLoader.
+ */
+ private SingletonStoreDefaultConfig config;
+
+ /**
+ * Executor service used to submit tasks to push in-memory state.
+ */
+ private final ExecutorService executor;
+
+ /**
+ * Future result of the in-memory push state task. This allows SingletonStoreCacheLoader to check whether there's any
+ * push taks on going.
+ */
+ private Future<?> pushStateFuture; /* FutureTask guarantess a safe publication of the result */
+
+ /**
+ * Address instance that allows SingletonStoreCacheLoader to find out whether it became the coordinator of the
+ * cluster, or whether it stopped being it. This dictates whether the SingletonStoreCacheLoader is active or not.
+ */
+ private Address localAddress;
+
+ /**
+ * Whether the the current node is the coordinator and therefore SingletonStoreCacheLoader is active. Being active
+ * means delegating calls to the underlying cache loader.
+ */
+ private boolean active;
+
+ /**
+ * Empty constructor so that it can instantiated using reflection.
+ */
+ public SingletonStoreCacheLoader()
+ {
+ super(null);
+
+ executor = Executors.newSingleThreadExecutor(new ThreadFactory()
+ {
+ public Thread newThread(Runnable r)
+ {
+ return new Thread(r, THREAD_NAME);
+ }
+ });
+ }
+
+ /**
+ * Sets the config for SingletonStoreCacheLoader and for the delegating cache loader.
+ */
+ @Override
+ public void setConfig(CacheLoaderConfig.IndividualCacheLoaderConfig config)
+ {
+ super.setConfig(config);
+
+ SingletonStoreConfig ssc = config.getSingletonStoreConfig();
+ if (ssc instanceof SingletonStoreDefaultConfig)
+ {
+ this.config = (SingletonStoreDefaultConfig) ssc;
+ }
+ else if (ssc != null)
+ {
+ this.config = new SingletonStoreDefaultConfig(ssc);
+ }
+ else
+ {
+ this.config = new SingletonStoreDefaultConfig();
+ }
+ }
+
+ @Override
+ public void create()// throws Exception
+ {
+ super.create();
+
+ cache.addCacheListener(new SingletonStoreListener());
+ }
+
+ /**
+ * Protected constructor which should only be used from unit tests. Production code should set
+ * pushStateWhenCoordinator using setConfig() method instead.
+ *
+ * @param config configuration instance for SingletonStoreCacheLoader
+ */
+ protected SingletonStoreCacheLoader(SingletonStoreDefaultConfig config)
+ {
+ this();
+
+ this.config = config;
+ }
+
+ /**
+ * Returns SingletonStoreCacheLoader's configuration instance. This method has been defined for convenience reasons
+ * when unit testing SingletonStoreCacheLoader's configuration.
+ *
+ * @return instance of SingletonStoreDefaultConfig
+ */
+ protected SingletonStoreDefaultConfig getSingletonStoreDefaultConfig()
+ {
+ return config;
+ }
+
+ /**
+ * Returns the Future instance of a running in-memory to cache loader push task. This method has been defined for
+ * convenience reasons when unit testing.
+ *
+ * @return an instance of Future
+ */
+ protected Future<?> getPushStateFuture()
+ {
+ return pushStateFuture;
+ }
+
+ /**
+ * Method called when the node either becomes the coordinator or stops being the coordinator. If it becomes the
+ * coordinator, it can optionally start the in-memory state transfer to the underlying cache store.
+ *
+ * @param newActiveState true if the node just became the coordinator, false if the nodes stopped being the coordinator.
+ */
+ protected void activeStatusChanged(boolean newActiveState) throws PushStateException
+ {
+ active = newActiveState;
+ log.debug("changed mode: " + this);
+ if (active && config.isPushStateWhenCoordinator())
+ {
+ doPushState();
+ }
+ }
+
+ /**
+ * Factory method for the creation of a Callable task in charge of pushing in-memory state to cache loader.
+ *
+ * @return new instance of Callable<?> whose call() method either throws an exception or returns null if the task
+ * was successfull.
+ */
+ protected Callable<?> createPushStateTask()
+ {
+ return new Callable()
+ {
+ public Object call() throws Exception
+ {
+ final boolean debugEnabled = log.isDebugEnabled();
+
+ if (debugEnabled) log.debug("start pushing in-memory state to cache cacheLoader");
+// pushState(cache.getRoot());
+ if (debugEnabled) log.debug("in-memory state passed to cache cacheLoader successfully");
+
+ return null;
+ }
+ };
+ }
+
+ /**
+ * Pushes the state of a specific node by reading the node's data from the cache and putting in the cache store
+ * via the cache loader. This method is call recursively so that it iterates through the whole cache.
+ *
+ * @param node instance of NodeSPI to push to the cache loader
+ * @throws Exception if there's any issues reading the data from the cache or pushing the node's data to the cache
+ * loader.
+ */
+ // TODO implement me
+// protected void pushState(NodeSPI node) throws Exception
+// {
+// /* Put the node's data first */
+// Set keys = node.getKeysDirect();
+// Fqn fqn = node.getFqn();
+//
+// for (Object aKey : keys)
+// {
+// Object value = cache.get(fqn, aKey);
+// put(fqn, aKey, value);
+// }
+//
+// /* Navigates to the children */
+// Collection<NodeSPI> children = node.getChildrenDirect();
+// for (NodeSPI aChildren : children)
+// {
+// //Map.Entry entry = (Map.Entry) aChildren;
+// pushState(aChildren);
+// }
+// }
+
+ /**
+ * Method that waits for the in-memory to cache loader state to finish. This method's called in case a push state
+ * is already in progress and we need to wait for it to finish.
+ *
+ * @param future instance of Future representing the on going push task
+ * @param timeout time to wait for the push task to finish
+ * @param unit instance of TimeUnit representing the unit of timeout
+ */
+ protected void awaitForPushToFinish(Future future, int timeout, TimeUnit unit)
+ {
+ final boolean debugEnabled = log.isDebugEnabled();
+ try
+ {
+ if (debugEnabled) log.debug("wait for state push to cache loader to finish");
+ future.get(timeout, unit);
+ }
+ catch (TimeoutException e)
+ {
+ if (debugEnabled) log.debug("timed out waiting for state push to cache loader to finish");
+ }
+ catch (ExecutionException e)
+ {
+ if (debugEnabled) log.debug("exception reported waiting for state push to cache loader to finish");
+ }
+ catch (InterruptedException ie)
+ {
+ /* Re-assert the thread's interrupted status */
+ Thread.currentThread().interrupt();
+ if (trace) log.trace("wait for state push to cache loader to finish was interrupted");
+ }
+ }
+
+ /**
+ * Called when the SingletonStoreCacheLoader discovers that the node has become the coordinator and push in memory
+ * state has been enabled. It might not actually push the state if there's an ongoing push task running, in which
+ * case will wait for the push task to finish.
+ *
+ * @throws PushStateException when the push state task reports an issue.
+ */
+ private void doPushState() throws PushStateException
+ {
+ if (pushStateFuture == null || pushStateFuture.isDone())
+ {
+ Callable<?> task = createPushStateTask();
+ pushStateFuture = executor.submit(task);
+ try
+ {
+ waitForTaskToFinish(pushStateFuture, config.getPushStateWhenCoordinatorTimeout(), TimeUnit.MILLISECONDS);
+ }
+ catch (Exception e)
+ {
+ throw new PushStateException("unable to complete in memory state push to cache loader", e);
+ }
+ }
+ else
+ {
+ /* at the most, we wait for push state timeout value. if it push task finishes earlier, this call
+ * will stop when the push task finishes, otherwise a timeout exception will be reported */
+ awaitForPushToFinish(pushStateFuture, config.getPushStateWhenCoordinatorTimeout(), TimeUnit.MILLISECONDS);
+ }
+ }
+
+ /**
+ * Waits, within a time constraint, for a task to finish.
+ *
+ * @param future represents the task waiting to finish.
+ * @param timeout maximum time to wait for the time to finish.
+ * @param unit instance of TimeUnit representing the unit of timeout
+ * @throws Exception if any issues are reported while waiting for the task to finish
+ */
+ private void waitForTaskToFinish(Future future, int timeout, TimeUnit unit) throws Exception
+ {
+ try
+ {
+ future.get(timeout, unit);
+ }
+ catch (TimeoutException e)
+ {
+ throw new Exception("task timed out", e);
+ }
+ catch (InterruptedException e)
+ {
+ /* Re-assert the thread's interrupted status */
+ Thread.currentThread().interrupt();
+ if (trace) log.trace("task was interrupted");
+ }
+ finally
+ {
+ /* no-op if task is completed */
+ future.cancel(true); /* interrupt if running */
+ }
+ }
+
+ /**
+ * Indicates whether the current nodes is the coordinator of the cluster.
+ *
+ * @param newView View instance containing the new view of the cluster
+ * @return whether the current node is the coordinator or not.
+ */
+ private boolean isCoordinator(View newView)
+ {
+ if (newView != null && localAddress != null)
+ {
+ Vector mbrs = newView.getMembers();
+ if (mbrs != null)
+ {
+ if (mbrs.size() > 0 && localAddress.equals(mbrs.firstElement()))
+ {
+ /* This node is the coordinator */
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /* Invalid new view, so previous value returned */
+ return active;
+ }
+
+ /**
+ * Calls the underlying cache loader's operation if the current node is the coordinator.
+ */
+// @Override
+ public Object put(Fqn name, Object key, Object value) throws Exception
+ {
+ if (active)
+ {
+// return super.put(name, key, value);
+ }
+
+ return null;
+ }
+
+ /**
+ * Calls the underlying cache loader's operation if the current node is the coordinator.
+ */
+// @Override
+ public void put(Fqn name, Map attributes) throws Exception
+ {
+ // TODO implement me
+// if (active)
+// {
+// super.put(name, attributes);
+// }
+ }
+
+ /**
+ * Calls the underlying cache loader's operation if the current node is the coordinator.
+ */
+// @Override
+// public void put(List<Modification> modifications) throws Exception
+// {
+ // TODO implement me
+// if (active)
+// {
+// super.put(modifications);
+// }
+// }
+
+ /**
+ * Calls the underlying cache loader's operation if the current node is the coordinator.
+ */
+// @Override
+ public Object remove(Fqn fqn, Object key) throws Exception
+ {
+ if (active)
+ {
+// return super.remove(fqn, key);
+ }
+
+ return null;
+ }
+
+ /**
+ * Calls the underlying cache loader's operation if the current node is the coordinator.
+ */
+// @Override
+ public void remove(Fqn fqn) throws Exception
+ {
+ if (active)
+ {
+ super.remove(fqn);
+ }
+ }
+
+ /**
+ * Calls the underlying cache loader's operation if the current node is the coordinator.
+ */
+// @Override
+ public void removeData(Fqn fqn) throws Exception
+ {
+ if (active)
+ {
+// super.removeData(fqn);
+ }
+ }
+
+ /**
+ * Calls the underlying cache loader's operation if the current node is the coordinator.
+ */
+// @Override
+// public void prepare(Object tx, List<Modification> modifications, boolean one_phase) throws Exception
+// {
+// if (active)
+// {
+// super.prepare(tx, modifications, one_phase);
+// }
+// }
+
+ /**
+ * Calls the underlying cache loader's operation if the current node is the coordinator.
+ */
+ @Override
+ public void commit(Object tx) // throws Exception
+ {
+ if (active)
+ {
+ super.commit(tx);
+ }
+ }
+
+ /**
+ * Calls the underlying cache loader's operation if the current node is the coordinator.
+ */
+ @Override
+ public void rollback(Object tx)
+ {
+ if (active)
+ {
+ super.rollback(tx);
+ }
+ }
+
+ /**
+ * Calls the underlying cache loader's operation if the current node is the coordinator.
+ */
+ @Override
+ public void storeEntireState(ObjectInputStream is) //throws Exception
+ {
+ if (active)
+ {
+ super.storeEntireState(is);
+ }
+ }
+
+ /**
+ * Calls the underlying cache loader's operation if the current node is the coordinator.
+ */
+// @Override
+ public void storeState(Fqn subtree, ObjectInputStream is) throws Exception
+ {
+ if (active)
+ {
+ // super.storeState(subtree, is);
+ }
+ }
+
+ /**
+ * Calls the underlying cache loader's operation if the current node is the coordinator.
+ */
+ @Override
+ public String toString()
+ {
+ return "loc_addr=" + localAddress + ", active=" + active;
+ }
+
+ /**
+ * Cache listener that reacts to cluster topology changes to find out whether a new coordinator is elected.
+ * SingletonStoreCacheLoader reacts to these changes in order to decide which node should interact with the
+ * underlying cache store.
+ */
+ @CacheListener
+ public class SingletonStoreListener
+ {
+ /**
+ * Cache started, check whether the node is the coordinator and set the singleton store cache loader's active
+ * status.
+ */
+ @CacheStarted
+ public void cacheStarted(Event e)
+ {
+ localAddress = cache.getLocalAddress();
+ active = cache.getRPCManager().isCoordinator();
+ if (log.isDebugEnabled()) log.debug("cache started: " + this);
+ }
+
+ @CacheStopped
+ public void cacheStopped(Event e)
+ {
+ if (log.isDebugEnabled()) log.debug("cache stopped: " + this);
+ }
+
+ /**
+ * The cluster formation changed, so determine whether the current node stopped being the coordinator or became
+ * the coordinator. This method can lead to an optional in memory to cache loader state push, if the current node
+ * became the coordinator. This method will report any issues that could potentially arise from this push.
+ */
+ @ViewChanged
+ public void viewChange(ViewChangedEvent event)
+ {
+ boolean tmp = isCoordinator(event.getNewView());
+
+ if (active != tmp)
+ {
+ try
+ {
+ activeStatusChanged(tmp);
+ }
+ catch (PushStateException e)
+ {
+ log.error("exception reported changing nodes active status", e);
+ }
+
+ }
+ }
+ }
+
+ /**
+ * Exception representing any issues that arise from pushing the in-memory state to the cache loader.
+ */
+ public static class PushStateException extends Exception
+ {
+ private static final long serialVersionUID = 5542893943730200886L;
+
+ public PushStateException(String message, Throwable cause)
+ {
+ super(message, cause);
+ }
+
+ public PushStateException(Throwable cause)
+ {
+ super(cause);
+ }
+ }
+}
\ No newline at end of file
Property changes on: core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreCacheLoader.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Copied: core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreDefaultConfig.java (from rev 7484, core/branches/flat/src/main/java/org/jboss/cache/loader/SingletonStoreDefaultConfig.java)
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreDefaultConfig.java (rev 0)
+++ core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreDefaultConfig.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,175 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.horizon.loader;
+
+
+import org.horizon.config.CacheLoaderConfig.IndividualCacheLoaderConfig.SingletonStoreConfig;
+import org.horizon.config.Dynamic;
+
+import java.util.Properties;
+
+/**
+ * Default singleton store cache loader configuration implementation, which is provided with the default singleton store
+ * cache loader implementation. It provides with the capability of defining whether to push the in memory state to cache
+ * loader when becoming the coordinator within a time constraint.
+ *
+ * @author <a href="mailto:galder.zamarreno at jboss.com">Galder Zamarreno</a>
+ */
+public class SingletonStoreDefaultConfig extends SingletonStoreConfig
+{
+ private static final long serialVersionUID = -5828927920142613537L;
+
+ /**
+ * Boolean indicating whether push state when coordinator has been configured.
+ */
+ @Dynamic
+ private boolean pushStateWhenCoordinator;
+
+ /**
+ * Number of milliseconds configured defining the time constraint for the state push.
+ */
+ @Dynamic
+ private int pushStateWhenCoordinatorTimeout;
+
+ /**
+ * Default constructor that sets default values for singleton store cache loader configuration taking in account
+ * that this configuration belongs to the default singleton store cache loader implementation.
+ */
+ public SingletonStoreDefaultConfig()
+ {
+ /* pushStateWhenCoordinator enabled by default with 20 seconds as default timeout*/
+ pushStateWhenCoordinator = true;
+ pushStateWhenCoordinatorTimeout = 20000;
+
+ /* if we got to this point, we know that singleton store must have been enabled */
+ setSingletonStoreEnabled(true);
+ /* and we also know that the configuration was created by SingletonStoreCacheLoader */
+ setSingletonStoreClass(SingletonStoreCacheLoader.class.getName());
+ }
+
+ /**
+ * Constructor that sets the assumed values for the default singleton store cache loader implementation and also
+ * the properties, as per the properties section defined in the XML configuration.
+ *
+ * @param base contains properties set in XML configuration
+ */
+ public SingletonStoreDefaultConfig(SingletonStoreConfig base)
+ {
+ this();
+ setSingletonStoreproperties(base.getSingletonStoreproperties());
+ }
+
+ @Override
+ public boolean isSingletonStoreEnabled()
+ {
+ return true;
+ }
+
+ @Override
+ public void setSingletonStoreEnabled(boolean singletonStoreEnabled)
+ {
+ /* ignore it */
+ }
+
+ @Override
+ public String getSingletonStoreClass()
+ {
+ return SingletonStoreCacheLoader.class.getName();
+ }
+
+ @Override
+ public void setSingletonStoreClass(String singletonStoreClass)
+ {
+ /* ignore it */
+ }
+
+ /**
+ * Takes the properties defined and populates the individual instance fields of the default singleton store cache
+ * loader configuration.
+ *
+ * @param props is an instance of Properties containing these values.
+ */
+ @Override
+ public void setSingletonStoreproperties(Properties props)
+ {
+ super.setSingletonStoreproperties(props);
+ String pushStateWhenCoordinatorStr = props.getProperty("pushStateWhenCoordinator");
+ if (pushStateWhenCoordinatorStr != null)
+ {
+ /* if not null, we use the defined value, otherwise we leave it to the default value, true */
+ /* note: default value for a null property is false, hence the check */
+ setPushStateWhenCoordinator(Boolean.valueOf(pushStateWhenCoordinatorStr));
+ }
+ String pushStateWhenCoordinatorTimeoutStr = props.getProperty("pushStateWhenCoordinatorTimeout");
+ if (pushStateWhenCoordinatorTimeoutStr != null)
+ {
+ setPushStateWhenCoordinatorTimeout(Integer.parseInt(pushStateWhenCoordinatorTimeoutStr));
+ }
+ }
+
+ public boolean isPushStateWhenCoordinator()
+ {
+ return pushStateWhenCoordinator;
+ }
+
+ public void setPushStateWhenCoordinator(boolean pushStateWhenCoordinator)
+ {
+ testImmutability("pushStateWhenCoordinator");
+ this.pushStateWhenCoordinator = pushStateWhenCoordinator;
+ }
+
+ public int getPushStateWhenCoordinatorTimeout()
+ {
+ return pushStateWhenCoordinatorTimeout;
+ }
+
+ public void setPushStateWhenCoordinatorTimeout(int pushStateWhenCoordinatorTimeout)
+ {
+ testImmutability("pushStateWhenCoordinatorTimeout");
+ this.pushStateWhenCoordinatorTimeout = pushStateWhenCoordinatorTimeout;
+ }
+
+ @Override
+ public boolean equals(Object obj)
+ {
+ if (this == obj)
+ return true;
+
+ if (obj instanceof SingletonStoreDefaultConfig)
+ {
+ SingletonStoreDefaultConfig other = (SingletonStoreDefaultConfig) obj;
+ return (other.pushStateWhenCoordinator == this.pushStateWhenCoordinator)
+ && (other.pushStateWhenCoordinatorTimeout == this.pushStateWhenCoordinatorTimeout);
+ }
+ return false;
+ }
+
+
+ @Override
+ public int hashCode()
+ {
+ int result = 13;
+ result = 23 * result + (pushStateWhenCoordinator ? 0 : 1);
+ result = 23 * result + pushStateWhenCoordinatorTimeout;
+ return result;
+ }
+}
Property changes on: core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreDefaultConfig.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Copied: core/branches/flat/src/main/java/org/horizon/lock/IsolationLevel.java (from rev 7484, core/branches/flat/src/main/java/org/jboss/cache/lock/IsolationLevel.java)
===================================================================
--- core/branches/flat/src/main/java/org/horizon/lock/IsolationLevel.java (rev 0)
+++ core/branches/flat/src/main/java/org/horizon/lock/IsolationLevel.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,43 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.horizon.lock;
+
+/**
+ * Various transaction isolation levels as an enumerated class. Note that <a href="http://wiki.jboss.org/wiki/JBossCacheMVCC">MVCC</a>
+ * in JBoss Cache 3.0.0 and above only supports {@link #READ_COMMITTED} and {@link #REPEATABLE_READ}, upgrading where possible.
+ * <p/>
+ * Also note that JBoss Cache defaults to {@link #REPEATABLE_READ}.
+ * <p/>
+ *
+ * @see <a href="http://en.wikipedia.org/wiki/Isolation_%28computer_science%29">Isolation levels</a>
+ */
+public enum IsolationLevel
+{
+ /**
+ * No isolation.
+ */
+ NONE,
+ SERIALIZABLE,
+ REPEATABLE_READ,
+ READ_COMMITTED,
+ READ_UNCOMMITTED
+}
Property changes on: core/branches/flat/src/main/java/org/horizon/lock/IsolationLevel.java
___________________________________________________________________
Name: svn:executable
+ *
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Modified: core/branches/flat/src/main/java/org/horizon/marshall/CommandAwareRpcDispatcher.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/CommandAwareRpcDispatcher.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/marshall/CommandAwareRpcDispatcher.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -23,9 +23,6 @@
import org.horizon.commands.ReplicableCommand;
import org.horizon.commands.VisitableCommand;
-import org.horizon.commands.remote.AnnounceBuddyPoolNameCommand;
-import org.horizon.commands.remote.AssignToBuddyGroupCommand;
-import org.horizon.commands.remote.RemoveFromBuddyGroupCommand;
import org.horizon.config.Configuration;
import org.horizon.context.InvocationContext;
import org.horizon.factories.ComponentRegistry;
@@ -218,13 +215,8 @@
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 (!(cmd instanceof AnnounceBuddyPoolNameCommand ||
- cmd instanceof AssignToBuddyGroupCommand ||
- cmd instanceof RemoveFromBuddyGroupCommand)
- && !componentRegistry.invocationsAllowed(false))
- {
- return null;
- }
+ if (!componentRegistry.invocationsAllowed(false)) return null;
+
return cmd.perform(null);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/NotifierImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/NotifierImpl.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/notifications/NotifierImpl.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -75,13 +75,13 @@
private static final Class[] allowedMethodAnnotations =
{
CacheStarted.class, CacheStopped.class, CacheEntryCreated.class, CacheEntryRemoved.class, CacheEntryVisited.class, CacheEntryModified.class,
- CacheEntryActivated.class, CacheEntryPassivated.class, CacheEntryLoaded.class, CacheEntryEvicted.class, TransactionRegistered.class, TransactionCompleted.class, ViewChanged.class, BuddyGroupChanged.class,
+ CacheEntryActivated.class, CacheEntryPassivated.class, CacheEntryLoaded.class, CacheEntryEvicted.class, TransactionRegistered.class, TransactionCompleted.class, ViewChanged.class,
CacheEntryInvalidated.class
};
private static final Class[] parameterTypes =
{
CacheStartedEvent.class, CacheStoppedEvent.class, CacheEntryCreatedEvent.class, CacheEntryRemovedEvent.class, CacheEntryVisitedEvent.class, CacheEntryModifiedEvent.class,
- CacheEntryActivatedEvent.class, CacheEntryPassivatedEvent.class, CacheEntryLoadedEvent.class, CacheEntryEvictedEvent.class, TransactionRegisteredEvent.class, TransactionCompletedEvent.class, ViewChangedEvent.class, BuddyGroupChangedEvent.class,
+ CacheEntryActivatedEvent.class, CacheEntryPassivatedEvent.class, CacheEntryLoadedEvent.class, CacheEntryEvictedEvent.class, TransactionRegisteredEvent.class, TransactionCompletedEvent.class, ViewChangedEvent.class,
CacheEntryInvalidatedEvent.class
};
@@ -100,7 +100,6 @@
final List<ListenerInvocation> transactionRegisteredListeners = new CopyOnWriteArrayList<ListenerInvocation>();
final List<ListenerInvocation> transactionCompletedListeners = new CopyOnWriteArrayList<ListenerInvocation>();
final List<ListenerInvocation> viewChangedListeners = new CopyOnWriteArrayList<ListenerInvocation>();
- final List<ListenerInvocation> buddyGroupChangedListeners = new CopyOnWriteArrayList<ListenerInvocation>();
// final Map<Class, List<ListenerInvocation>> listenerInvocations = new ConcurrentHashMap<Class, List<ListenerInvocation>>();
private Cache cache;
@@ -126,7 +125,6 @@
listenersMap.put(TransactionRegistered.class, transactionRegisteredListeners);
listenersMap.put(TransactionCompleted.class, transactionCompletedListeners);
listenersMap.put(ViewChanged.class, viewChangedListeners);
- listenersMap.put(BuddyGroupChanged.class, buddyGroupChangedListeners);
listenersMap.put(CacheEntryInvalidated.class, nodeInvalidatedListeners);
}
@@ -282,7 +280,6 @@
transactionRegisteredListeners.clear();
transactionCompletedListeners.clear();
viewChangedListeners.clear();
- buddyGroupChangedListeners.clear();
}
public Set<Object> getCacheListeners()
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/EventImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/EventImpl.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/EventImpl.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -21,7 +21,6 @@
*/
package org.horizon.notifications.event;
-import org.horizon.buddyreplication.BuddyGroup;
import org.horizon.Cache;
import org.horizon.tree.Fqn;
import org.jgroups.View;
@@ -37,7 +36,7 @@
public class EventImpl implements CacheStartedEvent, CacheStoppedEvent,
CacheEntryActivatedEvent, CacheEntryCreatedEvent, CacheEntryEvictedEvent, CacheEntryLoadedEvent, CacheEntryModifiedEvent,
CacheEntryPassivatedEvent, CacheEntryRemovedEvent, CacheEntryVisitedEvent, TransactionCompletedEvent, TransactionRegisteredEvent,
- ViewChangedEvent, BuddyGroupChangedEvent, CacheEntryInvalidatedEvent
+ ViewChangedEvent, CacheEntryInvalidatedEvent
{
private boolean pre = false; // by default events are after the fact
private Cache cache;
@@ -48,9 +47,7 @@
private boolean successful;
private View newView;
private Type type;
- private BuddyGroup buddyGroup;
-
public EventImpl(boolean pre, Cache cache, Object key, Transaction transaction, boolean originLocal, Fqn targetFqn, boolean successful, View newView, Type type)
{
this.pre = pre;
@@ -160,11 +157,6 @@
this.type = type;
}
- public void setBuddyGroup(BuddyGroup buddyGroup)
- {
- this.buddyGroup = buddyGroup;
- }
-
@Override
public boolean equals(Object o)
{
@@ -181,7 +173,6 @@
if (targetFqn != null ? !targetFqn.equals(event.targetFqn) : event.targetFqn != null) return false;
if (transaction != null ? !transaction.equals(event.transaction) : event.transaction != null) return false;
if (newView != null ? !newView.equals(event.newView) : event.newView != null) return false;
- if (buddyGroup != null ? !buddyGroup.equals(event.buddyGroup) : event.buddyGroup != null) return false;
if (type != null ? !type.equals(event.type) : event.type != null) return false;
return true;
@@ -199,7 +190,6 @@
result = 31 * result + (targetFqn != null ? targetFqn.hashCode() : 0);
result = 31 * result + (successful ? 1 : 0);
result = 31 * result + (newView != null ? newView.hashCode() : 0);
- result = 31 * result + (buddyGroup != null ? buddyGroup.hashCode() : 0);
result = 31 * result + (type != null ? type.hashCode() : 0);
return result;
}
@@ -218,12 +208,6 @@
", targetFqn=" + targetFqn +
", successful=" + successful +
", newView=" + newView +
- ", buddyGroup=" + buddyGroup +
'}';
}
-
- public BuddyGroup getBuddyGroup()
- {
- return buddyGroup;
- }
}
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-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/remoting/RPCManagerImpl.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -282,42 +282,6 @@
return muxchannel;
}
-
- @Deprecated
- private void removeLocksForDeadMembers(List deadMembers)
- {
-// Set<GlobalTransaction> deadOwners = new HashSet<GlobalTransaction>();
-// Object owner = lockManager.getOwner(node);
-//
-// todo fix me
-// /*
-// if (isLockOwnerDead(owner, deadMembers)) deadOwners.add((GlobalTransaction) owner);
-//
-//
-// for (Object readOwner : lockManager.getReadOwners(node))
-// {
-// if (isLockOwnerDead(readOwner, deadMembers)) deadOwners.add((GlobalTransaction) readOwner);
-// }
-// */
-//
-// for (GlobalTransaction deadOwner : deadOwners)
-// {
-// boolean localTx = deadOwner.getAddress().equals(getLocalAddress());
-// TODO: Fix me!!!
-// boolean broken = LockUtil.breakTransactionLock(node.getKey(), lockManager, deadOwner, localTx, txTable, txManager);
-// boolean broken = true;
-//
-// if (broken && trace) log.trace("Broke lock for node " + node.getKey() + " held by " + deadOwner);
-// }
-//
-// Recursively unlock children
-// for (Object child : node.getChildrenDirect())
-// {
-// removeLocksForDeadMembers((NodeSPI) child, deadMembers);
-// }
- }
-
-
/**
* Only used with MVCC.
*/
@@ -378,9 +342,6 @@
// short circuit if we don't have an RpcDispatcher!
if (rpcDispatcher == null) return null;
int modeToUse = mode;
- int preferredMode;
- if ((preferredMode = spi.getInvocationContext().getOptionOverrides().getGroupRequestMode()) > -1)
- modeToUse = preferredMode;
if (trace)
log.trace("callRemoteMethods(): valid members are " + recipients + " methods: " + command + " Using OOB? " + useOutOfBandMessage);
if (channel.flushSupported())
Modified: core/branches/flat/src/main/java/org/horizon/tree/Fqn.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/Fqn.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/main/java/org/horizon/tree/Fqn.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -131,7 +131,6 @@
*
* @param names List of names
* @param safe whether this list is referenced externally (safe = false) or not (safe = true).
- * @deprecated use {@link #fromList(java.util.List)} instead. The boolean "safety" hint is calculated internally. This constructor will be removed in 3.0.0.
*/
@SuppressWarnings("unchecked")
private Fqn(List names, boolean safe)
Copied: core/branches/flat/src/main/java/org/horizon/tree/NodeNotExistsException.java (from rev 7484, core/branches/flat/src/main/java/org/jboss/cache/NodeNotExistsException.java)
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/NodeNotExistsException.java (rev 0)
+++ core/branches/flat/src/main/java/org/horizon/tree/NodeNotExistsException.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,57 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.horizon.tree;
+
+import org.horizon.CacheException;
+
+
+/**
+ * Thrown when an operation is attempted on a non-existing node in the cache
+ *
+ * @author <a href="mailto:bela at jboss.com">Bela Ban</a>.
+ * @version $Id$
+ */
+
+public class NodeNotExistsException extends CacheException
+{
+
+ private static final long serialVersionUID = 779376138690777440L;
+
+ public NodeNotExistsException()
+ {
+ super();
+ }
+
+
+ public NodeNotExistsException(String msg)
+ {
+ super(msg);
+ }
+
+
+ public NodeNotExistsException(String msg, Throwable cause)
+ {
+ super(msg, cause);
+ }
+
+
+}
Property changes on: core/branches/flat/src/main/java/org/horizon/tree/NodeNotExistsException.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Copied: core/branches/flat/src/main/java/org/horizon/tree/NodeNotValidException.java (from rev 7484, core/branches/flat/src/main/java/org/jboss/cache/NodeNotValidException.java)
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/NodeNotValidException.java (rev 0)
+++ core/branches/flat/src/main/java/org/horizon/tree/NodeNotValidException.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,53 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.horizon.tree;
+
+import org.horizon.CacheException;
+
+/**
+ * Thrown whenever operations are attempted on a node that is no longer valid. See {@link Node#isValid()}
+ * for details.
+ *
+ * @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
+ * @since 2.1.0
+ */
+public class NodeNotValidException extends CacheException
+{
+ public NodeNotValidException()
+ {
+ }
+
+ public NodeNotValidException(Throwable cause)
+ {
+ super(cause);
+ }
+
+ public NodeNotValidException(String msg)
+ {
+ super(msg);
+ }
+
+ public NodeNotValidException(String msg, Throwable cause)
+ {
+ super(msg, cause);
+ }
+}
Property changes on: core/branches/flat/src/main/java/org/horizon/tree/NodeNotValidException.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Copied: core/branches/flat/src/test/java/org/horizon/BasicTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/BasicTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/BasicTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/BasicTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,116 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.horizon;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.horizon.config.Configuration;
+import org.horizon.manager.CacheManager;
+import org.horizon.manager.NamedCacheNotFoundException;
+import org.horizon.util.TestingUtil;
+import org.horizon.Cache;
+import org.horizon.CacheSPI;
+import org.testng.annotations.Test;
+
+ at Test(groups = "functional")
+public class BasicTest
+{
+ public void basicTest() throws Exception
+ {
+ // create a cache manager
+ Configuration c = new Configuration(); // LOCAL mode
+ c.setFetchInMemoryState(false);
+ CacheManager cm = new CacheManager(c);
+ try
+ {
+ cm.start();
+ Cache cache = cm.getCache("test");
+ String key = "key", value = "value";
+
+ assert cache.isEmpty();
+ assert cache.size() == 0;
+ assert !cache.containsKey(key);
+
+ cache.put(key, value);
+ assert cache.size() == 1;
+ assert cache.containsKey(key);
+ assert !cache.isEmpty();
+
+ assert cache.remove(key).equals(value);
+
+ assert cache.isEmpty();
+ assert cache.size() == 0;
+ assert !cache.containsKey(key);
+ }
+ finally
+ {
+ cm.stop();
+ }
+ }
+
+ public static final Log log = LogFactory.getLog(BasicTest.class);
+
+ public void testBasicReplication() throws NamedCacheNotFoundException
+ {
+ Configuration configuration = new Configuration();
+ configuration.setCacheMode(Configuration.CacheMode.REPL_SYNC);
+
+ CacheManager firstManager = new CacheManager(configuration);
+ CacheManager secondManager = new CacheManager(configuration);
+
+ try
+ {
+ firstManager.start();
+ secondManager.start();
+
+ 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");
+ assert firstCache.get("key").equals("value");
+ secondCache.put("key", "value2");
+ assert firstCache.get("key").equals("value2");
+ firstCache.remove("key");
+ assert secondCache.get("key") == null;
+ }
+ finally
+ {
+ firstManager.stop();
+ secondManager.stop();
+ }
+ }
+
+ public void concurrentMapMethodTest()
+ {
+
+ }
+
+ public void transactionalTest()
+ {
+
+ }
+}
Property changes on: core/branches/flat/src/test/java/org/horizon/BasicTest.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Copied: core/branches/flat/src/test/java/org/horizon/UnitTestCacheFactory.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/UnitTestCacheFactory.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/UnitTestCacheFactory.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/UnitTestCacheFactory.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,362 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.horizon;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.horizon.config.Configuration;
+import org.horizon.config.ConfigurationException;
+import org.horizon.config.parsing.XmlConfigurationParserJBC3;
+import org.horizon.manager.CacheManager;
+import org.horizon.util.TestingUtil;
+import org.jgroups.conf.XmlConfigurator;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * @author <a href="mailto:dpospisi at redhat.com">Dominik Pospisil (dpospisi at redhat.com)</a>
+ */
+public class UnitTestCacheFactory<K, V>// implements CacheFactory<K, V>
+{
+
+ private final Log log = LogFactory.getLog(UnitTestCacheFactory.class);
+
+
+ /**
+ * Holds unique mcast_addr for each thread used for JGroups channel construction.
+ */
+ private static final ThreadLocal<String> threadMcastIP = new ThreadLocal<String>()
+ {
+ private final AtomicInteger uniqueAddr = new AtomicInteger(11);
+
+ @Override
+ protected String initialValue()
+ {
+ return "228.10.10." + uniqueAddr.getAndIncrement();
+ }
+ };
+
+ /**
+ * Holds unique mcast_port for each thread used for JGroups channel construction.
+ */
+ private static final ThreadLocal<Integer> threadMcastPort = new ThreadLocal<Integer>()
+ {
+ private final AtomicInteger uniquePort = new AtomicInteger(45589);
+
+ @Override
+ protected Integer initialValue()
+ {
+ return uniquePort.getAndIncrement();
+ }
+ };
+
+ /**
+ * For each thread holds list of caches created using this factory.
+ */
+ private static final ThreadLocal<List<Cache>> threadCaches =
+ new ThreadLocal<List<Cache>>()
+ {
+ @Override
+ protected List<Cache> initialValue()
+ {
+ return new ArrayList<Cache>();
+ }
+ };
+
+ private final static List<Cache> allCaches = new ArrayList<Cache>();
+
+ /**
+ * For each thread holds the name of the test class which executed createCache factory method.
+ */
+ private static final ThreadLocal<String> threadTestName = new ThreadLocal<String>();
+
+ // factory methods
+
+ public Cache<K, V> createCache() throws ConfigurationException
+ {
+ return createCache(true);
+ }
+
+ public Cache<K, V> createCache(boolean start) throws ConfigurationException
+ {
+ return createCache(new Configuration(), start);
+ }
+
+ public Cache<K, V> createCache(String configFileName) throws ConfigurationException
+ {
+ return createCache(configFileName, true);
+ }
+
+ public Cache<K, V> createCache(String configFileName, boolean start) throws ConfigurationException
+ {
+ XmlConfigurationParserJBC3 parser = new XmlConfigurationParserJBC3();
+ Configuration c;
+ c = parser.parseFile(configFileName);
+ return createCache(c, start);
+ }
+
+ public Cache<K, V> createCache(Configuration configuration) throws ConfigurationException
+ {
+ return createCache(configuration, true);
+ }
+
+ public Cache<K, V> createCache(InputStream is) throws ConfigurationException
+ {
+ return createCache(is, true);
+ }
+
+ public Cache<K, V> createCache(InputStream is, boolean start) throws ConfigurationException
+ {
+ XmlConfigurationParserJBC3 parser = new XmlConfigurationParserJBC3();
+ Configuration c = parser.parseStream(is);
+ return createCache(c, start);
+ }
+
+ public Cache<K, V> createCache(Configuration configuration, boolean start) throws ConfigurationException
+ {
+ // - Do not print out this exception - since tests are ALSO run from IDEs on the main thread. - MANIK
+// if (!Thread.currentThread().getName().contains("pool"))
+// {
+// System.out.println("CreateCache called from wrong thread: " + Thread.currentThread().getName());
+// }
+
+ checkCaches();
+
+ switch (configuration.getCacheMode())
+ {
+ case LOCAL:
+ // local cache, no channel used
+ break;
+ case REPL_SYNC:
+ case REPL_ASYNC:
+ case INVALIDATION_ASYNC:
+ case INVALIDATION_SYNC:
+ // replicated cache, update channel setup
+ mangleConfiguration(configuration);
+ break;
+ default:
+ log.info("Unknown cache mode!");
+ }
+
+// Cache<K, V> cache = new DefaultCacheFactory<K, V>().createCache(configuration, start);
+ CacheManager cm = new CacheManager(configuration);
+ Cache<K, V> cache = cm.getCache();
+
+ List<Cache> caches = threadCaches.get();
+ caches.add(cache);
+
+ synchronized (allCaches)
+ {
+ allCaches.add(cache);
+ }
+ return cache;
+
+ }
+
+ /**
+ * Destroys all caches created by this factory in the current thread.
+ *
+ * @return true if some cleanup was actually performed
+ */
+ public boolean cleanUp()
+ {
+ List<Cache> caches = new ArrayList<Cache>(threadCaches.get());
+ boolean ret = false;
+
+ for (Cache cache : caches)
+ {
+ TestingUtil.killCaches(cache);
+ ret = true;
+ }
+ return ret;
+ }
+
+ public void removeCache(Cache c)
+ {
+
+ // - Do not print out this exception - since tests are ALSO run from IDEs on the main thread. - MANIK
+// if (!Thread.currentThread().getName().contains("pool"))
+// {
+// System.out.println("RemoveCache called from wrong thread.");
+// }
+
+ List<Cache> caches = threadCaches.get();
+ synchronized (allCaches)
+ {
+ if (caches.contains(c))
+ {
+ caches.remove(c);
+ allCaches.remove(c);
+ }
+ else if (allCaches.contains(c))
+ {
+ System.out.println("[" + Thread.currentThread().getName() + "] WARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Remove cache called from different thread.");
+ Thread.dumpStack();
+ }
+ }
+ }
+
+ /**
+ * Updates cluster configuration to ensure mutual thread isolation.
+ *
+ * @param configuration Configuration to update.
+ */
+ public void mangleConfiguration(Configuration configuration)
+ {
+
+ configuration.setClusterConfig(mangleClusterConfiguration(configuration.getClusterConfig()));
+ // Check if the cluster name contains thread id. If not, append.
+ // We can not just append the threadId, since some of the tests are crating instances
+ // using configurations derived from configurations returned by this factory.
+
+ String clusterName = configuration.getClusterName();
+
+ // append thread id
+ if (clusterName.indexOf(Thread.currentThread().getName()) == -1)
+ {
+ clusterName = clusterName + "-" + Thread.currentThread().getName();
+// System.out.println(getThreadId() + " Setting cluster name " + newClusterName);
+ }
+
+// String testName = extractTestName();
+
+ // prepend test name
+ /*
+ if (clusterName.indexOf(testName) == -1) {
+ clusterName = testName + "-" + clusterName;
+ }
+ */
+
+ configuration.setClusterName(clusterName);
+
+ }
+
+ /**
+ * Updates cluster configuration to ensure mutual thread isolation.
+ */
+ public String mangleClusterConfiguration(String clusterConfig)
+ {
+ if (clusterConfig == null)
+ {
+ // No explicit cluster configuration found. we need to resolve the default config
+ // now in orded to be able to update it before the cache (and the channel) starts.
+
+ clusterConfig = getDefaultClusterConfiguration();
+ }
+
+ // replace mcast_addr
+ Pattern pattern = Pattern.compile("mcast_addr=[^;]*");
+ Matcher m = pattern.matcher(clusterConfig);
+ if (m.find())
+ {
+ String origAddr = m.group().substring(m.group().indexOf("=") + 1);
+ String newAddr = threadMcastIP.get();
+// System.out.println(getThreadId() + " Replacing mcast_addr " + origAddr + " with " + newAddr);
+ clusterConfig = m.replaceFirst("mcast_addr=" + newAddr);
+ }
+ else
+ {
+ Thread.dumpStack();
+ System.exit(1);
+ }
+
+ // replace mcast_port
+ pattern = Pattern.compile("mcast_port=[^;]*");
+ m = pattern.matcher(clusterConfig);
+ if (m.find())
+ {
+// String origPort = m.group().substring(m.group().indexOf("=") + 1);
+ String newPort = threadMcastPort.get().toString();
+ // System.out.println(getThreadId() + " Replacing mcast_port " + origPort + " with " + newPort);
+ clusterConfig = m.replaceFirst("mcast_port=" + newPort);
+ }
+
+ return clusterConfig;
+ }
+
+// private String getThreadId()
+// {
+// return "[" + Thread.currentThread().getName() + "]";
+// }
+
+ private void checkCaches()
+ {
+ String lastTestName = threadTestName.get();
+ String currentTestName = extractTestName();
+
+ if ((lastTestName != null) && (!lastTestName.equals(currentTestName)))
+ {
+
+ String threadId = "[" + Thread.currentThread().getName() + "] ";
+
+ // we are running new test class
+ // check if there is a cache(s) instance left & kill it if possitive
+
+ if (cleanUp())
+ {
+ System.out.print(threadId + "WARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ");
+ System.out.print(threadId + " A test method in " + lastTestName + " did not clean all cache instances properly. ");
+ System.out.println(threadId + " Use UnitTestCacheFactory.cleanUp() or TestngUtil.killCaches(...) ");
+ }
+
+ }
+ threadTestName.set(currentTestName);
+ }
+
+ private String extractTestName()
+ {
+ StackTraceElement[] stack = Thread.currentThread().getStackTrace();
+ if (stack.length == 0) return null;
+ for (int i = stack.length - 1; i > 0; i--)
+ {
+ StackTraceElement e = stack[i];
+ String className = e.getClassName();
+ if (className.indexOf("org.horizon") != -1) return className; //+ "." + e.getMethodName();
+ }
+ return null;
+ }
+
+ private String getDefaultClusterConfiguration()
+ {
+ return getClusterConfigFromFile(new Configuration().getDefaultClusterConfig());
+ }
+
+ /**
+ * Helper method that takes a <b>JGroups</b> configuration file and creates an old-style JGroups config {@link String} that can be used
+ * in {@link Configuration#setClusterConfig(String)}. Note that expressions
+ * in the file - such as <tt>${jgroups.udp.mcast_port:45588}</tt> are expanded out accordingly.
+ *
+ * @param url url to the cfg file
+ * @return a String
+ */
+ public static String getClusterConfigFromFile(URL url)
+ {
+ try
+ {
+ XmlConfigurator conf = XmlConfigurator.getInstance(url);
+ String tmp = conf.getProtocolStackString();
+ // parse this string for ${} substitutions
+ // Highly crappy approach!!
+ tmp = tmp.replace("${jgroups.udp.mcast_addr:228.10.10.10}", "228.10.10.10");
+ tmp = tmp.replace("${jgroups.udp.mcast_port:45588}", "45588");
+ tmp = tmp.replace("${jgroups.udp.ip_ttl:2}", "2");
+// System.out.println("config string: " + tmp);
+ return tmp;
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException("Problems with url " + url, e);
+ }
+ }
+
+}
Property changes on: core/branches/flat/src/test/java/org/horizon/UnitTestCacheFactory.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Copied: core/branches/flat/src/test/java/org/horizon/UnitTestCacheManager.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/UnitTestCacheManager.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/UnitTestCacheManager.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/UnitTestCacheManager.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,32 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package org.horizon;
+
+import org.horizon.config.Configuration;
+
+/**
+ * @author dpospisi
+ */
+public class UnitTestCacheManager
+{
+ Configuration c;
+
+ public UnitTestCacheManager(Configuration c)
+ {
+ this.c = c.clone();
+ }
+
+ protected Cache createNewCache()
+ {
+ UnitTestCacheFactory dcf = new UnitTestCacheFactory();
+ return dcf.createCache(c);
+ }
+
+ public Cache createCache(String name)
+ {
+ return createNewCache();
+ }
+}
Property changes on: core/branches/flat/src/test/java/org/horizon/UnitTestCacheManager.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Copied: core/branches/flat/src/test/java/org/horizon/api (from rev 7484, core/branches/flat/src/test/java/org/jboss/starobrno/api)
Deleted: core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/CacheAPITest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,226 +0,0 @@
-package org.jboss.starobrno.api;
-
-import org.jboss.cache.CacheFactory;
-import org.jboss.cache.lock.IsolationLevel;
-import org.jboss.starobrno.CacheSPI;
-import org.jboss.starobrno.UnitTestCacheFactory;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.config.ConfigurationException;
-import org.jboss.starobrno.transaction.DummyTransactionManager;
-import org.jboss.starobrno.transaction.DummyTransactionManagerLookup;
-import org.jboss.starobrno.util.TestingUtil;
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertNull;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Tests the {@link org.jboss.cache.Cache} public API at a high level
- *
- * @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
- */
-
- at Test(groups = {"functional", "pessimistic"})
-public abstract class CacheAPITest
-{
- private ThreadLocal<CacheSPI<String, String>> cacheTL = new ThreadLocal<CacheSPI<String, String>>();
-
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
- // start a single cache instance
- Configuration c = new Configuration();
- c.setIsolationLevel(getIsolationLevel());
- c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- CacheFactory<String, String> cf = new UnitTestCacheFactory<String, String>();
- CacheSPI<String, String> cache = (CacheSPI<String, String>) cf.createCache(c.clone());
- cacheTL.set(cache);
- }
-
- protected abstract IsolationLevel getIsolationLevel();
-
- @AfterMethod(alwaysRun = true)
- public void tearDown()
- {
- CacheSPI<String, String> cache = cacheTL.get();
- TestingUtil.killCaches(cache);
- cacheTL.set(null);
- }
-
- /**
- * Tests that the configuration contains the values expected, as well as immutability of certain elements
- */
- public void testConfiguration()
- {
- CacheSPI<String, String> cache = cacheTL.get();
- Configuration c = cache.getConfiguration();
- assertEquals(Configuration.CacheMode.LOCAL, c.getCacheMode());
- assertEquals(DummyTransactionManagerLookup.class.getName(), c.getTransactionManagerLookupClass());
-
- // note that certain values should be immutable. E.g., CacheMode cannot be changed on the fly.
- try
- {
- c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
- assert false : "Should have thrown an Exception";
- }
- catch (ConfigurationException e)
- {
- // expected
- }
-
- // others should be changeable though.
- c.setLockAcquisitionTimeout(100);
- }
-
- public void testGetMembersInLocalMode()
- {
- CacheSPI<String, String> cache = cacheTL.get();
- assert cache.getRPCManager().getLocalAddress() == null : "Cache members should be null if running in LOCAL mode";
- }
-
- /**
- * All cache operations should happen on a {@link Node} - I.e., you look up a {@link Node} and perform data operations
- * on this {@link Node}. For convenience and familiarity with JBoss Cache 1.x, we provide some helpers in {@link Cache}
- * which dives you direct data access to nodes.
- * <p/>
- * This test exercises these.
- */
- public void testConvenienceMethods()
- {
- CacheSPI<String, String> cache = cacheTL.get();
- String key = "key", value = "value";
- Map<String, String> data = new HashMap<String, String>();
- data.put(key, value);
-
- assertNull(cache.get(key));
-
- cache.put(key, value);
-
- assertEquals(value, cache.get(key));
-
- cache.remove(key);
-
- assertNull(cache.get(key));
-
- cache.putAll(data);
-
- assertEquals(value, cache.get(key));
- }
-
- /**
- * Tests basic eviction
- */
- public void testEvict()
- {
- CacheSPI<String, String> cache = cacheTL.get();
- String key1 = "keyOne", key2 = "keyTwo", value = "value";
-
- cache.put(key1, value);
- cache.put(key2, value);
-
- assert cache.containsKey(key1);
- assert cache.containsKey(key2);
- assert cache.size() == 2;
-
- // evict two
- cache.evict(key2);
-
- assert cache.containsKey(key1);
- assert !cache.containsKey(key2);
- assert cache.size() == 1;
-
- cache.evict(key1);
-
- assert !cache.containsKey(key1);
- assert !cache.containsKey(key2);
- assert cache.size() == 0;
- }
-
- public void testStopClearsData() throws Exception
- {
- CacheSPI<String, String> cache = cacheTL.get();
- String key = "key", value = "value";
- cache.put(key, value);
- assert cache.get(key).equals(value);
- assert 1 == cache.size();
- cache.stop();
-
- cache.start();
-
- assert !cache.containsKey(key);
- assert cache.isEmpty();
- }
-
- public void testRollbackAfterPut() throws Exception
- {
- CacheSPI<String, String> cache = cacheTL.get();
- String key = "key", value = "value";
- cache.put(key, value);
- assert cache.get(key).equals(value);
- assert 1 == cache.size();
-
- DummyTransactionManager.getInstance().begin();
- cache.put("key2", "value2");
- assert cache.get("key2").equals("value2");
- DummyTransactionManager.getInstance().rollback();
-
- assert cache.get(key).equals(value);
- assert 1 == cache.size();
- }
-
- public void testRollbackAfterOverwrite() throws Exception
- {
- CacheSPI<String, String> cache = cacheTL.get();
- String key = "key", value = "value";
- cache.put(key, value);
- assert cache.get(key).equals(value);
- assert 1 == cache.size();
-
- DummyTransactionManager.getInstance().begin();
- cache.put(key, "value2");
- assert cache.get(key).equals("value2");
- assert 1 == cache.size();
- DummyTransactionManager.getInstance().rollback();
-
- assert cache.get(key).equals(value);
- assert 1 == cache.size();
- }
-
- public void testRollbackAfterRemove() throws Exception
- {
- CacheSPI<String, String> cache = cacheTL.get();
- String key = "key", value = "value";
- cache.put(key, value);
- assert cache.get(key).equals(value);
- assert 1 == cache.size();
-
- DummyTransactionManager.getInstance().begin();
- cache.remove(key);
- assert cache.get(key) == null;
- DummyTransactionManager.getInstance().rollback();
-
- assert cache.get(key).equals(value);
- assert 1 == cache.size();
- }
-
- public void testRollbackAfterClear() throws Exception
- {
- CacheSPI<String, String> cache = cacheTL.get();
- String key = "key", value = "value";
- cache.put(key, value);
- assert cache.get(key).equals(value);
- assert 1 == cache.size();
-
- DummyTransactionManager.getInstance().begin();
- cache.clear();
- assert cache.get(key) == null;
- DummyTransactionManager.getInstance().rollback();
-
- assert cache.get(key).equals(value);
- assert 1 == cache.size();
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/CacheAPITest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,218 @@
+package org.horizon.api;
+
+import org.horizon.lock.IsolationLevel;
+import org.horizon.CacheSPI;
+import org.horizon.UnitTestCacheFactory;
+import org.horizon.config.Configuration;
+import org.horizon.config.ConfigurationException;
+import org.horizon.transaction.DummyTransactionManager;
+import org.horizon.transaction.DummyTransactionManagerLookup;
+import org.horizon.util.TestingUtil;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNull;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Tests the {@link org.horizon.Cache} public API at a high level
+ *
+ * @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
+ */
+
+ at Test(groups = {"functional", "pessimistic"})
+public abstract class CacheAPITest
+{
+ private ThreadLocal<CacheSPI<String, String>> cacheTL = new ThreadLocal<CacheSPI<String, String>>();
+
+ @BeforeMethod(alwaysRun = true)
+ public void setUp() throws Exception
+ {
+ // start a single cache instance
+ Configuration c = new Configuration();
+ c.setIsolationLevel(getIsolationLevel());
+ c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ UnitTestCacheFactory<String, String> cf = new UnitTestCacheFactory<String, String>();
+ CacheSPI<String, String> cache = (CacheSPI<String, String>) cf.createCache(c.clone());
+ cacheTL.set(cache);
+ }
+
+ protected abstract IsolationLevel getIsolationLevel();
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown()
+ {
+ CacheSPI<String, String> cache = cacheTL.get();
+ TestingUtil.killCaches(cache);
+ cacheTL.set(null);
+ }
+
+ /**
+ * Tests that the configuration contains the values expected, as well as immutability of certain elements
+ */
+ public void testConfiguration()
+ {
+ CacheSPI<String, String> cache = cacheTL.get();
+ Configuration c = cache.getConfiguration();
+ assertEquals(Configuration.CacheMode.LOCAL, c.getCacheMode());
+ assertEquals(DummyTransactionManagerLookup.class.getName(), c.getTransactionManagerLookupClass());
+
+ // note that certain values should be immutable. E.g., CacheMode cannot be changed on the fly.
+ try
+ {
+ c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
+ assert false : "Should have thrown an Exception";
+ }
+ catch (ConfigurationException e)
+ {
+ // expected
+ }
+
+ // others should be changeable though.
+ c.setLockAcquisitionTimeout(100);
+ }
+
+ public void testGetMembersInLocalMode()
+ {
+ CacheSPI<String, String> cache = cacheTL.get();
+ assert cache.getRPCManager().getLocalAddress() == null : "Cache members should be null if running in LOCAL mode";
+ }
+
+ public void testConvenienceMethods()
+ {
+ CacheSPI<String, String> cache = cacheTL.get();
+ String key = "key", value = "value";
+ Map<String, String> data = new HashMap<String, String>();
+ data.put(key, value);
+
+ assertNull(cache.get(key));
+
+ cache.put(key, value);
+
+ assertEquals(value, cache.get(key));
+
+ cache.remove(key);
+
+ assertNull(cache.get(key));
+
+ cache.putAll(data);
+
+ assertEquals(value, cache.get(key));
+ }
+
+ /**
+ * Tests basic eviction
+ */
+ public void testEvict()
+ {
+ CacheSPI<String, String> cache = cacheTL.get();
+ String key1 = "keyOne", key2 = "keyTwo", value = "value";
+
+ cache.put(key1, value);
+ cache.put(key2, value);
+
+ assert cache.containsKey(key1);
+ assert cache.containsKey(key2);
+ assert cache.size() == 2;
+
+ // evict two
+ cache.evict(key2);
+
+ assert cache.containsKey(key1);
+ assert !cache.containsKey(key2);
+ assert cache.size() == 1;
+
+ cache.evict(key1);
+
+ assert !cache.containsKey(key1);
+ assert !cache.containsKey(key2);
+ assert cache.size() == 0;
+ }
+
+ public void testStopClearsData() throws Exception
+ {
+ CacheSPI<String, String> cache = cacheTL.get();
+ String key = "key", value = "value";
+ cache.put(key, value);
+ assert cache.get(key).equals(value);
+ assert 1 == cache.size();
+ cache.stop();
+
+ cache.start();
+
+ assert !cache.containsKey(key);
+ assert cache.isEmpty();
+ }
+
+ public void testRollbackAfterPut() throws Exception
+ {
+ CacheSPI<String, String> cache = cacheTL.get();
+ String key = "key", value = "value";
+ cache.put(key, value);
+ assert cache.get(key).equals(value);
+ assert 1 == cache.size();
+
+ DummyTransactionManager.getInstance().begin();
+ cache.put("key2", "value2");
+ assert cache.get("key2").equals("value2");
+ DummyTransactionManager.getInstance().rollback();
+
+ assert cache.get(key).equals(value);
+ assert 1 == cache.size();
+ }
+
+ public void testRollbackAfterOverwrite() throws Exception
+ {
+ CacheSPI<String, String> cache = cacheTL.get();
+ String key = "key", value = "value";
+ cache.put(key, value);
+ assert cache.get(key).equals(value);
+ assert 1 == cache.size();
+
+ DummyTransactionManager.getInstance().begin();
+ cache.put(key, "value2");
+ assert cache.get(key).equals("value2");
+ assert 1 == cache.size();
+ DummyTransactionManager.getInstance().rollback();
+
+ assert cache.get(key).equals(value);
+ assert 1 == cache.size();
+ }
+
+ public void testRollbackAfterRemove() throws Exception
+ {
+ CacheSPI<String, String> cache = cacheTL.get();
+ String key = "key", value = "value";
+ cache.put(key, value);
+ assert cache.get(key).equals(value);
+ assert 1 == cache.size();
+
+ DummyTransactionManager.getInstance().begin();
+ cache.remove(key);
+ assert cache.get(key) == null;
+ DummyTransactionManager.getInstance().rollback();
+
+ assert cache.get(key).equals(value);
+ assert 1 == cache.size();
+ }
+
+ public void testRollbackAfterClear() throws Exception
+ {
+ CacheSPI<String, String> cache = cacheTL.get();
+ String key = "key", value = "value";
+ cache.put(key, value);
+ assert cache.get(key).equals(value);
+ assert 1 == cache.size();
+
+ DummyTransactionManager.getInstance().begin();
+ cache.clear();
+ assert cache.get(key) == null;
+ DummyTransactionManager.getInstance().rollback();
+
+ assert cache.get(key).equals(value);
+ assert 1 == cache.size();
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/CacheSPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/CacheSPITest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/CacheSPITest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,92 +0,0 @@
-package org.jboss.starobrno.api;
-
-import org.jboss.starobrno.CacheSPI;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.config.Configuration.CacheMode;
-import org.jboss.starobrno.util.TestingUtil;
-import org.jboss.starobrno.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;
-import org.jboss.starobrno.UnitTestCacheFactory;
-
- at Test(groups = {"functional", "pessimistic"})
-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>>();
-
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
-
- 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);
- }
-
- @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);
-
- }
-
- public void testGetMembers() throws Exception
- {
- CacheSPI<Object, Object> cache1 = cache1TL.get();
- CacheSPI<Object, Object> cache2 = cache2TL.get();
-
- cache1.start();
- List memb1 = cache1.getRPCManager().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();
- assert 2 == memb1.size();
- assert memb1 == memb2;
-
- cache1.stop();
- TestingUtil.blockUntilViewsReceived(5000, false, cache2);
- memb2 = cache2.getRPCManager().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();
-
- cache1.start();
- assert cache1.getRPCManager().isCoordinator();
-
- cache2.start();
- assert cache1.getRPCManager().isCoordinator();
- assert !cache2.getRPCManager().isCoordinator();
- ViewChangeListener viewChangeListener = new ViewChangeListener(cache2);
- cache1.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();
- }
-}
\ No newline at end of file
Copied: core/branches/flat/src/test/java/org/horizon/api/CacheSPITest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/CacheSPITest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/CacheSPITest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/CacheSPITest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,92 @@
+package org.horizon.api;
+
+import org.horizon.CacheSPI;
+import org.horizon.config.Configuration;
+import org.horizon.config.Configuration.CacheMode;
+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;
+import org.horizon.UnitTestCacheFactory;
+
+ at Test(groups = {"functional", "pessimistic"})
+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>>();
+
+ @BeforeMethod(alwaysRun = true)
+ public void setUp() throws Exception
+ {
+
+ 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);
+ }
+
+ @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);
+
+ }
+
+ public void testGetMembers() throws Exception
+ {
+ CacheSPI<Object, Object> cache1 = cache1TL.get();
+ CacheSPI<Object, Object> cache2 = cache2TL.get();
+
+ cache1.start();
+ List memb1 = cache1.getRPCManager().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();
+ assert 2 == memb1.size();
+ assert memb1 == memb2;
+
+ cache1.stop();
+ TestingUtil.blockUntilViewsReceived(5000, false, cache2);
+ memb2 = cache2.getRPCManager().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();
+
+ cache1.start();
+ assert cache1.getRPCManager().isCoordinator();
+
+ cache2.start();
+ assert cache1.getRPCManager().isCoordinator();
+ assert !cache2.getRPCManager().isCoordinator();
+ ViewChangeListener viewChangeListener = new ViewChangeListener(cache2);
+ cache1.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();
+ }
+}
\ No newline at end of file
Deleted: core/branches/flat/src/test/java/org/horizon/api/batch/AbstractBatchTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/AbstractBatchTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/batch/AbstractBatchTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,24 +0,0 @@
-package org.jboss.starobrno.api.batch;
-
-import org.jboss.starobrno.Cache;
-
-import java.util.concurrent.atomic.AtomicReference;
-
-public abstract class AbstractBatchTest
-{
- protected String getOnDifferentThread(final Cache<String, String> cache, final String key) throws InterruptedException
- {
- final AtomicReference<String> ref = new AtomicReference<String>();
- Thread t = new Thread()
- {
- public void run()
- {
- ref.set(cache.get(key));
- }
- };
-
- t.start();
- t.join();
- return ref.get();
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/batch/AbstractBatchTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/AbstractBatchTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/batch/AbstractBatchTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/batch/AbstractBatchTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,24 @@
+package org.horizon.api.batch;
+
+import org.horizon.Cache;
+
+import java.util.concurrent.atomic.AtomicReference;
+
+public abstract class AbstractBatchTest
+{
+ protected String getOnDifferentThread(final Cache<String, String> cache, final String key) throws InterruptedException
+ {
+ final AtomicReference<String> ref = new AtomicReference<String>();
+ Thread t = new Thread()
+ {
+ public void run()
+ {
+ ref.set(cache.get(key));
+ }
+ };
+
+ t.start();
+ t.join();
+ return ref.get();
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTM.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/BatchWithTM.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTM.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,123 +0,0 @@
-package org.jboss.starobrno.api.batch;
-
-import org.jboss.cache.CacheFactory;
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.UnitTestCacheFactory;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.transaction.DummyTransactionManagerLookup;
-import org.jboss.starobrno.util.TestingUtil;
-import org.testng.annotations.Test;
-
-import javax.transaction.TransactionManager;
-
-
- at 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()
- {
- CacheFactory<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/BatchWithTM.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/BatchWithTM.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTM.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTM.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,122 @@
+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;
+
+
+ at 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);
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTM.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/BatchWithoutTM.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTM.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,144 +0,0 @@
-package org.jboss.starobrno.api.batch;
-
-import org.jboss.cache.CacheFactory;
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.UnitTestCacheFactory;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.config.ConfigurationException;
-import org.jboss.starobrno.util.TestingUtil;
-import org.testng.annotations.Test;
-
- at 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)
- {
- CacheFactory<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/BatchWithoutTM.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/BatchWithoutTM.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTM.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTM.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,143 @@
+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;
+
+ at 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);
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/mvcc/LockAssert.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/LockAssert.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/LockAssert.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,35 +0,0 @@
-package org.jboss.starobrno.api.mvcc;
-
-import org.jboss.starobrno.invocation.InvocationContextContainer;
-import org.jboss.starobrno.lock.LockManager;
-import org.jboss.starobrno.util.TestingUtil;
-import org.jboss.starobrno.util.concurrent.locks.LockContainer;
-
-/**
- * Helper class to assert lock status in MVCC
- *
- * @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
- * @since 3.0
- */
-public class LockAssert
-{
- public static void assertLocked(Object key, LockManager lockManager, InvocationContextContainer icc)
- {
- assert lockManager.isLocked(key) : key + " not locked!";
-// assert icc.get().getKeysLocked().contains(key) : "Lock not recorded for " + key;
- }
-
- public static void assertNotLocked(Object key, InvocationContextContainer icc)
- {
- // can't rely on the negative test since other nodes may share the same lock with lock striping.
-// assert !lockManager.isLocked(fqn) : fqn + " is locked!";
- assert !icc.get().getKeysLocked().contains(key) : key + " lock recorded!";
- }
-
- public static void assertNoLocks(LockManager lockManager, InvocationContextContainer icc)
- {
- LockContainer lc = (LockContainer) TestingUtil.extractField(lockManager, "lockContainer");
- assert lc.getNumLocksHeld() == 0 : "Stale locks exist! NumLocksHeld is " + lc.getNumLocksHeld() + " and lock info is " + lockManager.printLockInfo();
- assert icc.get().getKeysLocked().isEmpty() : "Stale (?) locks recorded! " + icc.get().getKeysLocked();
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/mvcc/LockAssert.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/LockAssert.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/LockAssert.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/LockAssert.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,35 @@
+package org.horizon.api.mvcc;
+
+import org.horizon.invocation.InvocationContextContainer;
+import org.horizon.lock.LockManager;
+import org.horizon.util.TestingUtil;
+import org.horizon.util.concurrent.locks.LockContainer;
+
+/**
+ * Helper class to assert lock status in MVCC
+ *
+ * @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
+ * @since 3.0
+ */
+public class LockAssert
+{
+ public static void assertLocked(Object key, LockManager lockManager, InvocationContextContainer icc)
+ {
+ assert lockManager.isLocked(key) : key + " not locked!";
+// assert icc.get().getKeysLocked().contains(key) : "Lock not recorded for " + key;
+ }
+
+ public static void assertNotLocked(Object key, InvocationContextContainer icc)
+ {
+ // can't rely on the negative test since other nodes may share the same lock with lock striping.
+// assert !lockManager.isLocked(fqn) : fqn + " is locked!";
+ assert !icc.get().getKeysLocked().contains(key) : key + " lock recorded!";
+ }
+
+ public static void assertNoLocks(LockManager lockManager, InvocationContextContainer icc)
+ {
+ LockContainer lc = (LockContainer) TestingUtil.extractField(lockManager, "lockContainer");
+ assert lc.getNumLocksHeld() == 0 : "Stale locks exist! NumLocksHeld is " + lc.getNumLocksHeld() + " and lock info is " + lockManager.printLockInfo();
+ assert icc.get().getKeysLocked().isEmpty() : "Stale (?) locks recorded! " + icc.get().getKeysLocked();
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/LockTestBase.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,347 +0,0 @@
-package org.jboss.starobrno.api.mvcc;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.cache.lock.IsolationLevel;
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.UnitTestCacheFactory;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.invocation.InvocationContextContainer;
-import org.jboss.starobrno.lock.LockManager;
-import org.jboss.starobrno.lock.TimeoutException;
-import org.jboss.starobrno.transaction.DummyTransactionManagerLookup;
-import org.jboss.starobrno.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.Collections;
-
-/**
- * @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
- * @since 3.0
- */
- at Test(groups = {"functional", "mvcc"})
-public abstract class LockTestBase
-{
- protected boolean repeatableRead = true;
- protected boolean lockParentForChildInsertRemove = false;
- private Log log = LogFactory.getLog(LockTestBase.class);
-
- protected class LockTestBaseTL
- {
- public Cache<String, String> cache;
- public TransactionManager tm;
- public LockManager lockManager;
- public InvocationContextContainer icc;
- }
-
- protected ThreadLocal<LockTestBaseTL> threadLocal = new ThreadLocal<LockTestBaseTL>();
-
-
- @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();
- 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);
- threadLocal.set(tl);
- }
-
- @AfterMethod
- public void tearDown()
- {
- LockTestBaseTL tl = threadLocal.get();
- log.debug("**** - STARTING TEARDOWN - ****");
- TestingUtil.killCaches(tl.cache);
- threadLocal.set(null);
- }
-
- protected void assertLocked(Object key)
- {
- LockTestBaseTL tl = threadLocal.get();
- LockAssert.assertLocked(key, tl.lockManager, tl.icc);
- }
-
- protected void assertNotLocked(Object key)
- {
- LockTestBaseTL tl = threadLocal.get();
- LockAssert.assertNotLocked(key, tl.icc);
- }
-
- protected void assertNoLocks()
- {
- LockTestBaseTL tl = threadLocal.get();
- LockAssert.assertNoLocks(tl.lockManager, tl.icc);
- }
-
- public void testLocksOnPutKeyVal() throws Exception
- {
- LockTestBaseTL tl = threadLocal.get();
- Cache<String, String> cache = tl.cache;
- TransactionManager tm = tl.tm;
- tm.begin();
- cache.put("k", "v");
- assertLocked("k");
- tm.commit();
-
- assertNoLocks();
-
- tm.begin();
- assert cache.get("k").equals("v");
- assertNotLocked("k");
- tm.commit();
-
- assertNoLocks();
-
- tm.begin();
- cache.remove("k");
- assertLocked("k");
- tm.commit();
-
- assertNoLocks();
- }
-
- public void testLocksOnPutData() throws Exception
- {
- LockTestBaseTL tl = threadLocal.get();
- Cache<String, String> cache = tl.cache;
- TransactionManager tm = tl.tm;
- tm.begin();
- cache.putAll(Collections.singletonMap("k", "v"));
- assertLocked("k");
- assert "v".equals(cache.get("k"));
- tm.commit();
-
- assertNoLocks();
-
- tm.begin();
- assert "v".equals(cache.get("k"));
- assertNoLocks();
- tm.commit();
-
- assertNoLocks();
- }
-
- public void testLocksOnEvictNode() throws Exception
- {
- LockTestBaseTL tl = threadLocal.get();
- Cache<String, String> cache = tl.cache;
- TransactionManager tm = tl.tm;
- // init some data on a node
- cache.putAll(Collections.singletonMap("k", "v"));
-
- assert "v".equals(cache.get("k"));
-
- tm.begin();
- cache.evict("k");
- assertLocked("k");
- tm.commit();
- assert !cache.containsKey("k") : "Should not exist";
- assertNoLocks();
- }
-
- public void testLocksOnRemoveNonexistentNode() throws Exception
- {
- LockTestBaseTL tl = threadLocal.get();
- Cache<String, String> cache = tl.cache;
- TransactionManager tm = tl.tm;
- assert !cache.containsKey("k") : "Should not exist";
-
- tm.begin();
- cache.remove("k");
- assertLocked("k");
- tm.commit();
- assert !cache.containsKey("k") : "Should not exist";
- assertNoLocks();
- }
-
- public void testLocksOnEvictNonexistentNode() throws Exception
- {
- LockTestBaseTL tl = threadLocal.get();
- Cache<String, String> cache = tl.cache;
- TransactionManager tm = tl.tm;
- assert !cache.containsKey("k") : "Should not exist";
-
- tm.begin();
- cache.evict("k");
- assertLocked("k");
- tm.commit();
- assert !cache.containsKey("k") : "Should not exist";
- assertNoLocks();
- }
-
- public void testLocksOnRemoveData() throws Exception
- {
- LockTestBaseTL tl = threadLocal.get();
- Cache<String, String> cache = tl.cache;
- TransactionManager tm = tl.tm;
- // init some data on a node
- cache.put("k", "v");
- cache.put("k2", "v2");
-
- assert "v".equals(cache.get("k"));
- assert "v2".equals(cache.get("k2"));
-
- // remove
- tm.begin();
- cache.clear();
- assertLocked("k");
- assertLocked("k2");
- tm.commit();
-
- assert cache.isEmpty();
- assertNoLocks();
- }
-
- public void testWriteDoesntBlockRead() throws Exception
- {
- LockTestBaseTL tl = threadLocal.get();
- Cache<String, String> cache = tl.cache;
- TransactionManager tm = tl.tm;
- cache.put("k", "v");
-
- // start a write.
- tm.begin();
- cache.put("k2", "v2");
- assertLocked("k2");
- Transaction write = tm.suspend();
-
- // now start a read and confirm that the write doesn't block it.
- tm.begin();
- assert "v".equals(cache.get("k"));
- assert null == cache.get("k2") : "Should not see uncommitted changes";
- Transaction read = tm.suspend();
-
- // commit the write
- tm.resume(write);
- tm.commit();
-
- assertNoLocks();
-
- tm.resume(read);
- if (repeatableRead)
- assert null == cache.get("k2") : "Should have repeatable read";
- else
- assert "v2".equals(cache.get("k2")) : "Read committed should see committed changes";
- tm.commit();
- assertNoLocks();
- }
-
- public void testWriteDoesntBlockReadNonexistent() throws Exception
- {
- LockTestBaseTL tl = threadLocal.get();
- Cache<String, String> cache = tl.cache;
- TransactionManager tm = tl.tm;
- // start a write.
- tm.begin();
- cache.put("k", "v");
- assertLocked("k");
- Transaction write = tm.suspend();
-
- // now start a read and confirm that the write doesn't block it.
- tm.begin();
- assert null == cache.get("k") : "Should not see uncommitted changes";
- Transaction read = tm.suspend();
-
- // commit the write
- tm.resume(write);
- tm.commit();
-
- assertNoLocks();
-
- tm.resume(read);
- if (repeatableRead)
- {
- assert null == cache.get("k") : "Should have repeatable read";
- }
- else
- {
- assert "v".equals(cache.get("k")) : "Read committed should see committed changes";
- }
- tm.commit();
- assertNoLocks();
- }
-
- public void testConcurrentWriters() throws Exception
- {
- LockTestBaseTL tl = threadLocal.get();
- Cache<String, String> cache = tl.cache;
- TransactionManager tm = tl.tm;
- tm.begin();
- cache.put("k", "v");
- Transaction t1 = tm.suspend();
-
- tm.begin();
- try
- {
- cache.put("k", "v");
- assert false : "Should fail lock acquisition";
- }
- catch (TimeoutException expected)
- {
-// expected.printStackTrace(); // for debugging
- }
- tm.commit();
- tm.resume(t1);
- tm.commit();
- assertNoLocks();
- }
-
- public void testRollbacks() throws Exception
- {
- LockTestBaseTL tl = threadLocal.get();
- Cache<String, String> cache = tl.cache;
- TransactionManager tm = tl.tm;
- cache.put("k", "v");
- tm.begin();
- assert "v".equals(cache.get("k"));
- Transaction reader = tm.suspend();
-
- tm.begin();
- cache.put("k", "v2");
- tm.rollback();
-
- tm.resume(reader);
- Object value = cache.get("k");
- assert "v".equals(value) : "Expecting 'v' but was " + value;
- tm.commit();
-
- // even after commit
- assert "v".equals(cache.get("k"));
- assertNoLocks();
- }
-
- public void testRollbacksOnNullNode() throws Exception
- {
- LockTestBaseTL tl = threadLocal.get();
- Cache<String, String> cache = tl.cache;
- TransactionManager tm = tl.tm;
- tm.begin();
- assert null == cache.get("k");
- Transaction reader = tm.suspend();
-
- tm.begin();
- cache.put("k", "v");
- assert "v".equals(cache.get("k"));
- tm.rollback();
-
- tm.resume(reader);
- assert null == cache.get("k") : "Expecting null but was " + cache.get("k");
- tm.commit();
-
- // even after commit
- assert null == cache.get("k");
- assertNoLocks();
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/LockTestBase.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,347 @@
+package org.horizon.api.mvcc;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.horizon.lock.IsolationLevel;
+import org.horizon.Cache;
+import org.horizon.UnitTestCacheFactory;
+import org.horizon.config.Configuration;
+import org.horizon.invocation.InvocationContextContainer;
+import org.horizon.lock.LockManager;
+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.Collections;
+
+/**
+ * @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
+ * @since 3.0
+ */
+ at Test(groups = {"functional", "mvcc"})
+public abstract class LockTestBase
+{
+ protected boolean repeatableRead = true;
+ protected boolean lockParentForChildInsertRemove = false;
+ private Log log = LogFactory.getLog(LockTestBase.class);
+
+ protected class LockTestBaseTL
+ {
+ public Cache<String, String> cache;
+ public TransactionManager tm;
+ public LockManager lockManager;
+ public InvocationContextContainer icc;
+ }
+
+ protected ThreadLocal<LockTestBaseTL> threadLocal = new ThreadLocal<LockTestBaseTL>();
+
+
+ @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();
+ 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);
+ threadLocal.set(tl);
+ }
+
+ @AfterMethod
+ public void tearDown()
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ log.debug("**** - STARTING TEARDOWN - ****");
+ TestingUtil.killCaches(tl.cache);
+ threadLocal.set(null);
+ }
+
+ protected void assertLocked(Object key)
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ LockAssert.assertLocked(key, tl.lockManager, tl.icc);
+ }
+
+ protected void assertNotLocked(Object key)
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ LockAssert.assertNotLocked(key, tl.icc);
+ }
+
+ protected void assertNoLocks()
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ LockAssert.assertNoLocks(tl.lockManager, tl.icc);
+ }
+
+ public void testLocksOnPutKeyVal() throws Exception
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ Cache<String, String> cache = tl.cache;
+ TransactionManager tm = tl.tm;
+ tm.begin();
+ cache.put("k", "v");
+ assertLocked("k");
+ tm.commit();
+
+ assertNoLocks();
+
+ tm.begin();
+ assert cache.get("k").equals("v");
+ assertNotLocked("k");
+ tm.commit();
+
+ assertNoLocks();
+
+ tm.begin();
+ cache.remove("k");
+ assertLocked("k");
+ tm.commit();
+
+ assertNoLocks();
+ }
+
+ public void testLocksOnPutData() throws Exception
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ Cache<String, String> cache = tl.cache;
+ TransactionManager tm = tl.tm;
+ tm.begin();
+ cache.putAll(Collections.singletonMap("k", "v"));
+ assertLocked("k");
+ assert "v".equals(cache.get("k"));
+ tm.commit();
+
+ assertNoLocks();
+
+ tm.begin();
+ assert "v".equals(cache.get("k"));
+ assertNoLocks();
+ tm.commit();
+
+ assertNoLocks();
+ }
+
+ public void testLocksOnEvictNode() throws Exception
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ Cache<String, String> cache = tl.cache;
+ TransactionManager tm = tl.tm;
+ // init some data on a node
+ cache.putAll(Collections.singletonMap("k", "v"));
+
+ assert "v".equals(cache.get("k"));
+
+ tm.begin();
+ cache.evict("k");
+ assertLocked("k");
+ tm.commit();
+ assert !cache.containsKey("k") : "Should not exist";
+ assertNoLocks();
+ }
+
+ public void testLocksOnRemoveNonexistentNode() throws Exception
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ Cache<String, String> cache = tl.cache;
+ TransactionManager tm = tl.tm;
+ assert !cache.containsKey("k") : "Should not exist";
+
+ tm.begin();
+ cache.remove("k");
+ assertLocked("k");
+ tm.commit();
+ assert !cache.containsKey("k") : "Should not exist";
+ assertNoLocks();
+ }
+
+ public void testLocksOnEvictNonexistentNode() throws Exception
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ Cache<String, String> cache = tl.cache;
+ TransactionManager tm = tl.tm;
+ assert !cache.containsKey("k") : "Should not exist";
+
+ tm.begin();
+ cache.evict("k");
+ assertLocked("k");
+ tm.commit();
+ assert !cache.containsKey("k") : "Should not exist";
+ assertNoLocks();
+ }
+
+ public void testLocksOnRemoveData() throws Exception
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ Cache<String, String> cache = tl.cache;
+ TransactionManager tm = tl.tm;
+ // init some data on a node
+ cache.put("k", "v");
+ cache.put("k2", "v2");
+
+ assert "v".equals(cache.get("k"));
+ assert "v2".equals(cache.get("k2"));
+
+ // remove
+ tm.begin();
+ cache.clear();
+ assertLocked("k");
+ assertLocked("k2");
+ tm.commit();
+
+ assert cache.isEmpty();
+ assertNoLocks();
+ }
+
+ public void testWriteDoesntBlockRead() throws Exception
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ Cache<String, String> cache = tl.cache;
+ TransactionManager tm = tl.tm;
+ cache.put("k", "v");
+
+ // start a write.
+ tm.begin();
+ cache.put("k2", "v2");
+ assertLocked("k2");
+ Transaction write = tm.suspend();
+
+ // now start a read and confirm that the write doesn't block it.
+ tm.begin();
+ assert "v".equals(cache.get("k"));
+ assert null == cache.get("k2") : "Should not see uncommitted changes";
+ Transaction read = tm.suspend();
+
+ // commit the write
+ tm.resume(write);
+ tm.commit();
+
+ assertNoLocks();
+
+ tm.resume(read);
+ if (repeatableRead)
+ assert null == cache.get("k2") : "Should have repeatable read";
+ else
+ assert "v2".equals(cache.get("k2")) : "Read committed should see committed changes";
+ tm.commit();
+ assertNoLocks();
+ }
+
+ public void testWriteDoesntBlockReadNonexistent() throws Exception
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ Cache<String, String> cache = tl.cache;
+ TransactionManager tm = tl.tm;
+ // start a write.
+ tm.begin();
+ cache.put("k", "v");
+ assertLocked("k");
+ Transaction write = tm.suspend();
+
+ // now start a read and confirm that the write doesn't block it.
+ tm.begin();
+ assert null == cache.get("k") : "Should not see uncommitted changes";
+ Transaction read = tm.suspend();
+
+ // commit the write
+ tm.resume(write);
+ tm.commit();
+
+ assertNoLocks();
+
+ tm.resume(read);
+ if (repeatableRead)
+ {
+ assert null == cache.get("k") : "Should have repeatable read";
+ }
+ else
+ {
+ assert "v".equals(cache.get("k")) : "Read committed should see committed changes";
+ }
+ tm.commit();
+ assertNoLocks();
+ }
+
+ public void testConcurrentWriters() throws Exception
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ Cache<String, String> cache = tl.cache;
+ TransactionManager tm = tl.tm;
+ tm.begin();
+ cache.put("k", "v");
+ Transaction t1 = tm.suspend();
+
+ tm.begin();
+ try
+ {
+ cache.put("k", "v");
+ assert false : "Should fail lock acquisition";
+ }
+ catch (TimeoutException expected)
+ {
+// expected.printStackTrace(); // for debugging
+ }
+ tm.commit();
+ tm.resume(t1);
+ tm.commit();
+ assertNoLocks();
+ }
+
+ public void testRollbacks() throws Exception
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ Cache<String, String> cache = tl.cache;
+ TransactionManager tm = tl.tm;
+ cache.put("k", "v");
+ tm.begin();
+ assert "v".equals(cache.get("k"));
+ Transaction reader = tm.suspend();
+
+ tm.begin();
+ cache.put("k", "v2");
+ tm.rollback();
+
+ tm.resume(reader);
+ Object value = cache.get("k");
+ assert "v".equals(value) : "Expecting 'v' but was " + value;
+ tm.commit();
+
+ // even after commit
+ assert "v".equals(cache.get("k"));
+ assertNoLocks();
+ }
+
+ public void testRollbacksOnNullNode() throws Exception
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ Cache<String, String> cache = tl.cache;
+ TransactionManager tm = tl.tm;
+ tm.begin();
+ assert null == cache.get("k");
+ Transaction reader = tm.suspend();
+
+ tm.begin();
+ cache.put("k", "v");
+ assert "v".equals(cache.get("k"));
+ tm.rollback();
+
+ tm.resume(reader);
+ assert null == cache.get("k") : "Expecting null but was " + cache.get("k");
+ tm.commit();
+
+ // even after commit
+ assert null == cache.get("k");
+ assertNoLocks();
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/PutForExternalReadTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,343 +0,0 @@
-package org.jboss.starobrno.api.mvcc;
-
-import org.easymock.EasyMock;
-import static org.easymock.EasyMock.*;
-import org.jboss.cache.CacheFactory;
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.CacheSPI;
-import org.jboss.starobrno.UnitTestCacheFactory;
-import org.jboss.starobrno.commands.ReplicableCommand;
-import org.jboss.starobrno.commands.write.PutKeyValueCommand;
-import org.jboss.starobrno.commands.write.RemoveCommand;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.factories.ComponentRegistry;
-import org.jboss.starobrno.remoting.RPCManager;
-import org.jboss.starobrno.transaction.TransactionTable;
-import org.jboss.starobrno.util.TestingUtil;
-import org.jboss.starobrno.util.internals.ReplicationListener;
-import org.jgroups.Address;
-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.Vector;
-
- at Test(groups = {"functional", "jgroups", "transaction"})
-public class PutForExternalReadTest
-{
- protected final String key = "k", value = "v", value2 = "v2";
-
- protected CacheSPI<String, String> cache1, cache2;
-
- ReplicationListener replListener1;
- ReplicationListener replListener2;
-
- protected TransactionManager tm1, tm2;
-
- protected boolean useTx;
-
-
- @BeforeMethod(alwaysRun = true)
- public void setUp()
- {
-
- CacheFactory<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("org.jboss.starobrno.transaction.DummyTransactionManagerLookup");
- cache1.getConfiguration().setSerializationExecutorPoolSize(0);//this is very important for async tests!
-
- cache1.start();
- tm1 = cache1.getConfiguration().getRuntimeConfig().getTransactionManager();
-
- cache2 = (CacheSPI<String, String>) cf.createCache(cache1.getConfiguration().clone());
-
- tm2 = cache2.getConfiguration().getRuntimeConfig().getTransactionManager();
- replListener1 = new ReplicationListener(cache1);
- replListener2 = new ReplicationListener(cache2);
-
- TestingUtil.blockUntilViewsReceived(10000, cache1, cache2);
- }
-
- @AfterMethod(alwaysRun = true)
- public void tearDown()
- {
- TestingUtil.killCaches(cache1, cache2);
- }
-
- public void testNoOpWhenKeyPresent()
- {
- replListener2.expect(PutKeyValueCommand.class);
- cache1.putForExternalRead(key, value);
- replListener2.waitForReplicationToOccur();
-
-
- assertEquals("PFER should have succeeded", value, cache1.get(key));
- assertEquals("PFER should have replicated", value, cache2.get(key));
-
- // reset
- replListener2.expect(RemoveCommand.class);
- cache1.remove(key);
- replListener2.waitForReplicationToOccur();
-
- assert cache1.isEmpty() : "Should have reset";
- assert cache2.isEmpty() : "Should have reset";
-
- replListener2.expect(PutKeyValueCommand.class);
- cache1.put(key, value);
- replListener2.waitForReplicationToOccur();
-
- // now this pfer should be a no-op
- cache1.putForExternalRead(key, value2);
-
- assertEquals("PFER should have been a no-op", value, cache1.get(key));
- assertEquals("PFER should have been a no-op", value, cache2.get(key));
- }
-
- private Vector<Address> anyAddresses()
- {
- anyObject();
- return null;
- }
-
- 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();
-
- // 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.callRemoteMethods(anyAddresses(), (ReplicableCommand) anyObject(), eq(false), anyLong(), anyBoolean())).andReturn(null);
-
- replay(rpcManager);
-
- // now try a simple replication. Since the RPCManager is a mock object it will not actually replicate anything.
- cache1.putForExternalRead(key, value);
- verify(rpcManager);
-
- // cleanup
- TestingUtil.extractComponentRegistry(cache1).registerComponent(originalRpcManager, RPCManager.class);
- cache1.remove(key);
- }
-
- public void testTxSuspension() throws Exception
- {
- // create parent node first
- replListener2.expect(PutKeyValueCommand.class);
- cache1.put(key + "0", value);
- replListener2.waitForReplicationToOccur();
-
- // start a tx and do some stuff.
- replListener2.expect(PutKeyValueCommand.class);
- tm1.begin();
- cache1.get(key + "0");
- cache1.putForExternalRead(key, value); // should have happened in a separate tx and have committed already.
- Transaction t = tm1.suspend();
-
- replListener2.waitForReplicationToOccur();
- assertEquals("PFER should have completed", value, cache1.get(key));
- assertEquals("PFER should have completed", value, cache2.get(key));
-
- tm1.resume(t);
- tm1.commit();
-
- assertEquals("parent fqn tx should have completed", value, cache1.get(key + "0"));
- assertEquals("parent fqn tx should have completed", value, cache2.get(key + "0"));
- }
-
- public void testExceptionSuppression() throws Exception
- {
- RPCManager barfingRpcManager = EasyMock.createNiceMock(RPCManager.class);
- RPCManager originalRpcManager = cache1.getConfiguration().getRuntimeConfig().getRPCManager();
- try
- {
- List<Address> memberList = originalRpcManager.getMembers();
- expect(barfingRpcManager.getMembers()).andReturn(memberList).anyTimes();
- expect(barfingRpcManager.getLocalAddress()).andReturn(originalRpcManager.getLocalAddress()).anyTimes();
- expect(barfingRpcManager.callRemoteMethods(anyAddresses(), (ReplicableCommand) anyObject(), anyBoolean(), 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();
-
- try
- {
- cache1.put(key, value);
- fail("Should have barfed");
- }
- catch (RuntimeException re)
- {
- }
-
- // clean up any indeterminate state left over
- try
- {
- cache1.remove(key);
- fail("Should have barfed");
- }
- catch (RuntimeException re)
- {
- }
-
- assertNull("Should have cleaned up", cache1.get(key));
-
- // should not barf
- cache1.putForExternalRead(key, value);
- }
- finally
- {
- TestingUtil.extractComponentRegistry(cache1).registerComponent(originalRpcManager, RPCManager.class);
- }
- }
-
- public void testBasicPropagation() throws Exception
- {
- assert !cache1.containsKey(key);
- assert !cache2.containsKey(key);
-
- replListener2.expect(PutKeyValueCommand.class);
- cache1.putForExternalRead(key, value);
- replListener2.waitForReplicationToOccur();
-
- assertEquals("PFER updated cache1", value, cache1.get(key));
- assertEquals("PFER propagated to cache2 as expected", value, cache2.get(key));
-
- // replication to cache 1 should NOT happen.
- cache2.putForExternalRead(key, value + "0");
-
- assertEquals("PFER updated cache2", value, cache2.get(key));
- assertEquals("Cache1 should be unaffected", value, cache1.get(key));
- }
-
- /**
- * Tests that setting a cacheModeLocal=true Option prevents propagation
- * of the putForExternalRead().
- *
- * @throws Exception
- */
- public void testSimpleCacheModeLocal() throws Exception
- {
- cacheModeLocalTest(false);
- }
-
- /**
- * Tests that setting a cacheModeLocal=true Option prevents propagation
- * of the putForExternalRead() when the call occurs inside a transaction.
- *
- * @throws Exception
- */
- public void testCacheModeLocalInTx() throws Exception
- {
- cacheModeLocalTest(true);
- }
-
- private TransactionTable getTransactionTable(Cache cache)
- {
- return TestingUtil.extractComponent(cache, TransactionTable.class);
- }
-
- /**
- * Tests that suspended transactions do not leak. See JBCACHE-1246.
- */
- public void testMemLeakOnSuspendedTransactions() throws Exception
- {
- replListener2.expect(PutKeyValueCommand.class);
- tm1.begin();
- cache1.putForExternalRead(key, value);
- tm1.commit();
- replListener2.waitForReplicationToOccur();
-
- TransactionTable tt1 = getTransactionTable(cache1);
- TransactionTable tt2 = getTransactionTable(cache2);
-
- assert tt1.getNumGlobalTransactions() == 0 : "Cache 1 should have no stale global TXs";
- assert tt1.getNumLocalTransactions() == 0 : "Cache 1 should have no stale local TXs";
- assert tt2.getNumGlobalTransactions() == 0 : "Cache 2 should have no stale global TXs";
- assert tt2.getNumLocalTransactions() == 0 : "Cache 2 should have no stale local TXs";
-
- System.out.println("PutForExternalReadTest.testMemLeakOnSuspendedTransactions");
- //do not expectWithTx a PFER replication, as the node already exists so this is a no-op
- replListener2.expectWithTx(PutKeyValueCommand.class);
- tm1.begin();
- cache1.putForExternalRead(key, value);
- cache1.put(key, value);
- tm1.commit();
- replListener2.waitForReplicationToOccur();
-
- assert tt1.getNumGlobalTransactions() == 0 : "Cache 1 should have no stale global TXs";
- assert tt1.getNumLocalTransactions() == 0 : "Cache 1 should have no stale local TXs";
- assert tt2.getNumGlobalTransactions() == 0 : "Cache 2 should have no stale global TXs";
- assert tt2.getNumLocalTransactions() == 0 : "Cache 2 should have no stale local TXs";
-
- replListener2.expectWithTx(PutKeyValueCommand.class);
- tm1.begin();
- cache1.put(key, value);
- cache1.putForExternalRead(key, value);
- tm1.commit();
- replListener2.waitForReplicationToOccur();
-
- assert tt1.getNumGlobalTransactions() == 0 : "Cache 1 should have no stale global TXs";
- assert tt1.getNumLocalTransactions() == 0 : "Cache 1 should have no stale local TXs";
- assert tt2.getNumGlobalTransactions() == 0 : "Cache 2 should have no stale global TXs";
- assert tt2.getNumLocalTransactions() == 0 : "Cache 2 should have no stale local TXs";
-
- //do not expectWithTx a PFER replication, as the node already exists so this is a no-op
- replListener2.expectWithTx(PutKeyValueCommand.class, PutKeyValueCommand.class);
- tm1.begin();
- cache1.put(key, value);
- cache1.putForExternalRead(key, value);
- cache1.put(key, value);
- tm1.commit();
- replListener2.waitForReplicationToOccur();
-
- assert tt1.getNumGlobalTransactions() == 0 : "Cache 1 should have no stale global TXs";
- assert tt1.getNumLocalTransactions() == 0 : "Cache 1 should have no stale local TXs";
- assert tt2.getNumGlobalTransactions() == 0 : "Cache 2 should have no stale global TXs";
- assert tt2.getNumLocalTransactions() == 0 : "Cache 2 should have no stale local TXs";
- }
-
- /**
- * Tests that setting a cacheModeLocal=true Option prevents propagation
- * of the putForExternalRead().
- *
- * @throws Exception
- */
- private void cacheModeLocalTest(boolean transactional) throws Exception
- {
- RPCManager rpcManager = EasyMock.createMock(RPCManager.class);
- RPCManager originalRpcManager = cache1.getConfiguration().getRuntimeConfig().getRPCManager();
-
- // inject a mock RPC manager so that we can test whether calls made are sync or async.
- cache1.getConfiguration().getRuntimeConfig().setRPCManager(rpcManager);
-
- // specify that we expectWithTx nothing will be called on the mock Rpc Manager.
- replay(rpcManager);
-
- // now try a simple replication. Since the RPCManager is a mock object it will not actually replicate anything.
- if (transactional)
- tm1.begin();
-
- cache1.getInvocationContext().getOptionOverrides().setCacheModeLocal(true);
- cache1.putForExternalRead(key, value);
-
- if (transactional)
- tm1.commit();
-
- verify(rpcManager);
- // cleanup
- cache1.getConfiguration().getRuntimeConfig().setRPCManager(originalRpcManager);
- cache1.remove(key);
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/PutForExternalReadTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,343 @@
+package org.horizon.api.mvcc;
+
+import org.easymock.EasyMock;
+import static org.easymock.EasyMock.*;
+import org.horizon.Cache;
+import org.horizon.CacheSPI;
+import org.horizon.UnitTestCacheFactory;
+import org.horizon.commands.ReplicableCommand;
+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.remoting.RPCManager;
+import org.horizon.transaction.TransactionTable;
+import org.horizon.transaction.DummyTransactionManagerLookup;
+import org.horizon.util.TestingUtil;
+import org.horizon.util.internals.ReplicationListener;
+import org.jgroups.Address;
+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.Vector;
+
+ at Test(groups = {"functional", "jgroups", "transaction"})
+public class PutForExternalReadTest
+{
+ protected final String key = "k", value = "v", value2 = "v2";
+
+ 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());
+ cache1.getConfiguration().setSerializationExecutorPoolSize(0);//this is very important for async tests!
+
+ cache1.start();
+ tm1 = cache1.getConfiguration().getRuntimeConfig().getTransactionManager();
+
+ cache2 = (CacheSPI<String, String>) cf.createCache(cache1.getConfiguration().clone());
+
+ tm2 = cache2.getConfiguration().getRuntimeConfig().getTransactionManager();
+ replListener1 = new ReplicationListener(cache1);
+ replListener2 = new ReplicationListener(cache2);
+
+ TestingUtil.blockUntilViewsReceived(10000, cache1, cache2);
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown()
+ {
+ TestingUtil.killCaches(cache1, cache2);
+ }
+
+ public void testNoOpWhenKeyPresent()
+ {
+ replListener2.expect(PutKeyValueCommand.class);
+ cache1.putForExternalRead(key, value);
+ replListener2.waitForReplicationToOccur();
+
+
+ assertEquals("PFER should have succeeded", value, cache1.get(key));
+ assertEquals("PFER should have replicated", value, cache2.get(key));
+
+ // reset
+ replListener2.expect(RemoveCommand.class);
+ cache1.remove(key);
+ replListener2.waitForReplicationToOccur();
+
+ assert cache1.isEmpty() : "Should have reset";
+ assert cache2.isEmpty() : "Should have reset";
+
+ replListener2.expect(PutKeyValueCommand.class);
+ cache1.put(key, value);
+ replListener2.waitForReplicationToOccur();
+
+ // now this pfer should be a no-op
+ cache1.putForExternalRead(key, value2);
+
+ assertEquals("PFER should have been a no-op", value, cache1.get(key));
+ assertEquals("PFER should have been a no-op", value, cache2.get(key));
+ }
+
+ private Vector<Address> anyAddresses()
+ {
+ anyObject();
+ return null;
+ }
+
+ 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();
+
+ // 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.callRemoteMethods(anyAddresses(), (ReplicableCommand) anyObject(), eq(false), anyLong(), anyBoolean())).andReturn(null);
+
+ replay(rpcManager);
+
+ // now try a simple replication. Since the RPCManager is a mock object it will not actually replicate anything.
+ cache1.putForExternalRead(key, value);
+ verify(rpcManager);
+
+ // cleanup
+ TestingUtil.extractComponentRegistry(cache1).registerComponent(originalRpcManager, RPCManager.class);
+ cache1.remove(key);
+ }
+
+ public void testTxSuspension() throws Exception
+ {
+ // create parent node first
+ replListener2.expect(PutKeyValueCommand.class);
+ cache1.put(key + "0", value);
+ replListener2.waitForReplicationToOccur();
+
+ // start a tx and do some stuff.
+ replListener2.expect(PutKeyValueCommand.class);
+ tm1.begin();
+ cache1.get(key + "0");
+ cache1.putForExternalRead(key, value); // should have happened in a separate tx and have committed already.
+ Transaction t = tm1.suspend();
+
+ replListener2.waitForReplicationToOccur();
+ assertEquals("PFER should have completed", value, cache1.get(key));
+ assertEquals("PFER should have completed", value, cache2.get(key));
+
+ tm1.resume(t);
+ tm1.commit();
+
+ assertEquals("parent fqn tx should have completed", value, cache1.get(key + "0"));
+ assertEquals("parent fqn tx should have completed", value, cache2.get(key + "0"));
+ }
+
+ public void testExceptionSuppression() throws Exception
+ {
+ RPCManager barfingRpcManager = EasyMock.createNiceMock(RPCManager.class);
+ RPCManager originalRpcManager = cache1.getConfiguration().getRuntimeConfig().getRPCManager();
+ try
+ {
+ List<Address> memberList = originalRpcManager.getMembers();
+ expect(barfingRpcManager.getMembers()).andReturn(memberList).anyTimes();
+ expect(barfingRpcManager.getLocalAddress()).andReturn(originalRpcManager.getLocalAddress()).anyTimes();
+ expect(barfingRpcManager.callRemoteMethods(anyAddresses(), (ReplicableCommand) anyObject(), anyBoolean(), 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();
+
+ try
+ {
+ cache1.put(key, value);
+ fail("Should have barfed");
+ }
+ catch (RuntimeException re)
+ {
+ }
+
+ // clean up any indeterminate state left over
+ try
+ {
+ cache1.remove(key);
+ fail("Should have barfed");
+ }
+ catch (RuntimeException re)
+ {
+ }
+
+ assertNull("Should have cleaned up", cache1.get(key));
+
+ // should not barf
+ cache1.putForExternalRead(key, value);
+ }
+ finally
+ {
+ TestingUtil.extractComponentRegistry(cache1).registerComponent(originalRpcManager, RPCManager.class);
+ }
+ }
+
+ public void testBasicPropagation() throws Exception
+ {
+ assert !cache1.containsKey(key);
+ assert !cache2.containsKey(key);
+
+ replListener2.expect(PutKeyValueCommand.class);
+ cache1.putForExternalRead(key, value);
+ replListener2.waitForReplicationToOccur();
+
+ assertEquals("PFER updated cache1", value, cache1.get(key));
+ assertEquals("PFER propagated to cache2 as expected", value, cache2.get(key));
+
+ // replication to cache 1 should NOT happen.
+ cache2.putForExternalRead(key, value + "0");
+
+ assertEquals("PFER updated cache2", value, cache2.get(key));
+ assertEquals("Cache1 should be unaffected", value, cache1.get(key));
+ }
+
+ /**
+ * Tests that setting a cacheModeLocal=true Option prevents propagation
+ * of the putForExternalRead().
+ *
+ * @throws Exception
+ */
+ public void testSimpleCacheModeLocal() throws Exception
+ {
+ cacheModeLocalTest(false);
+ }
+
+ /**
+ * Tests that setting a cacheModeLocal=true Option prevents propagation
+ * of the putForExternalRead() when the call occurs inside a transaction.
+ *
+ * @throws Exception
+ */
+ public void testCacheModeLocalInTx() throws Exception
+ {
+ cacheModeLocalTest(true);
+ }
+
+ private TransactionTable getTransactionTable(Cache cache)
+ {
+ return TestingUtil.extractComponent(cache, TransactionTable.class);
+ }
+
+ /**
+ * Tests that suspended transactions do not leak. See JBCACHE-1246.
+ */
+ public void testMemLeakOnSuspendedTransactions() throws Exception
+ {
+ replListener2.expect(PutKeyValueCommand.class);
+ tm1.begin();
+ cache1.putForExternalRead(key, value);
+ tm1.commit();
+ replListener2.waitForReplicationToOccur();
+
+ TransactionTable tt1 = getTransactionTable(cache1);
+ TransactionTable tt2 = getTransactionTable(cache2);
+
+ assert tt1.getNumGlobalTransactions() == 0 : "Cache 1 should have no stale global TXs";
+ assert tt1.getNumLocalTransactions() == 0 : "Cache 1 should have no stale local TXs";
+ assert tt2.getNumGlobalTransactions() == 0 : "Cache 2 should have no stale global TXs";
+ assert tt2.getNumLocalTransactions() == 0 : "Cache 2 should have no stale local TXs";
+
+ System.out.println("PutForExternalReadTest.testMemLeakOnSuspendedTransactions");
+ //do not expectWithTx a PFER replication, as the node already exists so this is a no-op
+ replListener2.expectWithTx(PutKeyValueCommand.class);
+ tm1.begin();
+ cache1.putForExternalRead(key, value);
+ cache1.put(key, value);
+ tm1.commit();
+ replListener2.waitForReplicationToOccur();
+
+ assert tt1.getNumGlobalTransactions() == 0 : "Cache 1 should have no stale global TXs";
+ assert tt1.getNumLocalTransactions() == 0 : "Cache 1 should have no stale local TXs";
+ assert tt2.getNumGlobalTransactions() == 0 : "Cache 2 should have no stale global TXs";
+ assert tt2.getNumLocalTransactions() == 0 : "Cache 2 should have no stale local TXs";
+
+ replListener2.expectWithTx(PutKeyValueCommand.class);
+ tm1.begin();
+ cache1.put(key, value);
+ cache1.putForExternalRead(key, value);
+ tm1.commit();
+ replListener2.waitForReplicationToOccur();
+
+ assert tt1.getNumGlobalTransactions() == 0 : "Cache 1 should have no stale global TXs";
+ assert tt1.getNumLocalTransactions() == 0 : "Cache 1 should have no stale local TXs";
+ assert tt2.getNumGlobalTransactions() == 0 : "Cache 2 should have no stale global TXs";
+ assert tt2.getNumLocalTransactions() == 0 : "Cache 2 should have no stale local TXs";
+
+ //do not expectWithTx a PFER replication, as the node already exists so this is a no-op
+ replListener2.expectWithTx(PutKeyValueCommand.class, PutKeyValueCommand.class);
+ tm1.begin();
+ cache1.put(key, value);
+ cache1.putForExternalRead(key, value);
+ cache1.put(key, value);
+ tm1.commit();
+ replListener2.waitForReplicationToOccur();
+
+ assert tt1.getNumGlobalTransactions() == 0 : "Cache 1 should have no stale global TXs";
+ assert tt1.getNumLocalTransactions() == 0 : "Cache 1 should have no stale local TXs";
+ assert tt2.getNumGlobalTransactions() == 0 : "Cache 2 should have no stale global TXs";
+ assert tt2.getNumLocalTransactions() == 0 : "Cache 2 should have no stale local TXs";
+ }
+
+ /**
+ * Tests that setting a cacheModeLocal=true Option prevents propagation
+ * of the putForExternalRead().
+ *
+ * @throws Exception
+ */
+ private void cacheModeLocalTest(boolean transactional) throws Exception
+ {
+ RPCManager rpcManager = EasyMock.createMock(RPCManager.class);
+ RPCManager originalRpcManager = cache1.getConfiguration().getRuntimeConfig().getRPCManager();
+
+ // inject a mock RPC manager so that we can test whether calls made are sync or async.
+ cache1.getConfiguration().getRuntimeConfig().setRPCManager(rpcManager);
+
+ // specify that we expectWithTx nothing will be called on the mock Rpc Manager.
+ replay(rpcManager);
+
+ // now try a simple replication. Since the RPCManager is a mock object it will not actually replicate anything.
+ if (transactional)
+ tm1.begin();
+
+ cache1.getInvocationContext().getOptionOverrides().setCacheModeLocal(true);
+ cache1.putForExternalRead(key, value);
+
+ if (transactional)
+ tm1.commit();
+
+ verify(rpcManager);
+ // cleanup
+ cache1.getConfiguration().getRuntimeConfig().setRPCManager(originalRpcManager);
+ cache1.remove(key);
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/CacheAPIMVCCTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/read_committed/CacheAPIMVCCTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/CacheAPIMVCCTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,18 +0,0 @@
-package org.jboss.starobrno.api.mvcc.read_committed;
-
-import org.jboss.cache.lock.IsolationLevel;
-import org.jboss.starobrno.api.CacheAPITest;
-import org.testng.annotations.Test;
-
-/**
- * MVCC version of {@link org.jboss.cache.api.CacheLoaderTest}
- */
- at Test(groups = {"functional", "mvcc"})
-public class CacheAPIMVCCTest extends CacheAPITest
-{
- @Override
- protected IsolationLevel getIsolationLevel()
- {
- return IsolationLevel.READ_COMMITTED;
- }
-}
\ No newline at end of file
Copied: core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/CacheAPIMVCCTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/read_committed/CacheAPIMVCCTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/CacheAPIMVCCTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/CacheAPIMVCCTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,15 @@
+package org.horizon.api.mvcc.read_committed;
+
+import org.horizon.lock.IsolationLevel;
+import org.horizon.api.CacheAPITest;
+import org.testng.annotations.Test;
+
+ at Test(groups = "functional")
+public class CacheAPIMVCCTest extends CacheAPITest
+{
+ @Override
+ protected IsolationLevel getIsolationLevel()
+ {
+ return IsolationLevel.READ_COMMITTED;
+ }
+}
\ No newline at end of file
Deleted: core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/ReadCommittedLockTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/read_committed/ReadCommittedLockTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/ReadCommittedLockTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,74 +0,0 @@
-package org.jboss.starobrno.api.mvcc.read_committed;
-
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.api.mvcc.LockTestBase;
-import org.testng.annotations.Test;
-
-import javax.transaction.Transaction;
-
- at Test(groups = {"functional", "mvcc"})
-public class ReadCommittedLockTest extends LockTestBase
-{
- public ReadCommittedLockTest()
- {
- repeatableRead = false;
- }
-
- public void testVisibilityOfCommittedDataPut() throws Exception
- {
- Cache c = threadLocal.get().cache;
- c.put("k", "v");
-
- assert "v".equals(c.get("k"));
-
- // start a tx and read K
- threadLocal.get().tm.begin();
- assert "v".equals(c.get("k"));
- assert "v".equals(c.get("k"));
- Transaction reader = threadLocal.get().tm.suspend();
-
- threadLocal.get().tm.begin();
- c.put("k", "v2");
- Transaction writer = threadLocal.get().tm.suspend();
-
- threadLocal.get().tm.resume(reader);
- assert "v".equals(c.get("k")) : "Should not read uncommitted data";
- reader = threadLocal.get().tm.suspend();
-
- threadLocal.get().tm.resume(writer);
- threadLocal.get().tm.commit();
-
- threadLocal.get().tm.resume(reader);
- assert "v2".equals(c.get("k")) : "Should read committed data";
- threadLocal.get().tm.commit();
- }
-
- public void testVisibilityOfCommittedDataReplace() throws Exception
- {
- Cache c = threadLocal.get().cache;
- c.put("k", "v");
-
- assert "v".equals(c.get("k"));
-
- // start a tx and read K
- threadLocal.get().tm.begin();
- assert "v".equals(c.get("k"));
- assert "v".equals(c.get("k"));
- Transaction reader = threadLocal.get().tm.suspend();
-
- threadLocal.get().tm.begin();
- c.replace("k", "v2");
- Transaction writer = threadLocal.get().tm.suspend();
-
- threadLocal.get().tm.resume(reader);
- assert "v".equals(c.get("k")) : "Should not read uncommitted data";
- reader = threadLocal.get().tm.suspend();
-
- threadLocal.get().tm.resume(writer);
- threadLocal.get().tm.commit();
-
- threadLocal.get().tm.resume(reader);
- assert "v2".equals(c.get("k")) : "Should read committed data";
- threadLocal.get().tm.commit();
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/ReadCommittedLockTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/read_committed/ReadCommittedLockTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/ReadCommittedLockTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/ReadCommittedLockTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,74 @@
+package org.horizon.api.mvcc.read_committed;
+
+import org.horizon.Cache;
+import org.horizon.api.mvcc.LockTestBase;
+import org.testng.annotations.Test;
+
+import javax.transaction.Transaction;
+
+ at Test(groups = {"functional", "mvcc"})
+public class ReadCommittedLockTest extends LockTestBase
+{
+ public ReadCommittedLockTest()
+ {
+ repeatableRead = false;
+ }
+
+ public void testVisibilityOfCommittedDataPut() throws Exception
+ {
+ Cache c = threadLocal.get().cache;
+ c.put("k", "v");
+
+ assert "v".equals(c.get("k"));
+
+ // start a tx and read K
+ threadLocal.get().tm.begin();
+ assert "v".equals(c.get("k"));
+ assert "v".equals(c.get("k"));
+ Transaction reader = threadLocal.get().tm.suspend();
+
+ threadLocal.get().tm.begin();
+ c.put("k", "v2");
+ Transaction writer = threadLocal.get().tm.suspend();
+
+ threadLocal.get().tm.resume(reader);
+ assert "v".equals(c.get("k")) : "Should not read uncommitted data";
+ reader = threadLocal.get().tm.suspend();
+
+ threadLocal.get().tm.resume(writer);
+ threadLocal.get().tm.commit();
+
+ threadLocal.get().tm.resume(reader);
+ assert "v2".equals(c.get("k")) : "Should read committed data";
+ threadLocal.get().tm.commit();
+ }
+
+ public void testVisibilityOfCommittedDataReplace() throws Exception
+ {
+ Cache c = threadLocal.get().cache;
+ c.put("k", "v");
+
+ assert "v".equals(c.get("k"));
+
+ // start a tx and read K
+ threadLocal.get().tm.begin();
+ assert "v".equals(c.get("k"));
+ assert "v".equals(c.get("k"));
+ Transaction reader = threadLocal.get().tm.suspend();
+
+ threadLocal.get().tm.begin();
+ c.replace("k", "v2");
+ Transaction writer = threadLocal.get().tm.suspend();
+
+ threadLocal.get().tm.resume(reader);
+ assert "v".equals(c.get("k")) : "Should not read uncommitted data";
+ reader = threadLocal.get().tm.suspend();
+
+ threadLocal.get().tm.resume(writer);
+ threadLocal.get().tm.commit();
+
+ threadLocal.get().tm.resume(reader);
+ assert "v2".equals(c.get("k")) : "Should read committed data";
+ threadLocal.get().tm.commit();
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/CacheAPIMVCCTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/CacheAPIMVCCTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/CacheAPIMVCCTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,18 +0,0 @@
-package org.jboss.starobrno.api.mvcc.repeatable_read;
-
-import org.jboss.cache.lock.IsolationLevel;
-import org.jboss.starobrno.api.CacheAPITest;
-import org.testng.annotations.Test;
-
-/**
- * MVCC version of {@link org.jboss.cache.api.CacheLoaderTest}
- */
- at Test(groups = {"functional", "mvcc"})
-public class CacheAPIMVCCTest extends CacheAPITest
-{
- @Override
- protected IsolationLevel getIsolationLevel()
- {
- return IsolationLevel.READ_COMMITTED;
- }
-}
\ No newline at end of file
Copied: core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/CacheAPIMVCCTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/CacheAPIMVCCTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/CacheAPIMVCCTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/CacheAPIMVCCTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,15 @@
+package org.horizon.api.mvcc.repeatable_read;
+
+import org.horizon.lock.IsolationLevel;
+import org.horizon.api.CacheAPITest;
+import org.testng.annotations.Test;
+
+ at Test(groups = "functional")
+public class CacheAPIMVCCTest extends CacheAPITest
+{
+ @Override
+ protected IsolationLevel getIsolationLevel()
+ {
+ return IsolationLevel.REPEATABLE_READ;
+ }
+}
\ No newline at end of file
Deleted: core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/RepeatableReadLockTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/RepeatableReadLockTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/RepeatableReadLockTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,103 +0,0 @@
-package org.jboss.starobrno.api.mvcc.repeatable_read;
-
-import org.jboss.starobrno.api.mvcc.LockTestBase;
-import org.testng.annotations.Test;
-
-import javax.transaction.Transaction;
-import javax.transaction.TransactionManager;
-import org.jboss.starobrno.Cache;
-
- at Test(groups = {"functional", "mvcc"})
-public class RepeatableReadLockTest extends LockTestBase
-{
- public RepeatableReadLockTest()
- {
- repeatableRead = true;
- }
-
- public void testRepeatableReadWithRemove() throws Exception
- {
- LockTestBaseTL tl = threadLocal.get();
- Cache<String, String> cache = tl.cache;
- TransactionManager tm = tl.tm;
- cache.put("k", "v");
-
- tm.begin();
- assert cache.get("k") != null;
- Transaction reader = tm.suspend();
-
- tm.begin();
- assert cache.remove("k") != null;
- assert cache.get("k") == null;
- tm.commit();
-
- assert cache.get("k") == null;
-
- tm.resume(reader);
- assert cache.get("k") != null;
- assert "v".equals(cache.get("k"));
- tm.commit();
-
- assert cache.get("k") == null;
- assertNoLocks();
- }
-
- public void testRepeatableReadWithEvict() throws Exception
- {
- LockTestBaseTL tl = threadLocal.get();
- Cache<String, String> cache = tl.cache;
- TransactionManager tm = tl.tm;
-
- cache.put("k", "v");
-
- tm.begin();
- assert cache.get("k") != null;
- Transaction reader = tm.suspend();
-
- tm.begin();
- cache.evict("k");
- assert cache.get("k") == null;
- tm.commit();
-
- assert cache.get("k") == null;
-
- tm.resume(reader);
- assert cache.get("k") != null;
- assert "v".equals(cache.get("k"));
- tm.commit();
-
- assert cache.get("k") == null;
- assertNoLocks();
- }
-
- public void testRepeatableReadWithNull() throws Exception
- {
- LockTestBaseTL tl = threadLocal.get();
- Cache<String, String> cache = tl.cache;
- TransactionManager tm = tl.tm;
-
- assert cache.get("k") == null;
-
- tm.begin();
- assert cache.get("k") == null;
- Transaction reader = tm.suspend();
-
- tm.begin();
- cache.put("k", "v");
- assert cache.get("k") != null;
- assert "v".equals(cache.get("k"));
- tm.commit();
-
- assert cache.get("k") != null;
- assert "v".equals(cache.get("k"));
-
- tm.resume(reader);
- Object o = cache.get("k");
- assert o == null : "found value " + o;
- tm.commit();
-
- assert cache.get("k") != null;
- assert "v".equals(cache.get("k"));
- assertNoLocks();
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/RepeatableReadLockTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/RepeatableReadLockTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/RepeatableReadLockTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/RepeatableReadLockTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,103 @@
+package org.horizon.api.mvcc.repeatable_read;
+
+import org.horizon.api.mvcc.LockTestBase;
+import org.testng.annotations.Test;
+
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
+import org.horizon.Cache;
+
+ at Test(groups = {"functional", "mvcc"})
+public class RepeatableReadLockTest extends LockTestBase
+{
+ public RepeatableReadLockTest()
+ {
+ repeatableRead = true;
+ }
+
+ public void testRepeatableReadWithRemove() throws Exception
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ Cache<String, String> cache = tl.cache;
+ TransactionManager tm = tl.tm;
+ cache.put("k", "v");
+
+ tm.begin();
+ assert cache.get("k") != null;
+ Transaction reader = tm.suspend();
+
+ tm.begin();
+ assert cache.remove("k") != null;
+ assert cache.get("k") == null;
+ tm.commit();
+
+ assert cache.get("k") == null;
+
+ tm.resume(reader);
+ assert cache.get("k") != null;
+ assert "v".equals(cache.get("k"));
+ tm.commit();
+
+ assert cache.get("k") == null;
+ assertNoLocks();
+ }
+
+ public void testRepeatableReadWithEvict() throws Exception
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ Cache<String, String> cache = tl.cache;
+ TransactionManager tm = tl.tm;
+
+ cache.put("k", "v");
+
+ tm.begin();
+ assert cache.get("k") != null;
+ Transaction reader = tm.suspend();
+
+ tm.begin();
+ cache.evict("k");
+ assert cache.get("k") == null;
+ tm.commit();
+
+ assert cache.get("k") == null;
+
+ tm.resume(reader);
+ assert cache.get("k") != null;
+ assert "v".equals(cache.get("k"));
+ tm.commit();
+
+ assert cache.get("k") == null;
+ assertNoLocks();
+ }
+
+ public void testRepeatableReadWithNull() throws Exception
+ {
+ LockTestBaseTL tl = threadLocal.get();
+ Cache<String, String> cache = tl.cache;
+ TransactionManager tm = tl.tm;
+
+ assert cache.get("k") == null;
+
+ tm.begin();
+ assert cache.get("k") == null;
+ Transaction reader = tm.suspend();
+
+ tm.begin();
+ cache.put("k", "v");
+ assert cache.get("k") != null;
+ assert "v".equals(cache.get("k"));
+ tm.commit();
+
+ assert cache.get("k") != null;
+ assert "v".equals(cache.get("k"));
+
+ tm.resume(reader);
+ Object o = cache.get("k");
+ assert o == null : "found value " + o;
+ tm.commit();
+
+ assert cache.get("k") != null;
+ assert "v".equals(cache.get("k"));
+ assertNoLocks();
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/WriteSkewTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,191 +0,0 @@
-package org.jboss.starobrno.api.mvcc.repeatable_read;
-
-import org.jboss.cache.lock.IsolationLevel;
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.UnitTestCacheFactory;
-import org.jboss.starobrno.api.mvcc.LockAssert;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.invocation.InvocationContextContainer;
-import org.jboss.starobrno.lock.LockManager;
-import org.jboss.starobrno.transaction.DummyTransactionManagerLookup;
-import org.jboss.starobrno.util.TestingUtil;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import javax.transaction.SystemException;
-import javax.transaction.TransactionManager;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-
- at 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;
-
- @BeforeMethod
- 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
- }
-
- @AfterMethod
- public void tearDown()
- {
- TestingUtil.killCaches(cache);
- }
-
- private void postStart()
- {
- lockManager = TestingUtil.extractComponentRegistry(cache).getComponent(LockManager.class);
- icc = TestingUtil.extractComponentRegistry(cache).getComponent(InvocationContextContainer.class);
- tm = TestingUtil.extractComponentRegistry(cache).getComponent(TransactionManager.class);
- }
-
- protected void assertNoLocks()
- {
- LockAssert.assertNoLocks(lockManager, icc);
- }
-
- public void testDontCheckWriteSkew() throws Exception
- {
- cache.getConfiguration().setWriteSkewCheck(false);
- cache.start();
- postStart();
- doTest(true);
- }
-
- public void testCheckWriteSkew() throws Exception
- {
- cache.getConfiguration().setWriteSkewCheck(true);
- cache.start();
- 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);
-
- 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.
- }
- }
- }
- finally
- {
- if (!didCoundDown) threadSignal.countDown();
- }
- }
- };
-
- w1.start();
- w2.start();
-
- threadSignal.await();
- // now. both txs have read.
- // let tx1 start writing
- w1Signal.countDown();
- w1.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!";
- }
-
- assertNoLocks();
- }
- }
-
- private void throwExceptions(Collection<Exception>... exceptions) throws Exception
- {
- for (Collection<Exception> ce : exceptions)
- {
- for (Exception e : ce) throw e;
- }
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/WriteSkewTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,191 @@
+package org.horizon.api.mvcc.repeatable_read;
+
+import org.horizon.lock.IsolationLevel;
+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.LockManager;
+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.SystemException;
+import javax.transaction.TransactionManager;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+
+ at 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;
+
+ @BeforeMethod
+ 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
+ }
+
+ @AfterMethod
+ public void tearDown()
+ {
+ TestingUtil.killCaches(cache);
+ }
+
+ private void postStart()
+ {
+ lockManager = TestingUtil.extractComponentRegistry(cache).getComponent(LockManager.class);
+ icc = TestingUtil.extractComponentRegistry(cache).getComponent(InvocationContextContainer.class);
+ tm = TestingUtil.extractComponentRegistry(cache).getComponent(TransactionManager.class);
+ }
+
+ protected void assertNoLocks()
+ {
+ LockAssert.assertNoLocks(lockManager, icc);
+ }
+
+ public void testDontCheckWriteSkew() throws Exception
+ {
+ cache.getConfiguration().setWriteSkewCheck(false);
+ cache.start();
+ postStart();
+ doTest(true);
+ }
+
+ public void testCheckWriteSkew() throws Exception
+ {
+ cache.getConfiguration().setWriteSkewCheck(true);
+ cache.start();
+ 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);
+
+ 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.
+ }
+ }
+ }
+ finally
+ {
+ if (!didCoundDown) threadSignal.countDown();
+ }
+ }
+ };
+
+ w1.start();
+ w2.start();
+
+ threadSignal.await();
+ // now. both txs have read.
+ // let tx1 start writing
+ w1Signal.countDown();
+ w1.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!";
+ }
+
+ assertNoLocks();
+ }
+ }
+
+ private void throwExceptions(Collection<Exception>... exceptions) throws Exception
+ {
+ for (Collection<Exception> ce : exceptions)
+ {
+ for (Exception e : ce) throw e;
+ }
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/NodeAPITest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,398 +0,0 @@
-package org.jboss.starobrno.api.tree;
-
-import org.jboss.starobrno.CacheSPI;
-import org.jboss.starobrno.UnitTestCacheFactory;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.transaction.DummyTransactionManager;
-import org.jboss.starobrno.transaction.DummyTransactionManagerLookup;
-import org.jboss.starobrno.tree.Fqn;
-import org.jboss.starobrno.tree.Node;
-import org.jboss.starobrno.tree.TreeCache;
-import org.jboss.starobrno.tree.TreeCacheImpl;
-import org.jboss.starobrno.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.TransactionManager;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Tests {@link org.jboss.cache.Node}-centric operations
- *
- * @author <a href="mailto:manik AT jboss DOT org">Manik Surtani</a>
- * @since 2.0.0
- */
- at Test(groups = {"functional", "pessimistic"})
-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;
-
- @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();
- }
-
- @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");
-
- assertEquals("value", nodeA.get("key"));
- }
-
- 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);
- nodeA.put("key", "value");
-
- assertEquals("value", nodeA.get("key"));
- tm.commit();
- }
-
- public void testOverwritingDataTx() throws Exception
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- Node<Object, Object> nodeA = rootNode.addChild(A);
- nodeA.put("key", "value");
- assertEquals("value", nodeA.get("key"));
- tm.begin();
- rootNode.removeChild(A);
- cache.put(A, "k2", "v2");
- tm.commit();
- assertNull(nodeA.get("key"));
- assertEquals("v2", nodeA.get("k2"));
- }
-
-
- /**
- * 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);
- Node<Object, Object> nodeB = nodeA.addChild(B);
- Node<Object, Object> nodeC = nodeA.addChild(C);
- Node<Object, Object> nodeD = rootNode.addChild(D);
-
- assertEquals(rootNode, nodeA.getParent());
- assertEquals(nodeA, nodeB.getParent());
- assertEquals(nodeA, nodeC.getParent());
- assertEquals(rootNode, nodeD.getParent());
-
- assertTrue(rootNode.hasChild(A));
- assertFalse(rootNode.hasChild(B));
- assertFalse(rootNode.hasChild(C));
- assertTrue(rootNode.hasChild(D));
-
- assertTrue(nodeA.hasChild(B));
- assertTrue(nodeA.hasChild(C));
-
- assertEquals(nodeA, rootNode.getChild(A));
- assertEquals(nodeD, rootNode.getChild(D));
- assertEquals(nodeB, nodeA.getChild(B));
- assertEquals(nodeC, nodeA.getChild(C));
-
- assertTrue(nodeA.getChildren().contains(nodeB));
- assertTrue(nodeA.getChildren().contains(nodeC));
- assertEquals(2, nodeA.getChildren().size());
-
- assertTrue(rootNode.getChildren().contains(nodeA));
- assertTrue(rootNode.getChildren().contains(nodeD));
- assertEquals(2, rootNode.getChildren().size());
-
- assertEquals(true, rootNode.removeChild(A));
- assertFalse(rootNode.getChildren().contains(nodeA));
- assertTrue(rootNode.getChildren().contains(nodeD));
- assertEquals(1, rootNode.getChildren().size());
-
- assertEquals("double remove", false, rootNode.removeChild(A));
- assertEquals("double remove", false, rootNode.removeChild(A.getLastElement()));
- }
-
-
- public void testImmutabilityOfData()
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- rootNode.put("key", "value");
- Map<Object, Object> m = rootNode.getData();
- try
- {
- m.put("x", "y");
- fail("Map should be immutable!!");
- }
- catch (Exception e)
- {
- // expected
- }
-
- try
- {
- rootNode.getKeys().add(new Object());
- fail("Key set should be immutable");
- }
- catch (Exception e)
- {
- // expected
- }
- }
-
- public void testDefensiveCopyOfData()
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- rootNode.put("key", "value");
- Map<Object, Object> data = rootNode.getData();
- Set<Object> keys = rootNode.getKeys();
-
- assert keys.size() == 1;
- assert keys.contains("key");
-
- assert data.size() == 1;
- assert data.containsKey("key");
-
- // now change stuff.
-
- rootNode.put("key2", "value2");
-
- // assert that the collections we initially got have not changed.
- assert keys.size() == 1;
- assert keys.contains("key");
-
- assert data.size() == 1;
- assert data.containsKey("key");
- }
-
- public void testDefensiveCopyOfChildren()
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- Fqn childFqn = Fqn.fromString("/child");
- rootNode.addChild(childFqn).put("k", "v");
- Set<Node<Object, Object>> children = rootNode.getChildren();
- Set<Object> childrenNames = rootNode.getChildrenNames();
-
- assert childrenNames.size() == 1;
- assert childrenNames.contains(childFqn.getLastElement());
-
- assert children.size() == 1;
- assert children.iterator().next().getFqn().equals(childFqn);
-
- // now change stuff.
-
- rootNode.addChild(Fqn.fromString("/child2"));
-
- // assert that the collections we initially got have not changed.
- assert childrenNames.size() == 1;
- assert childrenNames.contains(childFqn.getLastElement());
-
- assert children.size() == 1;
- assert children.iterator().next().getFqn().equals(childFqn);
- }
-
-
- public void testImmutabilityOfChildren()
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- rootNode.addChild(A);
-
- try
- {
- rootNode.getChildren().clear();
- fail("Collection of child nodes returned in getChildren() should be immutable");
- }
- catch (Exception e)
- {
- // expected
- }
- }
-
- 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
- Node childA = rootNode.addChild(A);
- childA.addChild(B).addChild(C);
-
- rootNode.getChild(A).put("key", "value");
- rootNode.getChild(A).getChild(B).put("key", "value");
- rootNode.getChild(A).getChild(B).getChild(C).put("key", "value");
-
- assertEquals("value", rootNode.getChild(A).get("key"));
- assertEquals("value", rootNode.getChild(A).getChild(B).get("key"));
- assertEquals("value", rootNode.getChild(A).getChild(B).getChild(C).get("key"));
-
- assertNull(rootNode.getChild(Fqn.fromElements("nonexistent")));
- }
-
- public void testClearingData()
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- rootNode.put("k", "v");
- rootNode.put("k2", "v2");
- assertEquals(2, rootNode.getKeys().size());
- rootNode.clearData();
- assertEquals(0, rootNode.getKeys().size());
- assertTrue(rootNode.getData().isEmpty());
- }
-
- public void testClearingDataTx() throws Exception
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- tm.begin();
- rootNode.put("k", "v");
- rootNode.put("k2", "v2");
- assertEquals(2, rootNode.getKeys().size());
- rootNode.clearData();
- assertEquals(0, rootNode.getKeys().size());
- assertTrue(rootNode.getData().isEmpty());
- tm.commit();
- assertTrue(rootNode.getData().isEmpty());
- }
-
- public void testPutData()
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- assertTrue(rootNode.getData().isEmpty());
-
- Map<Object, Object> map = new HashMap<Object, Object>();
- map.put("k1", "v1");
- map.put("k2", "v2");
-
- rootNode.putAll(map);
-
- assertEquals(2, rootNode.getData().size());
- assertEquals("v1", rootNode.get("k1"));
- assertEquals("v2", rootNode.get("k2"));
-
- map.clear();
- map.put("k3", "v3");
-
- rootNode.putAll(map);
- assertEquals(3, rootNode.getData().size());
- assertEquals("v1", rootNode.get("k1"));
- assertEquals("v2", rootNode.get("k2"));
- assertEquals("v3", rootNode.get("k3"));
-
- map.clear();
- map.put("k4", "v4");
- map.put("k5", "v5");
-
- rootNode.replaceAll(map);
- assertEquals(2, rootNode.getData().size());
- assertEquals("v4", rootNode.get("k4"));
- assertEquals("v5", rootNode.get("k5"));
- }
-
- public void testGetChildrenNames() throws Exception
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- rootNode.addChild(A).put("k", "v");
- rootNode.addChild(B).put("k", "v");
-
- Set<Object> childrenNames = new HashSet<Object>();
- childrenNames.add(A.getLastElement());
- childrenNames.add(B.getLastElement());
-
- assertEquals(childrenNames, rootNode.getChildrenNames());
-
- // now delete a child, within a tx
- tm.begin();
- rootNode.removeChild(B);
- assertFalse(rootNode.hasChild(B));
- childrenNames.remove(B.getLastElement());
- assertEquals(childrenNames, rootNode.getChildrenNames());
- tm.commit();
- assertEquals(childrenNames, rootNode.getChildrenNames());
- }
-
- 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;
- assert 1 == (Integer) cache.get("/foo/1/2/3", "item");
- tm.begin();
- assert 1 == (Integer) cache.get("/foo/1/2/3", "item");
- cache.removeNode("/foo/1");
- assertNull(cache.getNode("/foo/1"));
- assertNull(cache.get("/foo/1", "item"));
- cache.removeNode("/foo/1/2/3");
- System.out.println("Cache: " + cache);
- assertNull(cache.get("/foo/1/2/3", "item"));
- assertNull(cache.get("/foo/1", "item"));
- tm.commit();
- assertFalse(cache.exists("/foo/1"));
- assertNull(cache.get("/foo/1/2/3", "item"));
- assertNull(cache.get("/foo/1", "item"));
- }
-
- 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);
- cache.removeNode("/foo/1");
- assertNull(cache.get("/foo/1", "item"));
- cache.removeNode("/foo/1/2");
- assertNull(cache.get("/foo/1", "item"));
- tm.commit();
- assertFalse(cache.exists("/foo/1"));
- assertNull(cache.get("/foo/1/2", "item"));
- assertNull(cache.get("/foo/1", "item"));
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/NodeAPITest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,398 @@
+package org.horizon.api.tree;
+
+import org.horizon.CacheSPI;
+import org.horizon.UnitTestCacheFactory;
+import org.horizon.config.Configuration;
+import org.horizon.transaction.DummyTransactionManager;
+import org.horizon.transaction.DummyTransactionManagerLookup;
+import org.horizon.tree.Fqn;
+import org.horizon.tree.Node;
+import org.horizon.tree.TreeCache;
+import org.horizon.tree.TreeCacheImpl;
+import org.horizon.util.TestingUtil;
+import static org.testng.AssertJUnit.*;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import javax.transaction.TransactionManager;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Tests {@link Node}-centric operations
+ *
+ * @author <a href="mailto:manik AT jboss DOT org">Manik Surtani</a>
+ * @since 2.0.0
+ */
+ at Test(groups = "functional")
+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;
+
+ @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();
+ }
+
+ @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");
+
+ assertEquals("value", nodeA.get("key"));
+ }
+
+ 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);
+ nodeA.put("key", "value");
+
+ assertEquals("value", nodeA.get("key"));
+ tm.commit();
+ }
+
+ public void testOverwritingDataTx() throws Exception
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ Node<Object, Object> nodeA = rootNode.addChild(A);
+ nodeA.put("key", "value");
+ assertEquals("value", nodeA.get("key"));
+ tm.begin();
+ rootNode.removeChild(A);
+ cache.put(A, "k2", "v2");
+ tm.commit();
+ assertNull(nodeA.get("key"));
+ assertEquals("v2", nodeA.get("k2"));
+ }
+
+
+ /**
+ * 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);
+ Node<Object, Object> nodeB = nodeA.addChild(B);
+ Node<Object, Object> nodeC = nodeA.addChild(C);
+ Node<Object, Object> nodeD = rootNode.addChild(D);
+
+ assertEquals(rootNode, nodeA.getParent());
+ assertEquals(nodeA, nodeB.getParent());
+ assertEquals(nodeA, nodeC.getParent());
+ assertEquals(rootNode, nodeD.getParent());
+
+ assertTrue(rootNode.hasChild(A));
+ assertFalse(rootNode.hasChild(B));
+ assertFalse(rootNode.hasChild(C));
+ assertTrue(rootNode.hasChild(D));
+
+ assertTrue(nodeA.hasChild(B));
+ assertTrue(nodeA.hasChild(C));
+
+ assertEquals(nodeA, rootNode.getChild(A));
+ assertEquals(nodeD, rootNode.getChild(D));
+ assertEquals(nodeB, nodeA.getChild(B));
+ assertEquals(nodeC, nodeA.getChild(C));
+
+ assertTrue(nodeA.getChildren().contains(nodeB));
+ assertTrue(nodeA.getChildren().contains(nodeC));
+ assertEquals(2, nodeA.getChildren().size());
+
+ assertTrue(rootNode.getChildren().contains(nodeA));
+ assertTrue(rootNode.getChildren().contains(nodeD));
+ assertEquals(2, rootNode.getChildren().size());
+
+ assertEquals(true, rootNode.removeChild(A));
+ assertFalse(rootNode.getChildren().contains(nodeA));
+ assertTrue(rootNode.getChildren().contains(nodeD));
+ assertEquals(1, rootNode.getChildren().size());
+
+ assertEquals("double remove", false, rootNode.removeChild(A));
+ assertEquals("double remove", false, rootNode.removeChild(A.getLastElement()));
+ }
+
+
+ public void testImmutabilityOfData()
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ rootNode.put("key", "value");
+ Map<Object, Object> m = rootNode.getData();
+ try
+ {
+ m.put("x", "y");
+ fail("Map should be immutable!!");
+ }
+ catch (Exception e)
+ {
+ // expected
+ }
+
+ try
+ {
+ rootNode.getKeys().add(new Object());
+ fail("Key set should be immutable");
+ }
+ catch (Exception e)
+ {
+ // expected
+ }
+ }
+
+ public void testDefensiveCopyOfData()
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ rootNode.put("key", "value");
+ Map<Object, Object> data = rootNode.getData();
+ Set<Object> keys = rootNode.getKeys();
+
+ assert keys.size() == 1;
+ assert keys.contains("key");
+
+ assert data.size() == 1;
+ assert data.containsKey("key");
+
+ // now change stuff.
+
+ rootNode.put("key2", "value2");
+
+ // assert that the collections we initially got have not changed.
+ assert keys.size() == 1;
+ assert keys.contains("key");
+
+ assert data.size() == 1;
+ assert data.containsKey("key");
+ }
+
+ public void testDefensiveCopyOfChildren()
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ Fqn childFqn = Fqn.fromString("/child");
+ rootNode.addChild(childFqn).put("k", "v");
+ Set<Node<Object, Object>> children = rootNode.getChildren();
+ Set<Object> childrenNames = rootNode.getChildrenNames();
+
+ assert childrenNames.size() == 1;
+ assert childrenNames.contains(childFqn.getLastElement());
+
+ assert children.size() == 1;
+ assert children.iterator().next().getFqn().equals(childFqn);
+
+ // now change stuff.
+
+ rootNode.addChild(Fqn.fromString("/child2"));
+
+ // assert that the collections we initially got have not changed.
+ assert childrenNames.size() == 1;
+ assert childrenNames.contains(childFqn.getLastElement());
+
+ assert children.size() == 1;
+ assert children.iterator().next().getFqn().equals(childFqn);
+ }
+
+
+ public void testImmutabilityOfChildren()
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ rootNode.addChild(A);
+
+ try
+ {
+ rootNode.getChildren().clear();
+ fail("Collection of child nodes returned in getChildren() should be immutable");
+ }
+ catch (Exception e)
+ {
+ // expected
+ }
+ }
+
+ 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
+ Node childA = rootNode.addChild(A);
+ childA.addChild(B).addChild(C);
+
+ rootNode.getChild(A).put("key", "value");
+ rootNode.getChild(A).getChild(B).put("key", "value");
+ rootNode.getChild(A).getChild(B).getChild(C).put("key", "value");
+
+ assertEquals("value", rootNode.getChild(A).get("key"));
+ assertEquals("value", rootNode.getChild(A).getChild(B).get("key"));
+ assertEquals("value", rootNode.getChild(A).getChild(B).getChild(C).get("key"));
+
+ assertNull(rootNode.getChild(Fqn.fromElements("nonexistent")));
+ }
+
+ public void testClearingData()
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ rootNode.put("k", "v");
+ rootNode.put("k2", "v2");
+ assertEquals(2, rootNode.getKeys().size());
+ rootNode.clearData();
+ assertEquals(0, rootNode.getKeys().size());
+ assertTrue(rootNode.getData().isEmpty());
+ }
+
+ public void testClearingDataTx() throws Exception
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ tm.begin();
+ rootNode.put("k", "v");
+ rootNode.put("k2", "v2");
+ assertEquals(2, rootNode.getKeys().size());
+ rootNode.clearData();
+ assertEquals(0, rootNode.getKeys().size());
+ assertTrue(rootNode.getData().isEmpty());
+ tm.commit();
+ assertTrue(rootNode.getData().isEmpty());
+ }
+
+ public void testPutData()
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ assertTrue(rootNode.getData().isEmpty());
+
+ Map<Object, Object> map = new HashMap<Object, Object>();
+ map.put("k1", "v1");
+ map.put("k2", "v2");
+
+ rootNode.putAll(map);
+
+ assertEquals(2, rootNode.getData().size());
+ assertEquals("v1", rootNode.get("k1"));
+ assertEquals("v2", rootNode.get("k2"));
+
+ map.clear();
+ map.put("k3", "v3");
+
+ rootNode.putAll(map);
+ assertEquals(3, rootNode.getData().size());
+ assertEquals("v1", rootNode.get("k1"));
+ assertEquals("v2", rootNode.get("k2"));
+ assertEquals("v3", rootNode.get("k3"));
+
+ map.clear();
+ map.put("k4", "v4");
+ map.put("k5", "v5");
+
+ rootNode.replaceAll(map);
+ assertEquals(2, rootNode.getData().size());
+ assertEquals("v4", rootNode.get("k4"));
+ assertEquals("v5", rootNode.get("k5"));
+ }
+
+ public void testGetChildrenNames() throws Exception
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ rootNode.addChild(A).put("k", "v");
+ rootNode.addChild(B).put("k", "v");
+
+ Set<Object> childrenNames = new HashSet<Object>();
+ childrenNames.add(A.getLastElement());
+ childrenNames.add(B.getLastElement());
+
+ assertEquals(childrenNames, rootNode.getChildrenNames());
+
+ // now delete a child, within a tx
+ tm.begin();
+ rootNode.removeChild(B);
+ assertFalse(rootNode.hasChild(B));
+ childrenNames.remove(B.getLastElement());
+ assertEquals(childrenNames, rootNode.getChildrenNames());
+ tm.commit();
+ assertEquals(childrenNames, rootNode.getChildrenNames());
+ }
+
+ 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;
+ assert 1 == (Integer) cache.get("/foo/1/2/3", "item");
+ tm.begin();
+ assert 1 == (Integer) cache.get("/foo/1/2/3", "item");
+ cache.removeNode("/foo/1");
+ assertNull(cache.getNode("/foo/1"));
+ assertNull(cache.get("/foo/1", "item"));
+ cache.removeNode("/foo/1/2/3");
+ System.out.println("Cache: " + cache);
+ assertNull(cache.get("/foo/1/2/3", "item"));
+ assertNull(cache.get("/foo/1", "item"));
+ tm.commit();
+ assertFalse(cache.exists("/foo/1"));
+ assertNull(cache.get("/foo/1/2/3", "item"));
+ assertNull(cache.get("/foo/1", "item"));
+ }
+
+ 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);
+ cache.removeNode("/foo/1");
+ assertNull(cache.get("/foo/1", "item"));
+ cache.removeNode("/foo/1/2");
+ assertNull(cache.get("/foo/1", "item"));
+ tm.commit();
+ assertFalse(cache.exists("/foo/1"));
+ assertNull(cache.get("/foo/1/2", "item"));
+ assertNull(cache.get("/foo/1", "item"));
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/tree/NodeLockSupport.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/NodeLockSupport.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeLockSupport.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,83 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- *
- */
-
-package org.jboss.starobrno.api.tree;
-
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.CacheSPI;
-import org.jboss.starobrno.lock.LockManager;
-import org.jboss.starobrno.tree.Fqn;
-import org.jboss.starobrno.tree.TreeCache;
-import org.jboss.starobrno.tree.TreeStructureSupport;
-
-import javax.transaction.TransactionManager;
-
-public abstract class NodeLockSupport
-{
- 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";
- static final Fqn A_B = Fqn.fromRelativeFqn(A, B);
- static final Fqn A_B_C = Fqn.fromRelativeFqn(A_B, C);
- static final Fqn A_B_C_E = Fqn.fromRelativeFqn(A_B_C, E);
- static final Fqn A_B_D = Fqn.fromRelativeFqn(A_B, D);
- static final Fqn C_E = Fqn.fromRelativeFqn(C, E);
- static final Fqn D_B = Fqn.fromRelativeFqn(D, B);
- static final Fqn D_B_C = Fqn.fromRelativeFqn(D_B, C);
-
- protected ThreadLocal<Cache<Object, Object>> cacheTL = new ThreadLocal<Cache<Object, Object>>();
- protected ThreadLocal<TransactionManager> tmTL = new ThreadLocal<TransactionManager>();
- protected ThreadLocal<TreeCache> treeCacheTL = new ThreadLocal<TreeCache>();
-
- protected void checkLocks()
- {
- Cache<Object, Object> cache = cacheTL.get();
-
- assert !TreeStructureSupport.isLocked(cache, A);
- assert !TreeStructureSupport.isLocked(cache, Fqn.ROOT);
- assert TreeStructureSupport.isLocked(cache, C);
- assert TreeStructureSupport.isLocked(cache, A_B);
- assert TreeStructureSupport.isLocked(cache, A_B_C);
- }
-
- protected void checkLocksDeep()
- {
- Cache<Object, Object> cache = cacheTL.get();
-
- assert !TreeStructureSupport.isLocked(cache, A);
- assert !TreeStructureSupport.isLocked(cache, Fqn.ROOT);
- assert !TreeStructureSupport.isLocked(cache, A_B_D);
-
- assert TreeStructureSupport.isLocked(cache, C);
- assert TreeStructureSupport.isLocked(cache, C_E);
- assert TreeStructureSupport.isLocked(cache, A_B);
- assert TreeStructureSupport.isLocked(cache, A_B_C);
- assert TreeStructureSupport.isLocked(cache, A_B_C_E);
- }
-
- protected void assertNoLocks()
- {
- Cache<Object, Object> cache = cacheTL.get();
- LockManager lm = ((CacheSPI) cache).getLockManager();
- for (Object key : cache.keySet()) assert !lm.isLocked(key);
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/tree/NodeLockSupport.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/NodeLockSupport.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/NodeLockSupport.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeLockSupport.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,83 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ *
+ */
+
+package org.horizon.api.tree;
+
+import org.horizon.Cache;
+import org.horizon.CacheSPI;
+import org.horizon.lock.LockManager;
+import org.horizon.tree.Fqn;
+import org.horizon.tree.TreeCache;
+import org.horizon.tree.TreeStructureSupport;
+
+import javax.transaction.TransactionManager;
+
+public abstract class NodeLockSupport
+{
+ 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";
+ static final Fqn A_B = Fqn.fromRelativeFqn(A, B);
+ static final Fqn A_B_C = Fqn.fromRelativeFqn(A_B, C);
+ static final Fqn A_B_C_E = Fqn.fromRelativeFqn(A_B_C, E);
+ static final Fqn A_B_D = Fqn.fromRelativeFqn(A_B, D);
+ static final Fqn C_E = Fqn.fromRelativeFqn(C, E);
+ static final Fqn D_B = Fqn.fromRelativeFqn(D, B);
+ static final Fqn D_B_C = Fqn.fromRelativeFqn(D_B, C);
+
+ protected ThreadLocal<Cache<Object, Object>> cacheTL = new ThreadLocal<Cache<Object, Object>>();
+ protected ThreadLocal<TransactionManager> tmTL = new ThreadLocal<TransactionManager>();
+ protected ThreadLocal<TreeCache> treeCacheTL = new ThreadLocal<TreeCache>();
+
+ protected void checkLocks()
+ {
+ Cache<Object, Object> cache = cacheTL.get();
+
+ assert !TreeStructureSupport.isLocked(cache, A);
+ assert !TreeStructureSupport.isLocked(cache, Fqn.ROOT);
+ assert TreeStructureSupport.isLocked(cache, C);
+ assert TreeStructureSupport.isLocked(cache, A_B);
+ assert TreeStructureSupport.isLocked(cache, A_B_C);
+ }
+
+ protected void checkLocksDeep()
+ {
+ Cache<Object, Object> cache = cacheTL.get();
+
+ assert !TreeStructureSupport.isLocked(cache, A);
+ assert !TreeStructureSupport.isLocked(cache, Fqn.ROOT);
+ assert !TreeStructureSupport.isLocked(cache, A_B_D);
+
+ assert TreeStructureSupport.isLocked(cache, C);
+ assert TreeStructureSupport.isLocked(cache, C_E);
+ assert TreeStructureSupport.isLocked(cache, A_B);
+ assert TreeStructureSupport.isLocked(cache, A_B_C);
+ assert TreeStructureSupport.isLocked(cache, A_B_C_E);
+ }
+
+ protected void assertNoLocks()
+ {
+ Cache<Object, Object> cache = cacheTL.get();
+ LockManager lm = ((CacheSPI) cache).getLockManager();
+ for (Object key : cache.keySet()) assert !lm.isLocked(key);
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/NodeMoveAPITest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,654 +0,0 @@
-package org.jboss.starobrno.api.tree;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.cache.NodeNotExistsException;
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.CacheSPI;
-import org.jboss.starobrno.UnitTestCacheFactory;
-import org.jboss.starobrno.api.mvcc.LockAssert;
-import org.jboss.starobrno.config.CacheLoaderConfig;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.config.parsing.XmlConfigHelper;
-import org.jboss.starobrno.config.parsing.element.LoadersElementParser;
-import org.jboss.starobrno.factories.ComponentRegistry;
-import org.jboss.starobrno.invocation.InvocationContextContainer;
-import org.jboss.starobrno.lock.LockManager;
-import org.jboss.starobrno.tree.*;
-import org.jboss.starobrno.util.TestingUtil;
-import static org.testng.AssertJUnit.*;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.w3c.dom.Element;
-
-import javax.transaction.TransactionManager;
-import java.util.Random;
-import java.util.concurrent.CountDownLatch;
-
-/**
- * Excercises and tests the new move() api
- *
- * @author <a href="mailto:manik AT jboss DOT org">Manik Surtani</a>
- * @since 2.0.0
- */
- at Test(groups = {"functional", "pessimistic"}, testName = "api.NodeMoveAPITest")
-public class NodeMoveAPITest
-{
- protected final Log log = LogFactory.getLog(getClass());
-
- protected static final Fqn A = Fqn.fromString("/a"), B = Fqn.fromString("/b"), C = Fqn.fromString("/c"), D = Fqn.fromString("/d"), E = Fqn.fromString("/e");
- static final Fqn A_B = Fqn.fromRelativeFqn(A, B);
- static final Fqn A_B_C = Fqn.fromRelativeFqn(A_B, C);
- static final Fqn A_B_C_E = Fqn.fromRelativeFqn(A_B_C, E);
- static final Fqn A_B_D = Fqn.fromRelativeFqn(A_B, D);
- static final Fqn C_E = Fqn.fromRelativeFqn(C, E);
- static final Fqn D_B = Fqn.fromRelativeFqn(D, B);
- static final Fqn D_B_C = Fqn.fromRelativeFqn(D_B, C);
- protected static final Object k = "key", vA = "valueA", vB = "valueB", vC = "valueC", vD = "valueD", vE = "valueE";
-
- protected ThreadLocal<TreeCache<Object, Object>> cacheTL = new ThreadLocal<TreeCache<Object, Object>>();
- protected ThreadLocal<TransactionManager> tmTL = new ThreadLocal<TransactionManager>();
-
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
- // start a single cache instance
- Configuration c = new Configuration();
- c.setFetchInMemoryState(false);
- c.setInvocationBatchingEnabled(true);
- CacheSPI<Object, Object> cache = (CacheSPI<Object, Object>) new UnitTestCacheFactory<Object, Object>().createCache(c);
-
- cacheTL.set(new TreeCacheImpl<Object, Object>(cache));
- tmTL.set(cache.getTransactionManager());
- }
-
- @AfterMethod(alwaysRun = true)
- public void tearDown()
- {
- TestingUtil.killTreeCaches(cacheTL.get());
- cacheTL.set(null);
- }
-
- public void testBasicMove()
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- TransactionManager tm = tmTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- Node<Object, Object> nodeA = rootNode.addChild(A);
- nodeA.put(k, vA);
- Node<Object, Object> nodeB = rootNode.addChild(B);
- nodeB.put(k, vB);
- Node<Object, Object> nodeC = nodeA.addChild(C);
- nodeC.put(k, vC);
- /*
- /a/c
- /b
- */
-
- assertTrue(rootNode.hasChild(A));
- assertTrue(rootNode.hasChild(B));
- assertFalse(rootNode.hasChild(C));
- assertTrue(nodeA.hasChild(C));
-
- // test data
- assertEquals("" + nodeA, vA, nodeA.get(k));
- assertEquals(vB, nodeB.get(k));
- assertEquals(vC, nodeC.get(k));
-
- // parentage
- assertEquals(nodeA, nodeC.getParent());
-
- log.info("BEFORE MOVE " + cache);
- // move
- cache.move(nodeC.getFqn(), nodeB.getFqn());
-
- // re-fetch nodeC
- nodeC = cache.getNode(Fqn.fromRelativeFqn(nodeB.getFqn(), C));
-
- log.info("POST MOVE " + cache);
- log.info("HC " + nodeC + " " + System.identityHashCode(nodeC));
- Node x = cache.getRoot().getChild(Fqn.fromString("b/c"));
- log.info("HC " + x + " " + System.identityHashCode(x));
- /*
- /a
- /b/c
- */
- assertEquals("NODE C " + nodeC, "/b/c", nodeC.getFqn().toString());
-
- assertTrue(rootNode.hasChild(A));
- assertTrue(rootNode.hasChild(B));
- assertFalse(rootNode.hasChild(C));
- assertFalse(nodeA.hasChild(C));
- assertTrue(nodeB.hasChild(C));
-
- // test data
- assertEquals(vA, nodeA.get(k));
- assertEquals(vB, nodeB.get(k));
- assertEquals(vC, nodeC.get(k));
-
- // parentage
- assertEquals("B is parent of C: " + nodeB, nodeB, nodeC.getParent());
- }
-
- @SuppressWarnings("unchecked")
- private Node<Object, Object> genericize(Node node)
- {
- return (Node<Object, Object>) node;
- }
-
- public void testMoveWithChildren()
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- TransactionManager tm = tmTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- Node<Object, Object> nodeA = rootNode.addChild(A);
- nodeA.put(k, vA);
- Node<Object, Object> nodeB = rootNode.addChild(B);
- nodeB.put(k, vB);
- Node<Object, Object> nodeC = nodeA.addChild(C);
- nodeC.put(k, vC);
- Node<Object, Object> nodeD = nodeC.addChild(D);
- nodeD.put(k, vD);
- Node<Object, Object> nodeE = nodeD.addChild(E);
- nodeE.put(k, vE);
-
- assertTrue(rootNode.hasChild(A));
- assertTrue(rootNode.hasChild(B));
- assertFalse(rootNode.hasChild(C));
- assertTrue(nodeA.hasChild(C));
- assertTrue(nodeC.hasChild(D));
- assertTrue(nodeD.hasChild(E));
-
- // test data
- assertEquals(vA, nodeA.get(k));
- assertEquals(vB, nodeB.get(k));
- assertEquals(vC, nodeC.get(k));
- assertEquals(vD, nodeD.get(k));
- assertEquals(vE, nodeE.get(k));
-
- // parentage
- assertEquals(rootNode, nodeA.getParent());
- assertEquals(rootNode, nodeB.getParent());
- assertEquals(nodeA, nodeC.getParent());
- assertEquals(nodeC, nodeD.getParent());
- assertEquals(nodeD, nodeE.getParent());
-
- // move
- log.info("move " + nodeC + " to " + nodeB);
- cache.move(nodeC.getFqn(), nodeB.getFqn());
- //System.out.println("nodeB " + nodeB);
- //System.out.println("nodeC " + nodeC);
-
- // child nodes will need refreshing, since existing pointers will be stale.
- nodeC = nodeB.getChild(C);
- nodeD = nodeC.getChild(D);
- nodeE = nodeD.getChild(E);
-
- assertTrue(rootNode.hasChild(A));
- assertTrue(rootNode.hasChild(B));
- assertFalse(rootNode.hasChild(C));
- assertFalse(nodeA.hasChild(C));
- assertTrue(nodeB.hasChild(C));
- assertTrue(nodeC.hasChild(D));
- assertTrue(nodeD.hasChild(E));
-
- // test data
- assertEquals(vA, nodeA.get(k));
- assertEquals(vB, nodeB.get(k));
- assertEquals(vC, nodeC.get(k));
- assertEquals(vD, nodeD.get(k));
- assertEquals(vE, nodeE.get(k));
-
- // parentage
- assertEquals(rootNode, nodeA.getParent());
- assertEquals(rootNode, nodeB.getParent());
- assertEquals(nodeB, nodeC.getParent());
- assertEquals(nodeC, nodeD.getParent());
- assertEquals(nodeD, nodeE.getParent());
- }
-
- public void testTxCommit() throws Exception
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- TransactionManager tm = tmTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- Node<Object, Object> nodeA = rootNode.addChild(A);
- Node<Object, Object> nodeB = nodeA.addChild(B);
-
- assertEquals(rootNode, nodeA.getParent());
- assertEquals(nodeA, nodeB.getParent());
- assertEquals(nodeA, rootNode.getChildren().iterator().next());
- assertEquals(nodeB, nodeA.getChildren().iterator().next());
-
- tm.begin();
- // move node B up to hang off the root
- cache.move(nodeB.getFqn(), Fqn.ROOT);
-
- tm.commit();
-
- nodeB = rootNode.getChild(B);
-
- assertEquals(rootNode, nodeA.getParent());
- assertEquals(rootNode, nodeB.getParent());
-
- assertTrue(rootNode.getChildren().contains(nodeA));
- assertTrue(rootNode.getChildren().contains(nodeB));
-
- assertTrue(nodeA.getChildren().isEmpty());
- }
-
- public void testTxRollback() throws Exception
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- TransactionManager tm = tmTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- Node<Object, Object> nodeA = rootNode.addChild(A);
- Node<Object, Object> nodeB = nodeA.addChild(B);
-
- assertEquals(rootNode, nodeA.getParent());
- assertEquals(nodeA, nodeB.getParent());
- assertEquals(nodeA, rootNode.getChildren().iterator().next());
- assertEquals(nodeB, nodeA.getChildren().iterator().next());
-
-
- tm.begin();
- // move node B up to hang off the root
- System.out.println("Before: " + TreeStructureSupport.printTree(cache, true));
- cache.move(nodeB.getFqn(), Fqn.ROOT);
- System.out.println("After: " + TreeStructureSupport.printTree(cache, true));
- tm.rollback();
- System.out.println("Rolled back: " + TreeStructureSupport.printTree(cache, true));
-
- nodeA = rootNode.getChild(A);
- nodeB = nodeA.getChild(B);
-
- // should revert
- assertEquals(rootNode, nodeA.getParent());
- assertEquals(nodeA, nodeB.getParent());
- assertEquals(nodeA, rootNode.getChildren().iterator().next());
- assertEquals(nodeB, nodeA.getChildren().iterator().next());
- }
-
- /*
- public void testWithCacheloaders() throws Exception
- {
- doCacheLoaderTest(false, false);
- }
-
- public void testWithPassivation() throws Exception
- {
- doCacheLoaderTest(true, false);
- }
-
- public void testWithCacheloadersTx() throws Exception
- {
- doCacheLoaderTest(false, true);
- }
-
- public void testWithPassivationTx() throws Exception
- {
- doCacheLoaderTest(true, true);
- }
- */
-
- /*
-protected void doCacheLoaderTest(boolean pasv, boolean useTx) throws Exception
-{
-TreeCache<Object, Object> cache = cacheTL.get();
-TransactionManager tm = tmTL.get();
-Node<Object, Object> rootNode = cache.getRoot();
-
-cache.destroy();
-cache.getConfiguration().setCacheLoaderConfig(getSingleCacheLoaderConfig(pasv, "/", DummyInMemoryCacheLoader.class.getName(), "debug=true", false, false, false, false));
-cache.start();
-
-DummyInMemoryCacheLoader loader = (DummyInMemoryCacheLoader) cache.getCacheLoaderManager().getCacheLoader();
-
-rootNode.put("key", "value");
-
-if (!pasv)
-{
-Map m = loader.get(Fqn.ROOT);
-assertNotNull("Should not be null", m);
-assertEquals("value", m.get("key"));
-}
-
-Node<Object, Object> nodeA = rootNode.addChild(A);
-nodeA.put(k, vA);
-Node<Object, Object> nodeB = rootNode.addChild(B);
-nodeB.put(k, vB);
-Node<Object, Object> nodeC = nodeA.addChild(C);
-nodeC.put(k, vC);
-Node<Object, Object> nodeD = nodeC.addChild(D);
-nodeD.put(k, vD);
-Node<Object, Object> nodeE = nodeD.addChild(E);
-nodeE.put(k, vE);
-cache.evict(Fqn.ROOT, true);
-
-// move
-if (useTx) tm.begin();
-cache.move(nodeC.getFqn(), nodeB.getFqn());
-if (useTx) tm.commit();
-
-// after eviction, the node objects we hold are probably stale.
-nodeA = rootNode.getChild(A);
-nodeB = rootNode.getChild(B);
-nodeC = nodeB.getChild(C);
-log.info("nodeC get child B ");
-nodeD = nodeC.getChild(D);
-log.info("nodeD get child E ");
-nodeE = nodeD.getChild(E);
-
-Fqn old_C = C;
-Fqn old_D = Fqn.fromRelativeFqn(old_C, D);
-Fqn old_E = Fqn.fromRelativeFqn(old_D, E);
-
-// test data
-assertEquals(vA, nodeA.get(k));
-assertEquals(vB, nodeB.get(k));
-assertEquals(vC, nodeC.get(k));
-assertEquals(vD, nodeD.get(k));
-assertEquals(vE, nodeE.get(k));
-
-// parentage
-assertEquals(rootNode, nodeA.getParent());
-assertEquals(rootNode, nodeB.getParent());
-assertEquals(nodeB, nodeC.getParent());
-assertEquals(nodeC, nodeD.getParent());
-assertEquals(nodeD, nodeE.getParent());
-
-
-if (pasv) cache.evict(Fqn.ROOT, true);
-
-//now inspect the loader.
-assertEquals(vA, loader.get(nodeA.getFqn()).get(k));
-assertEquals(vB, loader.get(nodeB.getFqn()).get(k));
-assertEquals(vC, loader.get(nodeC.getFqn()).get(k));
-assertEquals(vD, loader.get(nodeD.getFqn()).get(k));
-assertEquals(vE, loader.get(nodeE.getFqn()).get(k));
-
-assertNull(loader.get(old_C));
-assertNull(loader.get(old_D));
-assertNull(loader.get(old_E));
-
-}
- */
-
- public void testLocksDeepMove() throws Exception
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- TransactionManager tm = tmTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- Node<Object, Object> nodeA = rootNode.addChild(A);
- Node<Object, Object> nodeB = nodeA.addChild(B);
- Node<Object, Object> nodeD = nodeB.addChild(D);
- Node<Object, Object> nodeC = rootNode.addChild(C);
- Node<Object, Object> nodeE = nodeC.addChild(E);
- assertNoLocks();
- tm.begin();
-
- cache.move(nodeC.getFqn(), nodeB.getFqn());
-
- checkLocksDeep();
-
-
- tm.commit();
-
- assertNoLocks();
- }
-
- public void testLocks() throws Exception
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- TransactionManager tm = tmTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- Node<Object, Object> nodeA = rootNode.addChild(A);
- Node<Object, Object> nodeB = nodeA.addChild(B);
- Node<Object, Object> nodeC = rootNode.addChild(C);
- assertNoLocks();
- tm.begin();
-
- cache.move(nodeC.getFqn(), nodeB.getFqn());
-
- checkLocks();
-
- tm.commit();
- assertNoLocks();
- }
-
- public void testConcurrency() throws InterruptedException
- {
- final TreeCache<Object, Object> cache = cacheTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- final int N = 3;// number of threads
- final int loops = 1 << 6;// number of loops
- // tests a tree structure as such:
- // /a
- // /b
- // /c
- // /d
- // /e
- // /x
- // /y
-
- // N threads constantly move /x and /y around to hang off either /a ~ /e randomly.
-
- final Fqn FQN_A = A, FQN_B = B, FQN_C = C, FQN_D = D, FQN_E = E, FQN_X = Fqn.fromString("/x"), FQN_Y = Fqn.fromString("/y");
-
- // set up the initial structure.
- final Node[] NODES = {
- rootNode.addChild(FQN_A), rootNode.addChild(FQN_B),
- rootNode.addChild(FQN_C), rootNode.addChild(FQN_D), rootNode.addChild(FQN_E)
- };
-
- final Node<Object, Object> NODE_X = genericize(NODES[0]).addChild(FQN_X);
- final Node<Object, Object> NODE_Y = genericize(NODES[1]).addChild(FQN_Y);
-
- Thread[] movers = new Thread[N];
- final CountDownLatch latch = new CountDownLatch(1);
- final Random r = new Random();
-
- for (int i = 0; i < N; i++)
- {
- movers[i] = new Thread("Mover-" + i)
- {
- public void run()
- {
- try
- {
- latch.await();
- }
- catch (InterruptedException e)
- {
- }
-
- for (int counter = 0; counter < loops; counter++)
- {
-
- System.out.println(getName() + ": Attempt " + counter);
- try
- {
- cache.move(NODE_X.getFqn(), NODES[r.nextInt(NODES.length)].getFqn());
- }
- catch (NodeNotExistsException e)
- {
- // this may happen ...
- }
- TestingUtil.sleepRandom(250);
- try
- {
- cache.move(NODE_Y.getFqn(), NODES[r.nextInt(NODES.length)].getFqn());
- }
- catch (NodeNotExistsException e)
- {
- // this may happen ...
- }
- TestingUtil.sleepRandom(250);
- }
- }
- };
- movers[i].start();
- }
-
- latch.countDown();
-
- for (Thread t : movers)
- {
- t.join();
- }
-
- assertNoLocks();
- boolean found_x = false, found_x_again = false;
- for (Node erased : NODES)
- {
- Node<Object, Object> n = genericize(erased);
- if (!found_x)
- {
- found_x = n.hasChild(FQN_X);
- }
- else
- {
- found_x_again = found_x_again || n.hasChild(FQN_X);
- }
- }
- boolean found_y = false, found_y_again = false;
- for (Node erased : NODES)
- {
- Node<Object, Object> n = genericize(erased);
- if (!found_y)
- {
- found_y = n.hasChild(FQN_Y);
- }
- else
- {
- found_y_again = found_y_again || n.hasChild(FQN_Y);
- }
- }
-
- assertTrue("Should have found x", found_x);
- assertTrue("Should have found y", found_y);
- assertFalse("Should have only found x once", found_x_again);
- assertFalse("Should have only found y once", found_y_again);
- }
-
- public void testMoveInSamePlace()
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- Node<Object, Object> rootNode = cache.getRoot();
-
- final Fqn FQN_X = Fqn.fromString("/x");
- // set up the initial structure.
- Node aNode = rootNode.addChild(A);
- Node xNode = aNode.addChild(FQN_X);
- assertEquals(aNode.getChildren().size(), 1);
-
- System.out.println("Before: " + TreeStructureSupport.printTree(cache, true));
-
- cache.move(xNode.getFqn(), aNode.getFqn());
-
- System.out.println("After: " + TreeStructureSupport.printTree(cache, true));
-
- assertEquals(aNode.getChildren().size(), 1);
-
- assertNoLocks();
- }
-
- protected CacheLoaderConfig getSingleCacheLoaderConfig(boolean passivation, String preload, String cacheloaderClass, String properties, boolean async, boolean fetchPersistentState, boolean shared, boolean purgeOnStartup) throws Exception
- {
- String xml =
- " <loaders passivation=\"" + passivation + "\" shared=\"" + shared + "\">\n" +
- " <preload>\n" +
- " <node fqn=\"" + preload + "\"/>\n" +
- " </preload>\n" +
- " <loader class=\"" + cacheloaderClass + "\" async=\"" + async + "\" fetchPersistentState=\"" + fetchPersistentState + "\"\n" +
- " purgeOnStartup=\"" + purgeOnStartup + "\">\n" +
- " <properties>\n" +
- properties +
- " </properties>\n" +
- " </loader>\n" +
- " </loaders>";
- Element element = XmlConfigHelper.stringToElementInCoreNS(xml);
- LoadersElementParser elementParser = new LoadersElementParser();
- return elementParser.parseLoadersElement(element);
- }
-
- protected void checkLocks()
- {
- TreeCache<Object, Object> tree = cacheTL.get();
- Cache<Object, Object> cache = tree.getCache();
-
- assert TreeStructureSupport.isLocked(cache, C);
- assert !cache.getConfiguration().isLockParentForChildInsertRemove() || TreeStructureSupport.isLocked(cache, A_B);
- assert TreeStructureSupport.isLocked(cache, A_B_C);
- }
-
- protected void checkLocksDeep()
- {
- TreeCache<Object, Object> tree = cacheTL.get();
- 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);
- assert TreeStructureSupport.isLocked(cache, A_B_C_E);
- }
-
- protected void assertNoLocks()
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- ComponentRegistry cr = TestingUtil.extractComponentRegistry(cache.getCache());
- LockManager lm = cr.getComponent(LockManager.class);
- InvocationContextContainer icc = cr.getComponent(InvocationContextContainer.class);
- LockAssert.assertNoLocks(lm, icc);
- }
-
- public void testNonexistentSource()
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- cache.put(A_B_C, "k", "v");
- assert "v".equals(cache.get(A_B_C, "k"));
- assert 1 == cache.getNode(A_B).getChildren().size();
- assert cache.getNode(A_B).getChildrenNames().contains(C.getLastElement());
- assert !cache.getNode(A_B).getChildrenNames().contains(D.getLastElement());
-
- cache.move(D, A_B);
-
- assert "v".equals(cache.get(A_B_C, "k"));
- assert 1 == cache.getNode(A_B).getChildren().size();
- assert cache.getNode(A_B).getChildrenNames().contains(C.getLastElement());
- assert !cache.getNode(A_B).getChildrenNames().contains(D.getLastElement());
- }
-
- public void testNonexistentTarget()
- {
- TreeCache<Object, Object> cache = cacheTL.get();
- cache.put(A_B_C, "k", "v");
- assert "v".equals(cache.get(A_B_C, "k"));
- assert 1 == cache.getNode(A_B).getChildren().size();
- assert cache.getNode(A_B).getChildrenNames().contains(C.getLastElement());
- assert null == cache.getNode(D);
-
- System.out.println(TreeStructureSupport.printTree(cache, true));
-
- cache.move(A_B, D);
-
- System.out.println(TreeStructureSupport.printTree(cache, true));
-
- assert null == cache.getNode(A_B_C);
- assert null == cache.getNode(A_B);
- assert null != cache.getNode(D);
- assert null != cache.getNode(D_B);
- assert null != cache.getNode(D_B_C);
- assert "v".equals(cache.get(D_B_C, "k"));
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/NodeMoveAPITest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,654 @@
+package org.horizon.api.tree;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.horizon.tree.NodeNotExistsException;
+import org.horizon.Cache;
+import org.horizon.CacheSPI;
+import org.horizon.UnitTestCacheFactory;
+import org.horizon.api.mvcc.LockAssert;
+import org.horizon.config.CacheLoaderConfig;
+import org.horizon.config.Configuration;
+import org.horizon.config.parsing.XmlConfigHelper;
+import org.horizon.config.parsing.element.LoadersElementParser;
+import org.horizon.factories.ComponentRegistry;
+import org.horizon.invocation.InvocationContextContainer;
+import org.horizon.lock.LockManager;
+import org.horizon.tree.*;
+import org.horizon.util.TestingUtil;
+import static org.testng.AssertJUnit.*;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.w3c.dom.Element;
+
+import javax.transaction.TransactionManager;
+import java.util.Random;
+import java.util.concurrent.CountDownLatch;
+
+/**
+ * Excercises and tests the new move() api
+ *
+ * @author <a href="mailto:manik AT jboss DOT org">Manik Surtani</a>
+ * @since 2.0.0
+ */
+ at Test(groups = {"functional", "pessimistic"}, testName = "api.NodeMoveAPITest")
+public class NodeMoveAPITest
+{
+ protected final Log log = LogFactory.getLog(getClass());
+
+ protected static final Fqn A = Fqn.fromString("/a"), B = Fqn.fromString("/b"), C = Fqn.fromString("/c"), D = Fqn.fromString("/d"), E = Fqn.fromString("/e");
+ static final Fqn A_B = Fqn.fromRelativeFqn(A, B);
+ static final Fqn A_B_C = Fqn.fromRelativeFqn(A_B, C);
+ static final Fqn A_B_C_E = Fqn.fromRelativeFqn(A_B_C, E);
+ static final Fqn A_B_D = Fqn.fromRelativeFqn(A_B, D);
+ static final Fqn C_E = Fqn.fromRelativeFqn(C, E);
+ static final Fqn D_B = Fqn.fromRelativeFqn(D, B);
+ static final Fqn D_B_C = Fqn.fromRelativeFqn(D_B, C);
+ protected static final Object k = "key", vA = "valueA", vB = "valueB", vC = "valueC", vD = "valueD", vE = "valueE";
+
+ protected ThreadLocal<TreeCache<Object, Object>> cacheTL = new ThreadLocal<TreeCache<Object, Object>>();
+ protected ThreadLocal<TransactionManager> tmTL = new ThreadLocal<TransactionManager>();
+
+ @BeforeMethod(alwaysRun = true)
+ public void setUp() throws Exception
+ {
+ // start a single cache instance
+ Configuration c = new Configuration();
+ c.setFetchInMemoryState(false);
+ c.setInvocationBatchingEnabled(true);
+ CacheSPI<Object, Object> cache = (CacheSPI<Object, Object>) new UnitTestCacheFactory<Object, Object>().createCache(c);
+
+ cacheTL.set(new TreeCacheImpl<Object, Object>(cache));
+ tmTL.set(cache.getTransactionManager());
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown()
+ {
+ TestingUtil.killTreeCaches(cacheTL.get());
+ cacheTL.set(null);
+ }
+
+ public void testBasicMove()
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ TransactionManager tm = tmTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ Node<Object, Object> nodeA = rootNode.addChild(A);
+ nodeA.put(k, vA);
+ Node<Object, Object> nodeB = rootNode.addChild(B);
+ nodeB.put(k, vB);
+ Node<Object, Object> nodeC = nodeA.addChild(C);
+ nodeC.put(k, vC);
+ /*
+ /a/c
+ /b
+ */
+
+ assertTrue(rootNode.hasChild(A));
+ assertTrue(rootNode.hasChild(B));
+ assertFalse(rootNode.hasChild(C));
+ assertTrue(nodeA.hasChild(C));
+
+ // test data
+ assertEquals("" + nodeA, vA, nodeA.get(k));
+ assertEquals(vB, nodeB.get(k));
+ assertEquals(vC, nodeC.get(k));
+
+ // parentage
+ assertEquals(nodeA, nodeC.getParent());
+
+ log.info("BEFORE MOVE " + cache);
+ // move
+ cache.move(nodeC.getFqn(), nodeB.getFqn());
+
+ // re-fetch nodeC
+ nodeC = cache.getNode(Fqn.fromRelativeFqn(nodeB.getFqn(), C));
+
+ log.info("POST MOVE " + cache);
+ log.info("HC " + nodeC + " " + System.identityHashCode(nodeC));
+ Node x = cache.getRoot().getChild(Fqn.fromString("b/c"));
+ log.info("HC " + x + " " + System.identityHashCode(x));
+ /*
+ /a
+ /b/c
+ */
+ assertEquals("NODE C " + nodeC, "/b/c", nodeC.getFqn().toString());
+
+ assertTrue(rootNode.hasChild(A));
+ assertTrue(rootNode.hasChild(B));
+ assertFalse(rootNode.hasChild(C));
+ assertFalse(nodeA.hasChild(C));
+ assertTrue(nodeB.hasChild(C));
+
+ // test data
+ assertEquals(vA, nodeA.get(k));
+ assertEquals(vB, nodeB.get(k));
+ assertEquals(vC, nodeC.get(k));
+
+ // parentage
+ assertEquals("B is parent of C: " + nodeB, nodeB, nodeC.getParent());
+ }
+
+ @SuppressWarnings("unchecked")
+ private Node<Object, Object> genericize(Node node)
+ {
+ return (Node<Object, Object>) node;
+ }
+
+ public void testMoveWithChildren()
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ TransactionManager tm = tmTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ Node<Object, Object> nodeA = rootNode.addChild(A);
+ nodeA.put(k, vA);
+ Node<Object, Object> nodeB = rootNode.addChild(B);
+ nodeB.put(k, vB);
+ Node<Object, Object> nodeC = nodeA.addChild(C);
+ nodeC.put(k, vC);
+ Node<Object, Object> nodeD = nodeC.addChild(D);
+ nodeD.put(k, vD);
+ Node<Object, Object> nodeE = nodeD.addChild(E);
+ nodeE.put(k, vE);
+
+ assertTrue(rootNode.hasChild(A));
+ assertTrue(rootNode.hasChild(B));
+ assertFalse(rootNode.hasChild(C));
+ assertTrue(nodeA.hasChild(C));
+ assertTrue(nodeC.hasChild(D));
+ assertTrue(nodeD.hasChild(E));
+
+ // test data
+ assertEquals(vA, nodeA.get(k));
+ assertEquals(vB, nodeB.get(k));
+ assertEquals(vC, nodeC.get(k));
+ assertEquals(vD, nodeD.get(k));
+ assertEquals(vE, nodeE.get(k));
+
+ // parentage
+ assertEquals(rootNode, nodeA.getParent());
+ assertEquals(rootNode, nodeB.getParent());
+ assertEquals(nodeA, nodeC.getParent());
+ assertEquals(nodeC, nodeD.getParent());
+ assertEquals(nodeD, nodeE.getParent());
+
+ // move
+ log.info("move " + nodeC + " to " + nodeB);
+ cache.move(nodeC.getFqn(), nodeB.getFqn());
+ //System.out.println("nodeB " + nodeB);
+ //System.out.println("nodeC " + nodeC);
+
+ // child nodes will need refreshing, since existing pointers will be stale.
+ nodeC = nodeB.getChild(C);
+ nodeD = nodeC.getChild(D);
+ nodeE = nodeD.getChild(E);
+
+ assertTrue(rootNode.hasChild(A));
+ assertTrue(rootNode.hasChild(B));
+ assertFalse(rootNode.hasChild(C));
+ assertFalse(nodeA.hasChild(C));
+ assertTrue(nodeB.hasChild(C));
+ assertTrue(nodeC.hasChild(D));
+ assertTrue(nodeD.hasChild(E));
+
+ // test data
+ assertEquals(vA, nodeA.get(k));
+ assertEquals(vB, nodeB.get(k));
+ assertEquals(vC, nodeC.get(k));
+ assertEquals(vD, nodeD.get(k));
+ assertEquals(vE, nodeE.get(k));
+
+ // parentage
+ assertEquals(rootNode, nodeA.getParent());
+ assertEquals(rootNode, nodeB.getParent());
+ assertEquals(nodeB, nodeC.getParent());
+ assertEquals(nodeC, nodeD.getParent());
+ assertEquals(nodeD, nodeE.getParent());
+ }
+
+ public void testTxCommit() throws Exception
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ TransactionManager tm = tmTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ Node<Object, Object> nodeA = rootNode.addChild(A);
+ Node<Object, Object> nodeB = nodeA.addChild(B);
+
+ assertEquals(rootNode, nodeA.getParent());
+ assertEquals(nodeA, nodeB.getParent());
+ assertEquals(nodeA, rootNode.getChildren().iterator().next());
+ assertEquals(nodeB, nodeA.getChildren().iterator().next());
+
+ tm.begin();
+ // move node B up to hang off the root
+ cache.move(nodeB.getFqn(), Fqn.ROOT);
+
+ tm.commit();
+
+ nodeB = rootNode.getChild(B);
+
+ assertEquals(rootNode, nodeA.getParent());
+ assertEquals(rootNode, nodeB.getParent());
+
+ assertTrue(rootNode.getChildren().contains(nodeA));
+ assertTrue(rootNode.getChildren().contains(nodeB));
+
+ assertTrue(nodeA.getChildren().isEmpty());
+ }
+
+ public void testTxRollback() throws Exception
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ TransactionManager tm = tmTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ Node<Object, Object> nodeA = rootNode.addChild(A);
+ Node<Object, Object> nodeB = nodeA.addChild(B);
+
+ assertEquals(rootNode, nodeA.getParent());
+ assertEquals(nodeA, nodeB.getParent());
+ assertEquals(nodeA, rootNode.getChildren().iterator().next());
+ assertEquals(nodeB, nodeA.getChildren().iterator().next());
+
+
+ tm.begin();
+ // move node B up to hang off the root
+ System.out.println("Before: " + TreeStructureSupport.printTree(cache, true));
+ cache.move(nodeB.getFqn(), Fqn.ROOT);
+ System.out.println("After: " + TreeStructureSupport.printTree(cache, true));
+ tm.rollback();
+ System.out.println("Rolled back: " + TreeStructureSupport.printTree(cache, true));
+
+ nodeA = rootNode.getChild(A);
+ nodeB = nodeA.getChild(B);
+
+ // should revert
+ assertEquals(rootNode, nodeA.getParent());
+ assertEquals(nodeA, nodeB.getParent());
+ assertEquals(nodeA, rootNode.getChildren().iterator().next());
+ assertEquals(nodeB, nodeA.getChildren().iterator().next());
+ }
+
+ /*
+ public void testWithCacheloaders() throws Exception
+ {
+ doCacheLoaderTest(false, false);
+ }
+
+ public void testWithPassivation() throws Exception
+ {
+ doCacheLoaderTest(true, false);
+ }
+
+ public void testWithCacheloadersTx() throws Exception
+ {
+ doCacheLoaderTest(false, true);
+ }
+
+ public void testWithPassivationTx() throws Exception
+ {
+ doCacheLoaderTest(true, true);
+ }
+ */
+
+ /*
+protected void doCacheLoaderTest(boolean pasv, boolean useTx) throws Exception
+{
+TreeCache<Object, Object> cache = cacheTL.get();
+TransactionManager tm = tmTL.get();
+Node<Object, Object> rootNode = cache.getRoot();
+
+cache.destroy();
+cache.getConfiguration().setCacheLoaderConfig(getSingleCacheLoaderConfig(pasv, "/", DummyInMemoryCacheLoader.class.getName(), "debug=true", false, false, false, false));
+cache.start();
+
+DummyInMemoryCacheLoader loader = (DummyInMemoryCacheLoader) cache.getCacheLoaderManager().getCacheLoader();
+
+rootNode.put("key", "value");
+
+if (!pasv)
+{
+Map m = loader.get(Fqn.ROOT);
+assertNotNull("Should not be null", m);
+assertEquals("value", m.get("key"));
+}
+
+Node<Object, Object> nodeA = rootNode.addChild(A);
+nodeA.put(k, vA);
+Node<Object, Object> nodeB = rootNode.addChild(B);
+nodeB.put(k, vB);
+Node<Object, Object> nodeC = nodeA.addChild(C);
+nodeC.put(k, vC);
+Node<Object, Object> nodeD = nodeC.addChild(D);
+nodeD.put(k, vD);
+Node<Object, Object> nodeE = nodeD.addChild(E);
+nodeE.put(k, vE);
+cache.evict(Fqn.ROOT, true);
+
+// move
+if (useTx) tm.begin();
+cache.move(nodeC.getFqn(), nodeB.getFqn());
+if (useTx) tm.commit();
+
+// after eviction, the node objects we hold are probably stale.
+nodeA = rootNode.getChild(A);
+nodeB = rootNode.getChild(B);
+nodeC = nodeB.getChild(C);
+log.info("nodeC get child B ");
+nodeD = nodeC.getChild(D);
+log.info("nodeD get child E ");
+nodeE = nodeD.getChild(E);
+
+Fqn old_C = C;
+Fqn old_D = Fqn.fromRelativeFqn(old_C, D);
+Fqn old_E = Fqn.fromRelativeFqn(old_D, E);
+
+// test data
+assertEquals(vA, nodeA.get(k));
+assertEquals(vB, nodeB.get(k));
+assertEquals(vC, nodeC.get(k));
+assertEquals(vD, nodeD.get(k));
+assertEquals(vE, nodeE.get(k));
+
+// parentage
+assertEquals(rootNode, nodeA.getParent());
+assertEquals(rootNode, nodeB.getParent());
+assertEquals(nodeB, nodeC.getParent());
+assertEquals(nodeC, nodeD.getParent());
+assertEquals(nodeD, nodeE.getParent());
+
+
+if (pasv) cache.evict(Fqn.ROOT, true);
+
+//now inspect the loader.
+assertEquals(vA, loader.get(nodeA.getFqn()).get(k));
+assertEquals(vB, loader.get(nodeB.getFqn()).get(k));
+assertEquals(vC, loader.get(nodeC.getFqn()).get(k));
+assertEquals(vD, loader.get(nodeD.getFqn()).get(k));
+assertEquals(vE, loader.get(nodeE.getFqn()).get(k));
+
+assertNull(loader.get(old_C));
+assertNull(loader.get(old_D));
+assertNull(loader.get(old_E));
+
+}
+ */
+
+ public void testLocksDeepMove() throws Exception
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ TransactionManager tm = tmTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ Node<Object, Object> nodeA = rootNode.addChild(A);
+ Node<Object, Object> nodeB = nodeA.addChild(B);
+ Node<Object, Object> nodeD = nodeB.addChild(D);
+ Node<Object, Object> nodeC = rootNode.addChild(C);
+ Node<Object, Object> nodeE = nodeC.addChild(E);
+ assertNoLocks();
+ tm.begin();
+
+ cache.move(nodeC.getFqn(), nodeB.getFqn());
+
+ checkLocksDeep();
+
+
+ tm.commit();
+
+ assertNoLocks();
+ }
+
+ public void testLocks() throws Exception
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ TransactionManager tm = tmTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ Node<Object, Object> nodeA = rootNode.addChild(A);
+ Node<Object, Object> nodeB = nodeA.addChild(B);
+ Node<Object, Object> nodeC = rootNode.addChild(C);
+ assertNoLocks();
+ tm.begin();
+
+ cache.move(nodeC.getFqn(), nodeB.getFqn());
+
+ checkLocks();
+
+ tm.commit();
+ assertNoLocks();
+ }
+
+ public void testConcurrency() throws InterruptedException
+ {
+ final TreeCache<Object, Object> cache = cacheTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ final int N = 3;// number of threads
+ final int loops = 1 << 6;// number of loops
+ // tests a tree structure as such:
+ // /a
+ // /b
+ // /c
+ // /d
+ // /e
+ // /x
+ // /y
+
+ // N threads constantly move /x and /y around to hang off either /a ~ /e randomly.
+
+ final Fqn FQN_A = A, FQN_B = B, FQN_C = C, FQN_D = D, FQN_E = E, FQN_X = Fqn.fromString("/x"), FQN_Y = Fqn.fromString("/y");
+
+ // set up the initial structure.
+ final Node[] NODES = {
+ rootNode.addChild(FQN_A), rootNode.addChild(FQN_B),
+ rootNode.addChild(FQN_C), rootNode.addChild(FQN_D), rootNode.addChild(FQN_E)
+ };
+
+ final Node<Object, Object> NODE_X = genericize(NODES[0]).addChild(FQN_X);
+ final Node<Object, Object> NODE_Y = genericize(NODES[1]).addChild(FQN_Y);
+
+ Thread[] movers = new Thread[N];
+ final CountDownLatch latch = new CountDownLatch(1);
+ final Random r = new Random();
+
+ for (int i = 0; i < N; i++)
+ {
+ movers[i] = new Thread("Mover-" + i)
+ {
+ public void run()
+ {
+ try
+ {
+ latch.await();
+ }
+ catch (InterruptedException e)
+ {
+ }
+
+ for (int counter = 0; counter < loops; counter++)
+ {
+
+ System.out.println(getName() + ": Attempt " + counter);
+ try
+ {
+ cache.move(NODE_X.getFqn(), NODES[r.nextInt(NODES.length)].getFqn());
+ }
+ catch (NodeNotExistsException e)
+ {
+ // this may happen ...
+ }
+ TestingUtil.sleepRandom(250);
+ try
+ {
+ cache.move(NODE_Y.getFqn(), NODES[r.nextInt(NODES.length)].getFqn());
+ }
+ catch (NodeNotExistsException e)
+ {
+ // this may happen ...
+ }
+ TestingUtil.sleepRandom(250);
+ }
+ }
+ };
+ movers[i].start();
+ }
+
+ latch.countDown();
+
+ for (Thread t : movers)
+ {
+ t.join();
+ }
+
+ assertNoLocks();
+ boolean found_x = false, found_x_again = false;
+ for (Node erased : NODES)
+ {
+ Node<Object, Object> n = genericize(erased);
+ if (!found_x)
+ {
+ found_x = n.hasChild(FQN_X);
+ }
+ else
+ {
+ found_x_again = found_x_again || n.hasChild(FQN_X);
+ }
+ }
+ boolean found_y = false, found_y_again = false;
+ for (Node erased : NODES)
+ {
+ Node<Object, Object> n = genericize(erased);
+ if (!found_y)
+ {
+ found_y = n.hasChild(FQN_Y);
+ }
+ else
+ {
+ found_y_again = found_y_again || n.hasChild(FQN_Y);
+ }
+ }
+
+ assertTrue("Should have found x", found_x);
+ assertTrue("Should have found y", found_y);
+ assertFalse("Should have only found x once", found_x_again);
+ assertFalse("Should have only found y once", found_y_again);
+ }
+
+ public void testMoveInSamePlace()
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ Node<Object, Object> rootNode = cache.getRoot();
+
+ final Fqn FQN_X = Fqn.fromString("/x");
+ // set up the initial structure.
+ Node aNode = rootNode.addChild(A);
+ Node xNode = aNode.addChild(FQN_X);
+ assertEquals(aNode.getChildren().size(), 1);
+
+ System.out.println("Before: " + TreeStructureSupport.printTree(cache, true));
+
+ cache.move(xNode.getFqn(), aNode.getFqn());
+
+ System.out.println("After: " + TreeStructureSupport.printTree(cache, true));
+
+ assertEquals(aNode.getChildren().size(), 1);
+
+ assertNoLocks();
+ }
+
+ protected CacheLoaderConfig getSingleCacheLoaderConfig(boolean passivation, String preload, String cacheloaderClass, String properties, boolean async, boolean fetchPersistentState, boolean shared, boolean purgeOnStartup) throws Exception
+ {
+ String xml =
+ " <loaders passivation=\"" + passivation + "\" shared=\"" + shared + "\">\n" +
+ " <preload>\n" +
+ " <node fqn=\"" + preload + "\"/>\n" +
+ " </preload>\n" +
+ " <loader class=\"" + cacheloaderClass + "\" async=\"" + async + "\" fetchPersistentState=\"" + fetchPersistentState + "\"\n" +
+ " purgeOnStartup=\"" + purgeOnStartup + "\">\n" +
+ " <properties>\n" +
+ properties +
+ " </properties>\n" +
+ " </loader>\n" +
+ " </loaders>";
+ Element element = XmlConfigHelper.stringToElementInCoreNS(xml);
+ LoadersElementParser elementParser = new LoadersElementParser();
+ return elementParser.parseLoadersElement(element);
+ }
+
+ protected void checkLocks()
+ {
+ TreeCache<Object, Object> tree = cacheTL.get();
+ Cache<Object, Object> cache = tree.getCache();
+
+ assert TreeStructureSupport.isLocked(cache, C);
+ assert !cache.getConfiguration().isLockParentForChildInsertRemove() || TreeStructureSupport.isLocked(cache, A_B);
+ assert TreeStructureSupport.isLocked(cache, A_B_C);
+ }
+
+ protected void checkLocksDeep()
+ {
+ TreeCache<Object, Object> tree = cacheTL.get();
+ 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);
+ assert TreeStructureSupport.isLocked(cache, A_B_C_E);
+ }
+
+ protected void assertNoLocks()
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ ComponentRegistry cr = TestingUtil.extractComponentRegistry(cache.getCache());
+ LockManager lm = cr.getComponent(LockManager.class);
+ InvocationContextContainer icc = cr.getComponent(InvocationContextContainer.class);
+ LockAssert.assertNoLocks(lm, icc);
+ }
+
+ public void testNonexistentSource()
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ cache.put(A_B_C, "k", "v");
+ assert "v".equals(cache.get(A_B_C, "k"));
+ assert 1 == cache.getNode(A_B).getChildren().size();
+ assert cache.getNode(A_B).getChildrenNames().contains(C.getLastElement());
+ assert !cache.getNode(A_B).getChildrenNames().contains(D.getLastElement());
+
+ cache.move(D, A_B);
+
+ assert "v".equals(cache.get(A_B_C, "k"));
+ assert 1 == cache.getNode(A_B).getChildren().size();
+ assert cache.getNode(A_B).getChildrenNames().contains(C.getLastElement());
+ assert !cache.getNode(A_B).getChildrenNames().contains(D.getLastElement());
+ }
+
+ public void testNonexistentTarget()
+ {
+ TreeCache<Object, Object> cache = cacheTL.get();
+ cache.put(A_B_C, "k", "v");
+ assert "v".equals(cache.get(A_B_C, "k"));
+ assert 1 == cache.getNode(A_B).getChildren().size();
+ assert cache.getNode(A_B).getChildrenNames().contains(C.getLastElement());
+ assert null == cache.getNode(D);
+
+ System.out.println(TreeStructureSupport.printTree(cache, true));
+
+ cache.move(A_B, D);
+
+ System.out.println(TreeStructureSupport.printTree(cache, true));
+
+ assert null == cache.getNode(A_B_C);
+ assert null == cache.getNode(A_B);
+ assert null != cache.getNode(D);
+ assert null != cache.getNode(D_B);
+ assert null != cache.getNode(D_B_C);
+ assert "v".equals(cache.get(D_B_C, "k"));
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/NodeReplicatedMoveTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,160 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- *
- * Distributable under LGPL license.
- * See terms of license at gnu.org.
- */
-package org.jboss.starobrno.api.tree;
-
-import org.jboss.starobrno.UnitTestCacheFactory;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.transaction.DummyTransactionManagerLookup;
-import org.jboss.starobrno.tree.Fqn;
-import org.jboss.starobrno.tree.Node;
-import org.jboss.starobrno.tree.TreeCache;
-import org.jboss.starobrno.tree.TreeCacheImpl;
-import org.jboss.starobrno.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;
-
- at 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;
- }
-
- protected ThreadLocal<NodeReplicatedMoveTestTL> threadLocal = new ThreadLocal<NodeReplicatedMoveTestTL>();
-
- 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";
-
- @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());
- }
-
- @AfterMethod(alwaysRun = true)
- public void tearDown()
- {
- NodeReplicatedMoveTestTL tl = threadLocal.get();
- if (tl != null)
- {
- TestingUtil.killTreeCaches(tl.cache1, tl.cache2);
- threadLocal.set(null);
- }
- }
-
-
- public void testReplicatability()
- {
- NodeReplicatedMoveTestTL tl = threadLocal.get();
- Node<Object, Object> rootNode = tl.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));
-
- // now move...
- tl.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, tl.cache2.getRoot().getChild(A).get(k));
- assertEquals(vB, tl.cache2.getRoot().getChild(B).get(k));
- }
-
- public void testReplTxCommit() throws Exception
- {
- NodeReplicatedMoveTestTL tl = threadLocal.get();
- Node<Object, Object> rootNode = tl.cache1.getRoot();
- Fqn A_B = Fqn.fromRelativeFqn(A, B);
- 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));
-
- // now move...
- tl.tm.begin();
- tl.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, 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));
-
- }
-
- public void testReplTxRollback() throws Exception
- {
- NodeReplicatedMoveTestTL tl = threadLocal.get();
- Node<Object, Object> rootNode = tl.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));
-
- // now move...
- tl.tm.begin();
- tl.cache1.move(nodeB.getFqn(), Fqn.ROOT);
-
- assertEquals(vA, tl.cache1.get(A, k));
- assertEquals(vB, tl.cache1.get(B, k));
-
- tl.tm.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));
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/NodeReplicatedMoveTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,160 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.horizon.api.tree;
+
+import org.horizon.UnitTestCacheFactory;
+import org.horizon.config.Configuration;
+import org.horizon.transaction.DummyTransactionManagerLookup;
+import org.horizon.tree.Fqn;
+import org.horizon.tree.Node;
+import org.horizon.tree.TreeCache;
+import org.horizon.tree.TreeCacheImpl;
+import org.horizon.util.TestingUtil;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNull;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import javax.transaction.TransactionManager;
+
+ at 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;
+ }
+
+ protected ThreadLocal<NodeReplicatedMoveTestTL> threadLocal = new ThreadLocal<NodeReplicatedMoveTestTL>();
+
+ 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";
+
+ @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());
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown()
+ {
+ NodeReplicatedMoveTestTL tl = threadLocal.get();
+ if (tl != null)
+ {
+ TestingUtil.killTreeCaches(tl.cache1, tl.cache2);
+ threadLocal.set(null);
+ }
+ }
+
+
+ public void testReplicatability()
+ {
+ NodeReplicatedMoveTestTL tl = threadLocal.get();
+ Node<Object, Object> rootNode = tl.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));
+
+ // now move...
+ tl.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, tl.cache2.getRoot().getChild(A).get(k));
+ assertEquals(vB, tl.cache2.getRoot().getChild(B).get(k));
+ }
+
+ public void testReplTxCommit() throws Exception
+ {
+ NodeReplicatedMoveTestTL tl = threadLocal.get();
+ Node<Object, Object> rootNode = tl.cache1.getRoot();
+ Fqn A_B = Fqn.fromRelativeFqn(A, B);
+ 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));
+
+ // now move...
+ tl.tm.begin();
+ tl.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, 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));
+
+ }
+
+ public void testReplTxRollback() throws Exception
+ {
+ NodeReplicatedMoveTestTL tl = threadLocal.get();
+ Node<Object, Object> rootNode = tl.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));
+
+ // now move...
+ tl.tm.begin();
+ tl.cache1.move(nodeB.getFqn(), Fqn.ROOT);
+
+ assertEquals(vA, tl.cache1.get(A, k));
+ assertEquals(vB, tl.cache1.get(B, k));
+
+ tl.tm.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));
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/SyncReplTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,135 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- *
- * Distributable under LGPL license.
- * See terms of license at gnu.org.
- */
-
-package org.jboss.starobrno.api.tree;
-
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.CacheSPI;
-import org.jboss.starobrno.UnitTestCacheFactory;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.tree.Fqn;
-import org.jboss.starobrno.tree.Node;
-import org.jboss.starobrno.tree.TreeCache;
-import org.jboss.starobrno.tree.TreeCacheImpl;
-import org.jboss.starobrno.util.TestingUtil;
-import static org.testng.AssertJUnit.*;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @author <a href="mailto:manik AT jboss DOT org">Manik Surtani (manik AT jboss DOT org)</a>
- */
- at Test(groups = {"functional", "jgroups", "pessimistic"}, sequential = true, testName = "api.SyncReplTest")
-public class SyncReplTest
-{
- private CacheSPI<Object, Object> c1, c2;
- 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());
-
- 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);
-
- Fqn f = Fqn.fromString("/test/data");
- String k = "key", v = "value";
-
- assertNull("Should be null", cache1.getRoot().getChild(f));
- assertNull("Should be null", cache2.getRoot().getChild(f));
-
- Node<Object, Object> node = cache1.getRoot().addChild(f);
-
- assertNotNull("Should not be null", node);
-
- node.put(k, v);
-
- assertEquals(v, node.get(k));
- assertEquals(v, cache1.get(f, k));
- assert v.equals(cache2.get(f, k));
- }
-
- public void testSyncRepl()
- {
- 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.put(fqn, "age", 38);
- assertEquals("Value should be set", 38, cache1.get(fqn, "age"));
- assertEquals("Value should have replicated", 38, cache2.get(fqn, "age"));
- }
-
- public void testPutMap()
- {
- assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
-
- Fqn fqn = Fqn.fromString("/JSESSIONID/10.10.10.5:3000/1234567890/1");
- Fqn fqn1 = Fqn.fromString("/JSESSIONID/10.10.10.5:3000/1234567890/2");
-
- Map<Object, Object> map = new HashMap<Object, Object>();
- map.put("1", "1");
- map.put("2", "2");
- cache1.getInvocationContext().getOptionOverrides().setSuppressLocking(true);
- cache1.getRoot().addChild(fqn).putAll(map);
- cache1.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.getRoot().addChild(fqn1).putAll(map);
-
- cache1.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());
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/SyncReplTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,135 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+
+package org.horizon.api.tree;
+
+import org.horizon.Cache;
+import org.horizon.CacheSPI;
+import org.horizon.UnitTestCacheFactory;
+import org.horizon.config.Configuration;
+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;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author <a href="mailto:manik AT jboss DOT org">Manik Surtani (manik AT jboss DOT org)</a>
+ */
+ at Test(groups = {"functional", "jgroups", "pessimistic"}, sequential = true, testName = "api.SyncReplTest")
+public class SyncReplTest
+{
+ private CacheSPI<Object, Object> c1, c2;
+ 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());
+
+ 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);
+
+ Fqn f = Fqn.fromString("/test/data");
+ String k = "key", v = "value";
+
+ assertNull("Should be null", cache1.getRoot().getChild(f));
+ assertNull("Should be null", cache2.getRoot().getChild(f));
+
+ Node<Object, Object> node = cache1.getRoot().addChild(f);
+
+ assertNotNull("Should not be null", node);
+
+ node.put(k, v);
+
+ assertEquals(v, node.get(k));
+ assertEquals(v, cache1.get(f, k));
+ assert v.equals(cache2.get(f, k));
+ }
+
+ public void testSyncRepl()
+ {
+ 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.put(fqn, "age", 38);
+ assertEquals("Value should be set", 38, cache1.get(fqn, "age"));
+ assertEquals("Value should have replicated", 38, cache2.get(fqn, "age"));
+ }
+
+ public void testPutMap()
+ {
+ assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
+
+ Fqn fqn = Fqn.fromString("/JSESSIONID/10.10.10.5:3000/1234567890/1");
+ Fqn fqn1 = Fqn.fromString("/JSESSIONID/10.10.10.5:3000/1234567890/2");
+
+ Map<Object, Object> map = new HashMap<Object, Object>();
+ map.put("1", "1");
+ map.put("2", "2");
+ cache1.getInvocationContext().getOptionOverrides().setSuppressLocking(true);
+ cache1.getRoot().addChild(fqn).putAll(map);
+ cache1.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.getRoot().addChild(fqn1).putAll(map);
+
+ cache1.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());
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/SyncReplTxTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,117 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- *
- * Distributable under LGPL license.
- * See terms of license at gnu.org.
- */
-
-package org.jboss.starobrno.api.tree;
-
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.CacheSPI;
-import org.jboss.starobrno.UnitTestCacheFactory;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.transaction.DummyTransactionManagerLookup;
-import org.jboss.starobrno.tree.Fqn;
-import org.jboss.starobrno.tree.Node;
-import org.jboss.starobrno.tree.TreeCache;
-import org.jboss.starobrno.tree.TreeCacheImpl;
-import org.jboss.starobrno.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.*;
-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>
- */
- at 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;
-
- @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);
- c.setInvocationBatchingEnabled(true);
- c.setSyncCommitPhase(true);
- 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());
-
- flatCaches.add(cache1);
- flatCaches.add(cache2);
-
- TestingUtil.blockUntilViewsReceived(caches.toArray(new Cache[0]), 10000);
-
- caches.add(new TreeCacheImpl<Object, Object>(cache1));
- caches.add(new TreeCacheImpl<Object, Object>(cache2));
-
- System.out.println("*** Finished setUp()");
- }
-
- @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();
- mgr.begin();
- return mgr;
- }
-
- public void testBasicOperation() throws SystemException, NotSupportedException, HeuristicMixedException, HeuristicRollbackException, RollbackException
- {
- assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
-
- 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));
-
- Node<Object, Object> node = caches.get(0).getRoot().addChild(f);
-
- assertNotNull("Should not be null", node);
-
- TransactionManager tm = beginTransaction(caches.get(0).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));
- }
-
- 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.getMembers().size());
- }
-}
\ No newline at end of file
Copied: core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/SyncReplTxTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,117 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+
+package org.horizon.api.tree;
+
+import org.horizon.Cache;
+import org.horizon.CacheSPI;
+import org.horizon.UnitTestCacheFactory;
+import org.horizon.config.Configuration;
+import org.horizon.transaction.DummyTransactionManagerLookup;
+import org.horizon.tree.Fqn;
+import org.horizon.tree.Node;
+import org.horizon.tree.TreeCache;
+import org.horizon.tree.TreeCacheImpl;
+import org.horizon.util.TestingUtil;
+import static org.testng.AssertJUnit.*;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import javax.transaction.*;
+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>
+ */
+ at 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;
+
+ @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);
+ c.setInvocationBatchingEnabled(true);
+ c.setSyncCommitPhase(true);
+ 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());
+
+ flatCaches.add(cache1);
+ flatCaches.add(cache2);
+
+ TestingUtil.blockUntilViewsReceived(caches.toArray(new Cache[0]), 10000);
+
+ caches.add(new TreeCacheImpl<Object, Object>(cache1));
+ caches.add(new TreeCacheImpl<Object, Object>(cache2));
+
+ System.out.println("*** Finished setUp()");
+ }
+
+ @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();
+ mgr.begin();
+ return mgr;
+ }
+
+ public void testBasicOperation() throws SystemException, NotSupportedException, HeuristicMixedException, HeuristicRollbackException, RollbackException
+ {
+ assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
+
+ 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));
+
+ Node<Object, Object> node = caches.get(0).getRoot().addChild(f);
+
+ assertNotNull("Should not be null", node);
+
+ TransactionManager tm = beginTransaction(caches.get(0).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));
+ }
+
+ 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.getMembers().size());
+ }
+}
\ No newline at end of file
Deleted: core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/TreeCacheAPITest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,239 +0,0 @@
-package org.jboss.starobrno.api.tree;
-
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.CacheSPI;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.manager.CacheManager;
-import org.jboss.starobrno.transaction.DummyTransactionManagerLookup;
-import org.jboss.starobrno.tree.Fqn;
-import org.jboss.starobrno.tree.Node;
-import org.jboss.starobrno.tree.TreeCache;
-import org.jboss.starobrno.tree.TreeCacheImpl;
-import org.jboss.starobrno.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.TransactionManager;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Tests the {@link org.jboss.cache.Cache} public API at a high level
- *
- * @author <a href="mailto:manik AT jboss DOT org">Manik Surtani</a>
- */
-
- at Test(groups = {"functional", "pessimistic"}, sequential = true)
-public class TreeCacheAPITest
-{
- private TreeCache<String, String> cache;
- private TransactionManager tm;
-
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
- // start a single cache instance
- Configuration c = new Configuration();
- c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- c.setInvocationBatchingEnabled(true);
- CacheManager cm = new CacheManager(c);
-
- Cache flatcache = cm.getCache();
- cache = new TreeCacheImpl(flatcache);
-
- tm = ((CacheSPI) cache.getCache()).getTransactionManager();
- }
-
- @AfterMethod(alwaysRun = true)
- public void tearDown()
- {
- TestingUtil.killTreeCaches(cache);
- cache = null;
- }
-
- /**
- * All cache operations should happen on a {@link Node} - I.e., you look up a {@link Node} and perform data operations
- * on this {@link Node}. For convenience and familiarity with JBoss Cache 1.x, we provide some helpers in {@link Cache}
- * which dives you direct data access to nodes.
- * <p/>
- * This test exercises these.
- */
- public void testConvenienceMethods()
- {
- Fqn fqn = Fqn.fromString("/test/fqn");
- String key = "key", value = "value";
- Map<String, String> data = new HashMap<String, String>();
- data.put(key, value);
-
- assertNull(cache.get(fqn, key));
-
- cache.put(fqn, key, value);
-
- assertEquals(value, cache.get(fqn, key));
-
- cache.remove(fqn, key);
-
- assertNull(cache.get(fqn, key));
-
- cache.put(fqn, data);
-
- assertEquals(value, cache.get(fqn, key));
- }
-
-
- /**
- * Another convenience method that tests node removal
- */
- public void testNodeConvenienceNodeRemoval()
- {
- // this fqn is relative, but since it is from the root it may as well be absolute
- Fqn fqn = Fqn.fromString("/test/fqn");
- cache.getRoot().addChild(fqn);
- assertTrue(cache.getRoot().hasChild(fqn));
-
- assertEquals(true, cache.removeNode(fqn));
- assertFalse(cache.getRoot().hasChild(fqn));
- // remove should REALLY remove though and not just mark as deleted/invalid.
- Node n = cache.getNode(fqn);
- assert n == null;
-
- assertEquals(false, cache.removeNode(fqn));
-
- // remove should REALLY remove though and not just mark as deleted/invalid.
- n = cache.getNode(fqn);
- assert n == null;
-
- // Check that it's removed if it has a child
- Fqn child = Fqn.fromString("/test/fqn/child");
- cache.getRoot().addChild(child);
- assertTrue(cache.getRoot().hasChild(child));
-
- assertEquals(true, cache.removeNode(fqn));
- assertFalse(cache.getRoot().hasChild(fqn));
- assertEquals(false, cache.removeNode(fqn));
- }
-
- /**
- * Tests basic eviction
- */
- public void testEvict()
- {
- Fqn one = Fqn.fromString("/one");
- Fqn two = Fqn.fromString("/one/two");
- String key = "key", value = "value";
-
- cache.getRoot().addChild(one).put(key, value);
- cache.getRoot().addChild(two).put(key, value);
-
- assertTrue(cache.getRoot().hasChild(one));
- assertFalse(cache.getRoot().getChild(one).getData().isEmpty());
- assertTrue(cache.getRoot().hasChild(two));
- assertFalse(cache.getRoot().getChild(two).getData().isEmpty());
-
- // evict two
- cache.evict(two, false);
-
- assertTrue(cache.getRoot().hasChild(one));
- assertTrue(cache.getRoot().getChild(one).getKeys().contains(key));
- assertFalse(cache.getRoot().hasChild(two));
-
- // now add 2 again...
- cache.getRoot().addChild(two).put(key, value);
-
- // now evict one, NOT recursive
- cache.evict(one, false);
-
- // one will NOT be removed, just emptied.
- assertTrue(cache.getRoot().hasChild(one));
- assertFalse(cache.getRoot().getChild(one).getKeys().contains(key));
-
- // two will be unaffected
- assertTrue(cache.getRoot().hasChild(two));
- assertTrue(cache.getRoot().getChild(two).getKeys().contains(key));
- }
-
-
- /**
- * Tests recursive eviction
- */
- public void testEvictRecursive()
- {
- Fqn one = Fqn.fromString("/one");
- Fqn two = Fqn.fromString("/one/two");
- String key = "key", value = "value";
-
- cache.getRoot().addChild(one).put(key, value);
- cache.getRoot().addChild(two).put(key, value);
-
- assertTrue(cache.getRoot().hasChild(one));
- assertFalse(cache.getRoot().getChild(one).getData().isEmpty());
- assertTrue(cache.getRoot().hasChild(two));
- assertFalse(cache.getRoot().getChild(two).getData().isEmpty());
-
- // evict two
- cache.evict(two, true);
-
- assertTrue(cache.getRoot().hasChild(one));
- assertFalse(cache.getRoot().getChild(one).getData().isEmpty());
- assertFalse(cache.getRoot().hasChild(two));
-
- // now add 2 again...
- cache.getRoot().addChild(two).put(key, value);
-
- // now evict one, recursive
- cache.evict(one, true);
-
- assertFalse(cache.getRoot().hasChild(one));
- assertFalse(cache.getRoot().hasChild(two));
- }
-
- public void testStopClearsData() throws Exception
- {
- Fqn a = Fqn.fromString("/a");
- Fqn b = Fqn.fromString("/a/b");
- String key = "key", value = "value";
- cache.getRoot().addChild(a).put(key, value);
- cache.getRoot().addChild(b).put(key, value);
- cache.getRoot().put(key, value);
-
- assertEquals(value, cache.getRoot().get(key));
- assertEquals(value, cache.getRoot().getChild(a).get(key));
- assertEquals(value, cache.getRoot().getChild(b).get(key));
-
- cache.stop();
-
- cache.start();
-
- assertNull(cache.getRoot().get(key));
- assertTrue(cache.getRoot().getData().isEmpty());
- assertTrue(cache.getRoot().getChildren().isEmpty());
- }
-
- public void testPhantomStructuralNodesOnRemove()
- {
- assert cache.getNode(Fqn.fromString("/a/b/c")) == null;
- assert !cache.removeNode("/a/b/c");
- assert cache.getNode(Fqn.fromString("/a/b/c")) == null;
- assert cache.getNode(Fqn.fromString("/a/b")) == null;
- assert cache.getNode(Fqn.fromString("/a")) == null;
- }
-
- public void testPhantomStructuralNodesOnRemoveTransactional() throws Exception
- {
- assert cache.getNode(Fqn.fromString("/a/b/c")) == null;
- tm.begin();
- assert !cache.removeNode("/a/b/c");
- tm.commit();
- assert cache.getNode(Fqn.fromString("/a/b/c")) == null;
- assert cache.getNode(Fqn.fromString("/a/b")) == null;
- assert cache.getNode(Fqn.fromString("/a")) == null;
- }
-
- public void testRpcManagerElements()
- {
- assertEquals("CacheMode.LOCAL cache has no address", null, cache.getLocalAddress());
- assertEquals("CacheMode.LOCAL cache has no members list", null, cache.getMembers());
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/TreeCacheAPITest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,239 @@
+package org.horizon.api.tree;
+
+import org.horizon.Cache;
+import org.horizon.CacheSPI;
+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;
+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;
+
+import javax.transaction.TransactionManager;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Tests the {@link TreeCache} public API at a high level
+ *
+ * @author <a href="mailto:manik AT jboss DOT org">Manik Surtani</a>
+ */
+
+ at Test(groups = "functional", sequential = true)
+public class TreeCacheAPITest
+{
+ private TreeCache<String, String> cache;
+ private TransactionManager tm;
+
+ @BeforeMethod(alwaysRun = true)
+ public void setUp() throws Exception
+ {
+ // start a single cache instance
+ Configuration c = new Configuration();
+ c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ c.setInvocationBatchingEnabled(true);
+ CacheManager cm = new CacheManager(c);
+
+ Cache flatcache = cm.getCache();
+ cache = new TreeCacheImpl(flatcache);
+
+ tm = ((CacheSPI) cache.getCache()).getTransactionManager();
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown()
+ {
+ TestingUtil.killTreeCaches(cache);
+ cache = null;
+ }
+
+ /**
+ * All cache operations should happen on a {@link Node} - I.e., you look up a {@link Node} and perform data operations
+ * on this {@link Node}. For convenience and familiarity with JBoss Cache 1.x, we provide some helpers in {@link Cache}
+ * which dives you direct data access to nodes.
+ * <p/>
+ * This test exercises these.
+ */
+ public void testConvenienceMethods()
+ {
+ Fqn fqn = Fqn.fromString("/test/fqn");
+ String key = "key", value = "value";
+ Map<String, String> data = new HashMap<String, String>();
+ data.put(key, value);
+
+ assertNull(cache.get(fqn, key));
+
+ cache.put(fqn, key, value);
+
+ assertEquals(value, cache.get(fqn, key));
+
+ cache.remove(fqn, key);
+
+ assertNull(cache.get(fqn, key));
+
+ cache.put(fqn, data);
+
+ assertEquals(value, cache.get(fqn, key));
+ }
+
+
+ /**
+ * Another convenience method that tests node removal
+ */
+ public void testNodeConvenienceNodeRemoval()
+ {
+ // this fqn is relative, but since it is from the root it may as well be absolute
+ Fqn fqn = Fqn.fromString("/test/fqn");
+ cache.getRoot().addChild(fqn);
+ assertTrue(cache.getRoot().hasChild(fqn));
+
+ assertEquals(true, cache.removeNode(fqn));
+ assertFalse(cache.getRoot().hasChild(fqn));
+ // remove should REALLY remove though and not just mark as deleted/invalid.
+ Node n = cache.getNode(fqn);
+ assert n == null;
+
+ assertEquals(false, cache.removeNode(fqn));
+
+ // remove should REALLY remove though and not just mark as deleted/invalid.
+ n = cache.getNode(fqn);
+ assert n == null;
+
+ // Check that it's removed if it has a child
+ Fqn child = Fqn.fromString("/test/fqn/child");
+ cache.getRoot().addChild(child);
+ assertTrue(cache.getRoot().hasChild(child));
+
+ assertEquals(true, cache.removeNode(fqn));
+ assertFalse(cache.getRoot().hasChild(fqn));
+ assertEquals(false, cache.removeNode(fqn));
+ }
+
+ /**
+ * Tests basic eviction
+ */
+ public void testEvict()
+ {
+ Fqn one = Fqn.fromString("/one");
+ Fqn two = Fqn.fromString("/one/two");
+ String key = "key", value = "value";
+
+ cache.getRoot().addChild(one).put(key, value);
+ cache.getRoot().addChild(two).put(key, value);
+
+ assertTrue(cache.getRoot().hasChild(one));
+ assertFalse(cache.getRoot().getChild(one).getData().isEmpty());
+ assertTrue(cache.getRoot().hasChild(two));
+ assertFalse(cache.getRoot().getChild(two).getData().isEmpty());
+
+ // evict two
+ cache.evict(two, false);
+
+ assertTrue(cache.getRoot().hasChild(one));
+ assertTrue(cache.getRoot().getChild(one).getKeys().contains(key));
+ assertFalse(cache.getRoot().hasChild(two));
+
+ // now add 2 again...
+ cache.getRoot().addChild(two).put(key, value);
+
+ // now evict one, NOT recursive
+ cache.evict(one, false);
+
+ // one will NOT be removed, just emptied.
+ assertTrue(cache.getRoot().hasChild(one));
+ assertFalse(cache.getRoot().getChild(one).getKeys().contains(key));
+
+ // two will be unaffected
+ assertTrue(cache.getRoot().hasChild(two));
+ assertTrue(cache.getRoot().getChild(two).getKeys().contains(key));
+ }
+
+
+ /**
+ * Tests recursive eviction
+ */
+ public void testEvictRecursive()
+ {
+ Fqn one = Fqn.fromString("/one");
+ Fqn two = Fqn.fromString("/one/two");
+ String key = "key", value = "value";
+
+ cache.getRoot().addChild(one).put(key, value);
+ cache.getRoot().addChild(two).put(key, value);
+
+ assertTrue(cache.getRoot().hasChild(one));
+ assertFalse(cache.getRoot().getChild(one).getData().isEmpty());
+ assertTrue(cache.getRoot().hasChild(two));
+ assertFalse(cache.getRoot().getChild(two).getData().isEmpty());
+
+ // evict two
+ cache.evict(two, true);
+
+ assertTrue(cache.getRoot().hasChild(one));
+ assertFalse(cache.getRoot().getChild(one).getData().isEmpty());
+ assertFalse(cache.getRoot().hasChild(two));
+
+ // now add 2 again...
+ cache.getRoot().addChild(two).put(key, value);
+
+ // now evict one, recursive
+ cache.evict(one, true);
+
+ assertFalse(cache.getRoot().hasChild(one));
+ assertFalse(cache.getRoot().hasChild(two));
+ }
+
+ public void testStopClearsData() throws Exception
+ {
+ Fqn a = Fqn.fromString("/a");
+ Fqn b = Fqn.fromString("/a/b");
+ String key = "key", value = "value";
+ cache.getRoot().addChild(a).put(key, value);
+ cache.getRoot().addChild(b).put(key, value);
+ cache.getRoot().put(key, value);
+
+ assertEquals(value, cache.getRoot().get(key));
+ assertEquals(value, cache.getRoot().getChild(a).get(key));
+ assertEquals(value, cache.getRoot().getChild(b).get(key));
+
+ cache.stop();
+
+ cache.start();
+
+ assertNull(cache.getRoot().get(key));
+ assertTrue(cache.getRoot().getData().isEmpty());
+ assertTrue(cache.getRoot().getChildren().isEmpty());
+ }
+
+ public void testPhantomStructuralNodesOnRemove()
+ {
+ assert cache.getNode(Fqn.fromString("/a/b/c")) == null;
+ assert !cache.removeNode("/a/b/c");
+ assert cache.getNode(Fqn.fromString("/a/b/c")) == null;
+ assert cache.getNode(Fqn.fromString("/a/b")) == null;
+ assert cache.getNode(Fqn.fromString("/a")) == null;
+ }
+
+ public void testPhantomStructuralNodesOnRemoveTransactional() throws Exception
+ {
+ assert cache.getNode(Fqn.fromString("/a/b/c")) == null;
+ tm.begin();
+ assert !cache.removeNode("/a/b/c");
+ tm.commit();
+ assert cache.getNode(Fqn.fromString("/a/b/c")) == null;
+ assert cache.getNode(Fqn.fromString("/a/b")) == null;
+ assert cache.getNode(Fqn.fromString("/a")) == null;
+ }
+
+ public void testRpcManagerElements()
+ {
+ assertEquals("CacheMode.LOCAL cache has no address", null, cache.getLocalAddress());
+ assertEquals("CacheMode.LOCAL cache has no members list", null, cache.getMembers());
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/api/tree/TreeStructureHashCodeTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/TreeStructureHashCodeTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/TreeStructureHashCodeTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,64 +0,0 @@
-package org.jboss.starobrno.api.tree;
-
-import org.jboss.starobrno.tree.Fqn;
-import org.jboss.starobrno.tree.NodeKey;
-import org.jboss.starobrno.util.concurrent.locks.LockContainer;
-import org.jboss.starobrno.util.concurrent.locks.ReentrantLockContainer;
-import org.testng.annotations.Test;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.locks.Lock;
-
-/**
- * Tests the degree to which hash codes get spread
- */
- at Test
-public class TreeStructureHashCodeTest
-{
- public void testHashCodesAppendedCount()
- {
- List<Fqn> fqns = new ArrayList<Fqn>();
- fqns.add(Fqn.ROOT);
- for (int i = 0; i < 256; i++) fqns.add(Fqn.fromString("/fqn" + i));
- doTest(fqns);
- }
-
- public void testHashCodesAlpha()
- {
- List<Fqn> fqns = new ArrayList<Fqn>();
- fqns.add(Fqn.ROOT);
- for (int i = 0; i < 256; i++) fqns.add(Fqn.fromString("/" + Integer.toString(i, 36)));
- doTest(fqns);
- }
-
- private void doTest(List<Fqn> fqns)
- {
- LockContainer<NodeKey> container = new ReentrantLockContainer<NodeKey>(512);
- Map<Lock, Integer> distribution = new HashMap<Lock, Integer>();
- for (Fqn f : fqns)
- {
- NodeKey dataKey = new NodeKey(f, NodeKey.Type.DATA);
- NodeKey structureKey = new NodeKey(f, NodeKey.Type.STRUCTURE);
- addToDistribution(container.getLock(dataKey), distribution);
- addToDistribution(container.getLock(structureKey), distribution);
- }
-
- System.out.println("Distribution: " + distribution);
- assert distribution.size() <= container.size() : "Cannot have more locks than the container size!";
- // assume at least a 2/3rd even distribution
- // but also consider that data snd structure keys would typically provide the same hash code
- // so we need to double this
- assert distribution.size() * 1.5 * 2 >= container.size() : "Poorly distributed! Distribution size is just " + distribution.size() + " and there are " + container.size() + " shared locks";
-
- }
-
- private void addToDistribution(Lock lock, Map<Lock, Integer> map)
- {
- int count = 1;
- if (map.containsKey(lock)) count = map.get(lock) + 1;
- map.put(lock, count);
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/api/tree/TreeStructureHashCodeTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/api/tree/TreeStructureHashCodeTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/TreeStructureHashCodeTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/TreeStructureHashCodeTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,64 @@
+package org.horizon.api.tree;
+
+import org.horizon.tree.Fqn;
+import org.horizon.tree.NodeKey;
+import org.horizon.util.concurrent.locks.LockContainer;
+import org.horizon.util.concurrent.locks.ReentrantLockContainer;
+import org.testng.annotations.Test;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.locks.Lock;
+
+/**
+ * Tests the degree to which hash codes get spread
+ */
+ at Test
+public class TreeStructureHashCodeTest
+{
+ public void testHashCodesAppendedCount()
+ {
+ List<Fqn> fqns = new ArrayList<Fqn>();
+ fqns.add(Fqn.ROOT);
+ for (int i = 0; i < 256; i++) fqns.add(Fqn.fromString("/fqn" + i));
+ doTest(fqns);
+ }
+
+ public void testHashCodesAlpha()
+ {
+ List<Fqn> fqns = new ArrayList<Fqn>();
+ fqns.add(Fqn.ROOT);
+ for (int i = 0; i < 256; i++) fqns.add(Fqn.fromString("/" + Integer.toString(i, 36)));
+ doTest(fqns);
+ }
+
+ private void doTest(List<Fqn> fqns)
+ {
+ LockContainer<NodeKey> container = new ReentrantLockContainer<NodeKey>(512);
+ Map<Lock, Integer> distribution = new HashMap<Lock, Integer>();
+ for (Fqn f : fqns)
+ {
+ NodeKey dataKey = new NodeKey(f, NodeKey.Type.DATA);
+ NodeKey structureKey = new NodeKey(f, NodeKey.Type.STRUCTURE);
+ addToDistribution(container.getLock(dataKey), distribution);
+ addToDistribution(container.getLock(structureKey), distribution);
+ }
+
+ System.out.println("Distribution: " + distribution);
+ assert distribution.size() <= container.size() : "Cannot have more locks than the container size!";
+ // assume at least a 2/3rd even distribution
+ // but also consider that data snd structure keys would typically provide the same hash code
+ // so we need to double this
+ assert distribution.size() * 1.5 * 2 >= container.size() : "Poorly distributed! Distribution size is just " + distribution.size() + " and there are " + container.size() + " shared locks";
+
+ }
+
+ private void addToDistribution(Lock lock, Map<Lock, Integer> map)
+ {
+ int count = 1;
+ if (map.containsKey(lock)) count = map.get(lock) + 1;
+ map.put(lock, count);
+ }
+}
Copied: core/branches/flat/src/test/java/org/horizon/factories (from rev 7484, core/branches/flat/src/test/java/org/jboss/starobrno/factories)
Copied: core/branches/flat/src/test/java/org/horizon/profiling (from rev 7484, core/branches/flat/src/test/java/org/jboss/starobrno/profiling)
Deleted: core/branches/flat/src/test/java/org/horizon/profiling/AbstractProfileTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/profiling/AbstractProfileTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/profiling/AbstractProfileTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,31 +0,0 @@
-package org.jboss.starobrno.profiling;
-
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.util.TestingUtil;
-import org.testng.annotations.AfterTest;
-import org.testng.annotations.BeforeTest;
-import org.testng.annotations.Test;
-
-import java.util.Map;
-import org.jboss.starobrno.UnitTestCacheFactory;
-
- at Test(groups = "profiling")
-public abstract class AbstractProfileTest
-{
- protected Map cache;
-
- @BeforeTest
- public void setUp()
- {
- Configuration cfg = new Configuration();
- cache = new UnitTestCacheFactory().createCache(cfg, false);
- }
-
- @AfterTest
- public void tearDown()
- {
- TestingUtil.killCaches((Cache) cache);
- cache = null;
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/profiling/AbstractProfileTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/profiling/AbstractProfileTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/AbstractProfileTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/profiling/AbstractProfileTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,31 @@
+package org.horizon.profiling;
+
+import org.horizon.Cache;
+import org.horizon.config.Configuration;
+import org.horizon.util.TestingUtil;
+import org.testng.annotations.AfterTest;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Test;
+
+import java.util.Map;
+import org.horizon.UnitTestCacheFactory;
+
+ at Test(groups = "profiling")
+public abstract class AbstractProfileTest
+{
+ protected Map cache;
+
+ @BeforeTest
+ public void setUp()
+ {
+ Configuration cfg = new Configuration();
+ cache = new UnitTestCacheFactory().createCache(cfg, false);
+ }
+
+ @AfterTest
+ public void tearDown()
+ {
+ TestingUtil.killCaches((Cache) cache);
+ cache = null;
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/profiling/MemConsumptionTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/profiling/MemConsumptionTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/profiling/MemConsumptionTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,127 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.starobrno.profiling;
-
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.CacheException;
-import org.jboss.starobrno.manager.CacheManager;
-import org.jboss.starobrno.util.TestingUtil;
-import org.testng.annotations.Test;
-
-import java.io.IOException;
-import java.text.NumberFormat;
-import java.util.Arrays;
-import java.util.Random;
-
- at Test(groups = "profiling", enabled = false)
-public class MemConsumptionTest
-{
- // adjust the next 4 values
- int numEntries = 1000000;
- int payloadSize = 60; // bytes
- int keySize = 10; // bytes
- PayloadType payloadType = PayloadType.STRINGS;
-
- enum PayloadType
- {
- STRINGS, BYTE_ARRAYS
- }
-
- int bytesPerCharacter = 2;
-
- Random r = new Random();
-
- public void testMemConsumption() throws IOException
- {
- int kBytesCached = (bytesPerCharacter * numEntries * (payloadSize + keySize)) / 1024;
- System.out.println("Bytes to be cached: " + NumberFormat.getIntegerInstance().format(kBytesCached) + " kb");
-
- Cache c = new CacheManager().getCache();
- for (int i = 0; i < numEntries; i++)
- {
- switch (payloadType)
- {
- case STRINGS:
- c.put(generateUniqueString(i, keySize), generateRandomString(payloadSize));
- break;
- case BYTE_ARRAYS:
- c.put(generateUniqueKey(i, keySize), generateBytePayload(payloadSize));
- break;
- default:
- throw new CacheException("Unknown payload type");
- }
-
-
- if (i % 1000 == 0) System.out.println("Added " + i + " entries");
- }
-
- System.out.println("Calling System.gc()");
- System.gc(); // clear any unnecessary objects
-
- TestingUtil.sleepThread(1000); // wait for gc
-
- // wait for manual test exit
- System.out.println("Cache populated; check mem usage using jconsole, etc.!");
- System.in.read();
- }
-
- private String generateUniqueString(int runNumber, int keySize)
- {
- // string size should be exactly equal to key size but also be unique.
- // start by creating a string from the run number
- StringBuilder sb = new StringBuilder();
- // append the run number
- sb.append(runNumber);
- for (int i = sb.length(); i < keySize; i++) sb.append("_");
- return sb.toString();
- }
-
- private byte[] generateUniqueKey(int runNumber, int keySize)
- {
- byte[] b = new byte[keySize];
- b[0] = (byte) (runNumber >>> 0);
- b[1] = (byte) (runNumber >>> 8);
- b[2] = (byte) (runNumber >>> 16);
- b[3] = (byte) (runNumber >>> 24);
-
- for (int i = 4; i < keySize; i++) b[i] = 0;
- return b;
- }
-
- private byte[] generateBytePayload(int payloadSize)
- {
- byte[] b = new byte[payloadSize];
- Arrays.fill(b, (byte) 0);
- return b;
- }
-
- private String generateRandomString(int stringSize)
- {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < stringSize; i++)
- {
- sb.append(r.nextInt(9)); // single digit
- }
- assert sb.length() == stringSize;
- return sb.toString();
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/profiling/MemConsumptionTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/profiling/MemConsumptionTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/MemConsumptionTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/profiling/MemConsumptionTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,127 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.horizon.profiling;
+
+import org.horizon.Cache;
+import org.horizon.CacheException;
+import org.horizon.manager.CacheManager;
+import org.horizon.util.TestingUtil;
+import org.testng.annotations.Test;
+
+import java.io.IOException;
+import java.text.NumberFormat;
+import java.util.Arrays;
+import java.util.Random;
+
+ at Test(groups = "profiling", enabled = false)
+public class MemConsumptionTest
+{
+ // adjust the next 4 values
+ int numEntries = 1000000;
+ int payloadSize = 60; // bytes
+ int keySize = 10; // bytes
+ PayloadType payloadType = PayloadType.STRINGS;
+
+ enum PayloadType
+ {
+ STRINGS, BYTE_ARRAYS
+ }
+
+ int bytesPerCharacter = 2;
+
+ Random r = new Random();
+
+ public void testMemConsumption() throws IOException
+ {
+ int kBytesCached = (bytesPerCharacter * numEntries * (payloadSize + keySize)) / 1024;
+ System.out.println("Bytes to be cached: " + NumberFormat.getIntegerInstance().format(kBytesCached) + " kb");
+
+ Cache c = new CacheManager().getCache();
+ for (int i = 0; i < numEntries; i++)
+ {
+ switch (payloadType)
+ {
+ case STRINGS:
+ c.put(generateUniqueString(i, keySize), generateRandomString(payloadSize));
+ break;
+ case BYTE_ARRAYS:
+ c.put(generateUniqueKey(i, keySize), generateBytePayload(payloadSize));
+ break;
+ default:
+ throw new CacheException("Unknown payload type");
+ }
+
+
+ if (i % 1000 == 0) System.out.println("Added " + i + " entries");
+ }
+
+ System.out.println("Calling System.gc()");
+ System.gc(); // clear any unnecessary objects
+
+ TestingUtil.sleepThread(1000); // wait for gc
+
+ // wait for manual test exit
+ System.out.println("Cache populated; check mem usage using jconsole, etc.!");
+ System.in.read();
+ }
+
+ private String generateUniqueString(int runNumber, int keySize)
+ {
+ // string size should be exactly equal to key size but also be unique.
+ // start by creating a string from the run number
+ StringBuilder sb = new StringBuilder();
+ // append the run number
+ sb.append(runNumber);
+ for (int i = sb.length(); i < keySize; i++) sb.append("_");
+ return sb.toString();
+ }
+
+ private byte[] generateUniqueKey(int runNumber, int keySize)
+ {
+ byte[] b = new byte[keySize];
+ b[0] = (byte) (runNumber >>> 0);
+ b[1] = (byte) (runNumber >>> 8);
+ b[2] = (byte) (runNumber >>> 16);
+ b[3] = (byte) (runNumber >>> 24);
+
+ for (int i = 4; i < keySize; i++) b[i] = 0;
+ return b;
+ }
+
+ private byte[] generateBytePayload(int payloadSize)
+ {
+ byte[] b = new byte[payloadSize];
+ Arrays.fill(b, (byte) 0);
+ return b;
+ }
+
+ private String generateRandomString(int stringSize)
+ {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < stringSize; i++)
+ {
+ sb.append(r.nextInt(9)); // single digit
+ }
+ assert sb.length() == stringSize;
+ return sb.toString();
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/profiling/ProfileTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/profiling/ProfileTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/profiling/ProfileTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,291 +0,0 @@
-package org.jboss.starobrno.profiling;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.cache.lock.IsolationLevel;
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.profiling.testinternals.Generator;
-import org.jboss.starobrno.profiling.testinternals.TaskRunner;
-import org.jboss.starobrno.util.TestingUtil;
-import org.testng.annotations.Test;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * Test to use with a profiler to profile replication. To be used in conjunction with ProfileSlaveTest.
- * <p/>
- * Typical usage pattern:
- * <p/>
- * 1. Start a single test method in ProfileSlaveTest. This will block until you kill it.
- * 2. Start the corresponding test in this class, with the same name, in a different JVM, and attached to a profiler.
- * 3. Profile away!
- * <p/>
- *
- * @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
- * @since 2.1.0
- */
- at Test(groups = "profiling", sequential = true, enabled = false)
-public class ProfileTest extends AbstractProfileTest
-{
- /*
- Test configuration options
- */
- protected static final long NUM_OPERATIONS = 1000000; // DURATION is replaced with a fixed number of operations instead.
- protected static final int NUM_THREADS = 25;
- protected static final int MAX_RANDOM_SLEEP_MILLIS = 1;
- protected static final int MAX_OVERALL_KEYS = 2000;
- protected static final int WARMUP_LOOPS = 20000;
- protected static final boolean USE_SLEEP = false; // throttle generation a bit
-
- private List<Object> keys = new ArrayList<Object>(MAX_OVERALL_KEYS);
-
- Log log = LogFactory.getLog(ProfileTest.class);
-
- @Test(enabled = true)
- public void testLocalMode() throws Exception
- {
- Cache c = (Cache) cache;
- c.getConfiguration().setCacheMode(Configuration.CacheMode.LOCAL);
- c.getConfiguration().setConcurrencyLevel(2000);
- c.getConfiguration().setIsolationLevel(IsolationLevel.REPEATABLE_READ);
- runCompleteTest();
- }
-
- private void runCompleteTest() throws Exception
- {
- init();
- startup();
- warmup();
- doTest();
-
- // wait for user exit
- System.in.read();
- }
-
- /**
- * Thr following test phases can be profiled individually using triggers in JProfiler.
- */
-
- protected void init()
- {
- long startTime = System.currentTimeMillis();
- log.warn("Starting init() phase");
- keys.clear();
- for (int i = 0; i < MAX_OVERALL_KEYS; i++)
- {
- Object key;
- do
- {
- key = Generator.createRandomKey();
- }
- while (keys.contains(key));
-
- if (i % 10 == 0)
- {
- log.warn("Generated " + i + " keys");
- }
- keys.add(key);
- }
- System.gc();
- long duration = System.currentTimeMillis() - startTime;
- log.warn("Finished init() phase. " + printDuration(duration));
- }
-
-
- protected void startup()
- {
- long startTime = System.currentTimeMillis();
- log.warn("Starting cache");
- ((Cache) cache).start();
- long duration = System.currentTimeMillis() - startTime;
- log.warn("Started cache. " + printDuration(duration));
- }
-
- private void warmup() throws InterruptedException
- {
- long startTime = System.currentTimeMillis();
- TaskRunner exec = new TaskRunner(NUM_THREADS);
- log.warn("Starting warmup");
- // creates all the Fqns since this can be expensive and we don't really want to measure this (for now)
- for (final Object key : keys)
- {
- exec.execute(new Runnable()
- {
- public void run()
- {
- // this will create the necessary nodes.
- cache.put(key, Collections.emptyMap());
- }
- });
- }
-
- // loop through WARMUP_LOOPS gets and puts for JVM optimisation
- for (int i = 0; i < WARMUP_LOOPS; i++)
- {
- exec.execute(new Runnable()
- {
- public void run()
- {
- Object key = Generator.getRandomElement(keys);
- cache.get(key);
- cache.put(key, "Value");
- cache.remove(key);
- }
- });
- }
-
- exec.stop();
-
- long duration = System.currentTimeMillis() - startTime;
- log.warn("Finished warmup. " + printDuration(duration));
- //cache.removeNode(Fqn.ROOT);
- ((Cache) cache).stop();
-
- startup();
- }
-
- private void doTest() throws Exception
- {
- TaskRunner exec = new TaskRunner(NUM_THREADS);
- log.warn("Starting test");
- int i;
- long print = NUM_OPERATIONS / 10;
-
- AtomicLong durationPuts = new AtomicLong();
- AtomicLong durationGets = new AtomicLong();
- AtomicLong durationRemoves = new AtomicLong();
-
- long stElapsed = System.nanoTime();
- for (i = 0; i < NUM_OPERATIONS; i++)
- {
- MyRunnable r = null;
- switch (i % 3)
- {
- case 0:
- r = new Putter(i, durationPuts);
- break;
- case 1:
- r = new Getter(i, durationGets);
- break;
- case 2:
- r = new Remover(i, durationRemoves);
- break;
- }
- if (i % print == 0)
- log.warn("processing iteration " + i);
- exec.execute(r);
-// if (USE_SLEEP) TestingUtil.sleepRandom(MAX_RANDOM_SLEEP_MILLIS);
- if (USE_SLEEP) TestingUtil.sleepThread(MAX_RANDOM_SLEEP_MILLIS);
- }
- log.warn("Finished generating runnables; awaiting executor completion");
- // wait for executors to complete!
- exec.stop();
-
- // wait up to 1 sec for each call?
- long elapsedTimeNanos = System.nanoTime() - stElapsed;
-
- log.warn("Finished test. " + printDuration((long) toMillis(elapsedTimeNanos)));
- log.warn("Throughput: " + ((double) NUM_OPERATIONS * 1000 / toMillis(elapsedTimeNanos)) + " operations per second (roughly equal numbers of PUT, GET and REMOVE)");
- log.warn("Average GET time: " + printAvg(durationGets.get()));
- log.warn("Average PUT time: " + printAvg(durationPuts.get()));
- log.warn("Average REMOVE time: " + printAvg(durationRemoves.get()));
- }
-
- private String printAvg(long totalNanos)
- {
- double nOps = (double) (NUM_OPERATIONS / 3);
- double avg = ((double) totalNanos) / nOps;
- double avgMicros = avg / 1000;
- return avgMicros + " µs";
- }
-
- private double toMillis(long nanos)
- {
- return ((double) nanos / (double) 1000000);
- }
-
- enum Mode
- {
- PUT, GET, REMOVE
- }
-
- private abstract class MyRunnable implements Runnable
- {
- int id;
- Mode mode;
- AtomicLong duration;
-
- public void run()
- {
- Object key = Generator.getRandomElement(keys);
- long d = 0, st = 0;
- switch (mode)
- {
- case PUT:
- Object value = Generator.getRandomString();
- st = System.nanoTime();
- cache.put(key, value);
- d = System.nanoTime() - st;
- break;
- case GET:
- st = System.nanoTime();
- cache.get(key);
- d = System.nanoTime() - st;
- break;
- case REMOVE:
- st = System.nanoTime();
- cache.remove(key);
- d = System.nanoTime() - st;
- break;
- }
- duration.getAndAdd(d);
- }
- }
-
- private class Putter extends MyRunnable
- {
- private Putter(int id, AtomicLong duration)
- {
- this.id = id;
- this.duration = duration;
- mode = Mode.PUT;
- }
- }
-
- private class Getter extends MyRunnable
- {
- private Getter(int id, AtomicLong duration)
- {
- this.id = id;
- this.duration = duration;
- mode = Mode.GET;
- }
- }
-
- private class Remover extends MyRunnable
- {
- private Remover(int id, AtomicLong duration)
- {
- this.id = id;
- this.duration = duration;
- mode = Mode.REMOVE;
- }
- }
-
- protected String printDuration(long duration)
- {
- if (duration > 2000)
- {
- double dSecs = ((double) duration / (double) 1000);
- return "Duration: " + dSecs + " seconds";
- }
- else
- {
- return "Duration: " + duration + " millis";
- }
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/profiling/ProfileTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/profiling/ProfileTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/ProfileTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/profiling/ProfileTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,291 @@
+package org.horizon.profiling;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.horizon.lock.IsolationLevel;
+import org.horizon.Cache;
+import org.horizon.config.Configuration;
+import org.horizon.profiling.testinternals.Generator;
+import org.horizon.profiling.testinternals.TaskRunner;
+import org.horizon.util.TestingUtil;
+import org.testng.annotations.Test;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * Test to use with a profiler to profile replication. To be used in conjunction with ProfileSlaveTest.
+ * <p/>
+ * Typical usage pattern:
+ * <p/>
+ * 1. Start a single test method in ProfileSlaveTest. This will block until you kill it.
+ * 2. Start the corresponding test in this class, with the same name, in a different JVM, and attached to a profiler.
+ * 3. Profile away!
+ * <p/>
+ *
+ * @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
+ * @since 2.1.0
+ */
+ at Test(groups = "profiling", sequential = true, enabled = false)
+public class ProfileTest extends AbstractProfileTest
+{
+ /*
+ Test configuration options
+ */
+ protected static final long NUM_OPERATIONS = 1000000; // DURATION is replaced with a fixed number of operations instead.
+ protected static final int NUM_THREADS = 25;
+ protected static final int MAX_RANDOM_SLEEP_MILLIS = 1;
+ protected static final int MAX_OVERALL_KEYS = 2000;
+ protected static final int WARMUP_LOOPS = 20000;
+ protected static final boolean USE_SLEEP = false; // throttle generation a bit
+
+ private List<Object> keys = new ArrayList<Object>(MAX_OVERALL_KEYS);
+
+ Log log = LogFactory.getLog(ProfileTest.class);
+
+ @Test(enabled = true)
+ public void testLocalMode() throws Exception
+ {
+ Cache c = (Cache) cache;
+ c.getConfiguration().setCacheMode(Configuration.CacheMode.LOCAL);
+ c.getConfiguration().setConcurrencyLevel(2000);
+ c.getConfiguration().setIsolationLevel(IsolationLevel.REPEATABLE_READ);
+ runCompleteTest();
+ }
+
+ private void runCompleteTest() throws Exception
+ {
+ init();
+ startup();
+ warmup();
+ doTest();
+
+ // wait for user exit
+ System.in.read();
+ }
+
+ /**
+ * Thr following test phases can be profiled individually using triggers in JProfiler.
+ */
+
+ protected void init()
+ {
+ long startTime = System.currentTimeMillis();
+ log.warn("Starting init() phase");
+ keys.clear();
+ for (int i = 0; i < MAX_OVERALL_KEYS; i++)
+ {
+ Object key;
+ do
+ {
+ key = Generator.createRandomKey();
+ }
+ while (keys.contains(key));
+
+ if (i % 10 == 0)
+ {
+ log.warn("Generated " + i + " keys");
+ }
+ keys.add(key);
+ }
+ System.gc();
+ long duration = System.currentTimeMillis() - startTime;
+ log.warn("Finished init() phase. " + printDuration(duration));
+ }
+
+
+ protected void startup()
+ {
+ long startTime = System.currentTimeMillis();
+ log.warn("Starting cache");
+ ((Cache) cache).start();
+ long duration = System.currentTimeMillis() - startTime;
+ log.warn("Started cache. " + printDuration(duration));
+ }
+
+ private void warmup() throws InterruptedException
+ {
+ long startTime = System.currentTimeMillis();
+ TaskRunner exec = new TaskRunner(NUM_THREADS);
+ log.warn("Starting warmup");
+ // creates all the Fqns since this can be expensive and we don't really want to measure this (for now)
+ for (final Object key : keys)
+ {
+ exec.execute(new Runnable()
+ {
+ public void run()
+ {
+ // this will create the necessary nodes.
+ cache.put(key, Collections.emptyMap());
+ }
+ });
+ }
+
+ // loop through WARMUP_LOOPS gets and puts for JVM optimisation
+ for (int i = 0; i < WARMUP_LOOPS; i++)
+ {
+ exec.execute(new Runnable()
+ {
+ public void run()
+ {
+ Object key = Generator.getRandomElement(keys);
+ cache.get(key);
+ cache.put(key, "Value");
+ cache.remove(key);
+ }
+ });
+ }
+
+ exec.stop();
+
+ long duration = System.currentTimeMillis() - startTime;
+ log.warn("Finished warmup. " + printDuration(duration));
+ //cache.removeNode(Fqn.ROOT);
+ ((Cache) cache).stop();
+
+ startup();
+ }
+
+ private void doTest() throws Exception
+ {
+ TaskRunner exec = new TaskRunner(NUM_THREADS);
+ log.warn("Starting test");
+ int i;
+ long print = NUM_OPERATIONS / 10;
+
+ AtomicLong durationPuts = new AtomicLong();
+ AtomicLong durationGets = new AtomicLong();
+ AtomicLong durationRemoves = new AtomicLong();
+
+ long stElapsed = System.nanoTime();
+ for (i = 0; i < NUM_OPERATIONS; i++)
+ {
+ MyRunnable r = null;
+ switch (i % 3)
+ {
+ case 0:
+ r = new Putter(i, durationPuts);
+ break;
+ case 1:
+ r = new Getter(i, durationGets);
+ break;
+ case 2:
+ r = new Remover(i, durationRemoves);
+ break;
+ }
+ if (i % print == 0)
+ log.warn("processing iteration " + i);
+ exec.execute(r);
+// if (USE_SLEEP) TestingUtil.sleepRandom(MAX_RANDOM_SLEEP_MILLIS);
+ if (USE_SLEEP) TestingUtil.sleepThread(MAX_RANDOM_SLEEP_MILLIS);
+ }
+ log.warn("Finished generating runnables; awaiting executor completion");
+ // wait for executors to complete!
+ exec.stop();
+
+ // wait up to 1 sec for each call?
+ long elapsedTimeNanos = System.nanoTime() - stElapsed;
+
+ log.warn("Finished test. " + printDuration((long) toMillis(elapsedTimeNanos)));
+ log.warn("Throughput: " + ((double) NUM_OPERATIONS * 1000 / toMillis(elapsedTimeNanos)) + " operations per second (roughly equal numbers of PUT, GET and REMOVE)");
+ log.warn("Average GET time: " + printAvg(durationGets.get()));
+ log.warn("Average PUT time: " + printAvg(durationPuts.get()));
+ log.warn("Average REMOVE time: " + printAvg(durationRemoves.get()));
+ }
+
+ private String printAvg(long totalNanos)
+ {
+ double nOps = (double) (NUM_OPERATIONS / 3);
+ double avg = ((double) totalNanos) / nOps;
+ double avgMicros = avg / 1000;
+ return avgMicros + " µs";
+ }
+
+ private double toMillis(long nanos)
+ {
+ return ((double) nanos / (double) 1000000);
+ }
+
+ enum Mode
+ {
+ PUT, GET, REMOVE
+ }
+
+ private abstract class MyRunnable implements Runnable
+ {
+ int id;
+ Mode mode;
+ AtomicLong duration;
+
+ public void run()
+ {
+ Object key = Generator.getRandomElement(keys);
+ long d = 0, st = 0;
+ switch (mode)
+ {
+ case PUT:
+ Object value = Generator.getRandomString();
+ st = System.nanoTime();
+ cache.put(key, value);
+ d = System.nanoTime() - st;
+ break;
+ case GET:
+ st = System.nanoTime();
+ cache.get(key);
+ d = System.nanoTime() - st;
+ break;
+ case REMOVE:
+ st = System.nanoTime();
+ cache.remove(key);
+ d = System.nanoTime() - st;
+ break;
+ }
+ duration.getAndAdd(d);
+ }
+ }
+
+ private class Putter extends MyRunnable
+ {
+ private Putter(int id, AtomicLong duration)
+ {
+ this.id = id;
+ this.duration = duration;
+ mode = Mode.PUT;
+ }
+ }
+
+ private class Getter extends MyRunnable
+ {
+ private Getter(int id, AtomicLong duration)
+ {
+ this.id = id;
+ this.duration = duration;
+ mode = Mode.GET;
+ }
+ }
+
+ private class Remover extends MyRunnable
+ {
+ private Remover(int id, AtomicLong duration)
+ {
+ this.id = id;
+ this.duration = duration;
+ mode = Mode.REMOVE;
+ }
+ }
+
+ protected String printDuration(long duration)
+ {
+ if (duration > 2000)
+ {
+ double dSecs = ((double) duration / (double) 1000);
+ return "Duration: " + dSecs + " seconds";
+ }
+ else
+ {
+ return "Duration: " + duration + " millis";
+ }
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/profiling/TreeProfileTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,342 +0,0 @@
-package org.jboss.starobrno.profiling;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.cache.lock.IsolationLevel;
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.UnitTestCacheFactory;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.profiling.testinternals.Generator;
-import org.jboss.starobrno.profiling.testinternals.TaskRunner;
-import org.jboss.starobrno.transaction.DummyTransactionManager;
-import org.jboss.starobrno.tree.Fqn;
-import org.jboss.starobrno.tree.TreeCache;
-import org.jboss.starobrno.tree.TreeCacheImpl;
-import org.jboss.starobrno.util.TestingUtil;
-import org.testng.annotations.AfterTest;
-import org.testng.annotations.BeforeTest;
-import org.testng.annotations.Test;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * Test to use with a profiler to profile replication. To be used in conjunction with ProfileSlaveTest.
- * <p/>
- * Typical usage pattern:
- * <p/>
- * 1. Start a single test method in ProfileSlaveTest. This will block until you kill it.
- * 2. Start the corresponding test in this class, with the same name, in a different JVM, and attached to a profiler.
- * 3. Profile away!
- * <p/>
- *
- * @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
- * @since 2.1.0
- */
- at Test(groups = "profiling", sequential = true, enabled = false)
-public class TreeProfileTest
-{
- /*
- Test configuration options
- */
- protected static final long NUM_OPERATIONS = 1000000; // DURATION is replaced with a fixed number of operations instead.
- protected static final int NUM_THREADS = 25;
- protected static final int MAX_RANDOM_SLEEP_MILLIS = 1;
- protected static final int MAX_DEPTH = 3;
- protected static final int MAX_OVERALL_NODES = 2000;
- protected static final int WARMUP_LOOPS = 20000;
- protected static final boolean USE_SLEEP = false; // throttle generation a bit
-
- protected TreeCache cache;
-
- @BeforeTest
- public void setUp()
- {
- Configuration cfg = new Configuration();
- cfg.setInvocationBatchingEnabled(true);
- 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);
- }
-
- @AfterTest
- public void tearDown()
- {
- TestingUtil.killTreeCaches(cache);
- cache = null;
- }
-
- private List<Fqn> fqns = new ArrayList<Fqn>(MAX_OVERALL_NODES);
-
- Log log = LogFactory.getLog(TreeProfileTest.class);
-
- public void testLocalMode() throws Exception
- {
- runCompleteTest();
- }
-
- private void runCompleteTest() throws Exception
- {
- init();
- startup();
- warmup();
- doTest();
-
- // wait for user exit
- System.in.read();
- }
-
- /**
- * Thr following test phases can be profiled individually using triggers in JProfiler.
- */
-
- protected void init()
- {
- long startTime = System.currentTimeMillis();
- log.warn("Starting init() phase");
- fqns.clear();
- for (int i = 0; i < MAX_OVERALL_NODES; i++)
- {
- Fqn fqn;
- do
- {
- fqn = Generator.createRandomFqn(MAX_DEPTH);
- }
- while (fqns.contains(fqn));
-
- if (i % 100 == 0) log.warn("Generated " + i + " fqns");
- fqns.add(fqn);
- }
- System.gc();
- long duration = System.currentTimeMillis() - startTime;
- log.warn("Finished init() phase. " + printDuration(duration));
- }
-
- protected void startup()
- {
- long startTime = System.currentTimeMillis();
- log.warn("Starting cache");
- cache.start();
- long duration = System.currentTimeMillis() - startTime;
- log.warn("Started cache. " + printDuration(duration));
- }
-
- private void warmup() throws InterruptedException
- {
- long startTime = System.currentTimeMillis();
- TaskRunner runner = new TaskRunner(NUM_THREADS);
- log.warn("Starting warmup");
- // creates all the Fqns since this can be expensive and we don't really want to measure this (for now)
- for (final Fqn fqn : fqns)
- {
- runner.execute(new Runnable()
- {
- public void run()
- {
- try
- {
- // this will create the necessary nodes.
- cache.put(fqn, "key", Collections.emptyMap());
- }
- catch (Exception e)
- {
- log.warn("Caught Exception", e);
- }
- }
- });
- }
-
- // loop through WARMUP_LOOPS gets and puts for JVM optimisation
- for (int i = 0; i < WARMUP_LOOPS; i++)
- {
- runner.execute(new Runnable()
- {
- public void run()
- {
- try
- {
- Fqn fqn = Generator.getRandomElement(fqns);
- DummyTransactionManager.getInstance().begin();
- cache.get(fqn, "key");
- DummyTransactionManager.getInstance().commit();
- DummyTransactionManager.getInstance().begin();
- cache.put(fqn, "key", "Value");
- DummyTransactionManager.getInstance().commit();
- DummyTransactionManager.getInstance().begin();
- cache.remove(fqn, "key");
- DummyTransactionManager.getInstance().commit();
- }
- catch (Exception e)
- {
- log.warn("Caught Exception", e);
- }
- }
- });
- }
-
- runner.stop();
-
- long duration = System.currentTimeMillis() - startTime;
- log.warn("Finished warmup. " + printDuration(duration));
- //cache.removeNode(Fqn.ROOT);
- cache.stop();
-
- startup();
- }
-
- private void doTest() throws Exception
- {
- TaskRunner runner = new TaskRunner(NUM_THREADS);
-
- log.warn("Starting test");
- int i;
- long print = NUM_OPERATIONS / 10;
-
- AtomicLong durationPuts = new AtomicLong();
- AtomicLong durationGets = new AtomicLong();
- AtomicLong durationRemoves = new AtomicLong();
-
- long stElapsed = System.nanoTime();
- for (i = 0; i < NUM_OPERATIONS; i++)
- {
- MyRunnable r = null;
- switch (i % 3)
- {
- case 0:
- r = new Putter(i, durationPuts);
- break;
- case 1:
- r = new Getter(i, durationGets);
- break;
- case 2:
- r = new Remover(i, durationRemoves);
- break;
- }
- if (i % print == 0)
- log.warn("processing iteration " + i);
- runner.execute(r);
-// if (USE_SLEEP) TestingUtil.sleepRandom(MAX_RANDOM_SLEEP_MILLIS);
- if (USE_SLEEP) TestingUtil.sleepThread(MAX_RANDOM_SLEEP_MILLIS);
- }
- log.warn("Finished generating runnables; awaiting executor completion");
- // wait for executors to complete!
- runner.stop();
-
- // wait up to 1 sec for each call?
- long elapsedTimeNanos = System.nanoTime() - stElapsed;
-
- log.warn("Finished test. " + printDuration((long) toMillis(elapsedTimeNanos)));
- log.warn("Throughput: " + ((double) NUM_OPERATIONS * 1000 / toMillis(elapsedTimeNanos)) + " operations per second (roughly equal numbers of PUT, GET and REMOVE)");
- log.warn("Average GET time: " + printAvg(durationGets.get()));
- log.warn("Average PUT time: " + printAvg(durationPuts.get()));
- log.warn("Average REMOVE time: " + printAvg(durationRemoves.get()));
- }
-
- private String printAvg(long totalNanos)
- {
- double nOps = (double) (NUM_OPERATIONS / 3);
- double avg = ((double) totalNanos) / nOps;
- double avgMicros = avg / 1000;
- return avgMicros + " µs";
- }
-
- private double toMillis(long nanos)
- {
- return ((double) nanos / (double) 1000000);
- }
-
- enum Mode
- {
- PUT, GET, REMOVE
- }
-
- private abstract class MyRunnable implements Runnable
- {
- int id;
- Mode mode;
- AtomicLong duration;
-
- public void run()
- {
- Fqn fqn = Generator.getRandomElement(fqns);
- long d = 0, st = 0;
- try
- {
- switch (mode)
- {
- case PUT:
- Object value = Generator.getRandomString();
-
- st = System.nanoTime();
- cache.put(fqn, "key", value);
- d = System.nanoTime() - st;
- break;
- case GET:
- st = System.nanoTime();
- cache.get(fqn, "key");
- d = System.nanoTime() - st;
- break;
- case REMOVE:
- st = System.nanoTime();
- cache.remove(fqn, "key");
- d = System.nanoTime() - st;
- break;
- }
- }
- catch (Exception e)
- {
- d = 0;
- }
- duration.getAndAdd(d);
- }
- }
-
- private class Putter extends MyRunnable
- {
- private Putter(int id, AtomicLong duration)
- {
- this.id = id;
- this.duration = duration;
- mode = Mode.PUT;
- }
- }
-
- private class Getter extends MyRunnable
- {
- private Getter(int id, AtomicLong duration)
- {
- this.id = id;
- this.duration = duration;
- mode = Mode.GET;
- }
- }
-
- private class Remover extends MyRunnable
- {
- private Remover(int id, AtomicLong duration)
- {
- this.id = id;
- this.duration = duration;
- mode = Mode.REMOVE;
- }
- }
-
- protected String printDuration(long duration)
- {
- if (duration > 2000)
- {
- double dSecs = ((double) duration / (double) 1000);
- return "Duration: " + dSecs + " seconds";
- }
- else
- {
- return "Duration: " + duration + " millis";
- }
- }
-}
\ No newline at end of file
Copied: core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/profiling/TreeProfileTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,342 @@
+package org.horizon.profiling;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.horizon.lock.IsolationLevel;
+import org.horizon.Cache;
+import org.horizon.UnitTestCacheFactory;
+import org.horizon.config.Configuration;
+import org.horizon.profiling.testinternals.Generator;
+import org.horizon.profiling.testinternals.TaskRunner;
+import org.horizon.transaction.DummyTransactionManager;
+import org.horizon.tree.Fqn;
+import org.horizon.tree.TreeCache;
+import org.horizon.tree.TreeCacheImpl;
+import org.horizon.util.TestingUtil;
+import org.testng.annotations.AfterTest;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Test;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * Test to use with a profiler to profile replication. To be used in conjunction with ProfileSlaveTest.
+ * <p/>
+ * Typical usage pattern:
+ * <p/>
+ * 1. Start a single test method in ProfileSlaveTest. This will block until you kill it.
+ * 2. Start the corresponding test in this class, with the same name, in a different JVM, and attached to a profiler.
+ * 3. Profile away!
+ * <p/>
+ *
+ * @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
+ * @since 2.1.0
+ */
+ at Test(groups = "profiling", sequential = true, enabled = false)
+public class TreeProfileTest
+{
+ /*
+ Test configuration options
+ */
+ protected static final long NUM_OPERATIONS = 1000000; // DURATION is replaced with a fixed number of operations instead.
+ protected static final int NUM_THREADS = 25;
+ protected static final int MAX_RANDOM_SLEEP_MILLIS = 1;
+ protected static final int MAX_DEPTH = 3;
+ protected static final int MAX_OVERALL_NODES = 2000;
+ protected static final int WARMUP_LOOPS = 20000;
+ protected static final boolean USE_SLEEP = false; // throttle generation a bit
+
+ protected TreeCache cache;
+
+ @BeforeTest
+ public void setUp()
+ {
+ Configuration cfg = new Configuration();
+ cfg.setInvocationBatchingEnabled(true);
+ 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);
+ }
+
+ @AfterTest
+ public void tearDown()
+ {
+ TestingUtil.killTreeCaches(cache);
+ cache = null;
+ }
+
+ private List<Fqn> fqns = new ArrayList<Fqn>(MAX_OVERALL_NODES);
+
+ Log log = LogFactory.getLog(TreeProfileTest.class);
+
+ public void testLocalMode() throws Exception
+ {
+ runCompleteTest();
+ }
+
+ private void runCompleteTest() throws Exception
+ {
+ init();
+ startup();
+ warmup();
+ doTest();
+
+ // wait for user exit
+ System.in.read();
+ }
+
+ /**
+ * Thr following test phases can be profiled individually using triggers in JProfiler.
+ */
+
+ protected void init()
+ {
+ long startTime = System.currentTimeMillis();
+ log.warn("Starting init() phase");
+ fqns.clear();
+ for (int i = 0; i < MAX_OVERALL_NODES; i++)
+ {
+ Fqn fqn;
+ do
+ {
+ fqn = Generator.createRandomFqn(MAX_DEPTH);
+ }
+ while (fqns.contains(fqn));
+
+ if (i % 100 == 0) log.warn("Generated " + i + " fqns");
+ fqns.add(fqn);
+ }
+ System.gc();
+ long duration = System.currentTimeMillis() - startTime;
+ log.warn("Finished init() phase. " + printDuration(duration));
+ }
+
+ protected void startup()
+ {
+ long startTime = System.currentTimeMillis();
+ log.warn("Starting cache");
+ cache.start();
+ long duration = System.currentTimeMillis() - startTime;
+ log.warn("Started cache. " + printDuration(duration));
+ }
+
+ private void warmup() throws InterruptedException
+ {
+ long startTime = System.currentTimeMillis();
+ TaskRunner runner = new TaskRunner(NUM_THREADS);
+ log.warn("Starting warmup");
+ // creates all the Fqns since this can be expensive and we don't really want to measure this (for now)
+ for (final Fqn fqn : fqns)
+ {
+ runner.execute(new Runnable()
+ {
+ public void run()
+ {
+ try
+ {
+ // this will create the necessary nodes.
+ cache.put(fqn, "key", Collections.emptyMap());
+ }
+ catch (Exception e)
+ {
+ log.warn("Caught Exception", e);
+ }
+ }
+ });
+ }
+
+ // loop through WARMUP_LOOPS gets and puts for JVM optimisation
+ for (int i = 0; i < WARMUP_LOOPS; i++)
+ {
+ runner.execute(new Runnable()
+ {
+ public void run()
+ {
+ try
+ {
+ Fqn fqn = Generator.getRandomElement(fqns);
+ DummyTransactionManager.getInstance().begin();
+ cache.get(fqn, "key");
+ DummyTransactionManager.getInstance().commit();
+ DummyTransactionManager.getInstance().begin();
+ cache.put(fqn, "key", "Value");
+ DummyTransactionManager.getInstance().commit();
+ DummyTransactionManager.getInstance().begin();
+ cache.remove(fqn, "key");
+ DummyTransactionManager.getInstance().commit();
+ }
+ catch (Exception e)
+ {
+ log.warn("Caught Exception", e);
+ }
+ }
+ });
+ }
+
+ runner.stop();
+
+ long duration = System.currentTimeMillis() - startTime;
+ log.warn("Finished warmup. " + printDuration(duration));
+ //cache.removeNode(Fqn.ROOT);
+ cache.stop();
+
+ startup();
+ }
+
+ private void doTest() throws Exception
+ {
+ TaskRunner runner = new TaskRunner(NUM_THREADS);
+
+ log.warn("Starting test");
+ int i;
+ long print = NUM_OPERATIONS / 10;
+
+ AtomicLong durationPuts = new AtomicLong();
+ AtomicLong durationGets = new AtomicLong();
+ AtomicLong durationRemoves = new AtomicLong();
+
+ long stElapsed = System.nanoTime();
+ for (i = 0; i < NUM_OPERATIONS; i++)
+ {
+ MyRunnable r = null;
+ switch (i % 3)
+ {
+ case 0:
+ r = new Putter(i, durationPuts);
+ break;
+ case 1:
+ r = new Getter(i, durationGets);
+ break;
+ case 2:
+ r = new Remover(i, durationRemoves);
+ break;
+ }
+ if (i % print == 0)
+ log.warn("processing iteration " + i);
+ runner.execute(r);
+// if (USE_SLEEP) TestingUtil.sleepRandom(MAX_RANDOM_SLEEP_MILLIS);
+ if (USE_SLEEP) TestingUtil.sleepThread(MAX_RANDOM_SLEEP_MILLIS);
+ }
+ log.warn("Finished generating runnables; awaiting executor completion");
+ // wait for executors to complete!
+ runner.stop();
+
+ // wait up to 1 sec for each call?
+ long elapsedTimeNanos = System.nanoTime() - stElapsed;
+
+ log.warn("Finished test. " + printDuration((long) toMillis(elapsedTimeNanos)));
+ log.warn("Throughput: " + ((double) NUM_OPERATIONS * 1000 / toMillis(elapsedTimeNanos)) + " operations per second (roughly equal numbers of PUT, GET and REMOVE)");
+ log.warn("Average GET time: " + printAvg(durationGets.get()));
+ log.warn("Average PUT time: " + printAvg(durationPuts.get()));
+ log.warn("Average REMOVE time: " + printAvg(durationRemoves.get()));
+ }
+
+ private String printAvg(long totalNanos)
+ {
+ double nOps = (double) (NUM_OPERATIONS / 3);
+ double avg = ((double) totalNanos) / nOps;
+ double avgMicros = avg / 1000;
+ return avgMicros + " µs";
+ }
+
+ private double toMillis(long nanos)
+ {
+ return ((double) nanos / (double) 1000000);
+ }
+
+ enum Mode
+ {
+ PUT, GET, REMOVE
+ }
+
+ private abstract class MyRunnable implements Runnable
+ {
+ int id;
+ Mode mode;
+ AtomicLong duration;
+
+ public void run()
+ {
+ Fqn fqn = Generator.getRandomElement(fqns);
+ long d = 0, st = 0;
+ try
+ {
+ switch (mode)
+ {
+ case PUT:
+ Object value = Generator.getRandomString();
+
+ st = System.nanoTime();
+ cache.put(fqn, "key", value);
+ d = System.nanoTime() - st;
+ break;
+ case GET:
+ st = System.nanoTime();
+ cache.get(fqn, "key");
+ d = System.nanoTime() - st;
+ break;
+ case REMOVE:
+ st = System.nanoTime();
+ cache.remove(fqn, "key");
+ d = System.nanoTime() - st;
+ break;
+ }
+ }
+ catch (Exception e)
+ {
+ d = 0;
+ }
+ duration.getAndAdd(d);
+ }
+ }
+
+ private class Putter extends MyRunnable
+ {
+ private Putter(int id, AtomicLong duration)
+ {
+ this.id = id;
+ this.duration = duration;
+ mode = Mode.PUT;
+ }
+ }
+
+ private class Getter extends MyRunnable
+ {
+ private Getter(int id, AtomicLong duration)
+ {
+ this.id = id;
+ this.duration = duration;
+ mode = Mode.GET;
+ }
+ }
+
+ private class Remover extends MyRunnable
+ {
+ private Remover(int id, AtomicLong duration)
+ {
+ this.id = id;
+ this.duration = duration;
+ mode = Mode.REMOVE;
+ }
+ }
+
+ protected String printDuration(long duration)
+ {
+ if (duration > 2000)
+ {
+ double dSecs = ((double) duration / (double) 1000);
+ return "Duration: " + dSecs + " seconds";
+ }
+ else
+ {
+ return "Duration: " + duration + " millis";
+ }
+ }
+}
\ No newline at end of file
Deleted: core/branches/flat/src/test/java/org/horizon/profiling/testinternals/Generator.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/profiling/testinternals/Generator.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/profiling/testinternals/Generator.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,41 +0,0 @@
-package org.jboss.starobrno.profiling.testinternals;
-
-import org.jboss.starobrno.tree.Fqn;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Random;
-
-public class Generator
-{
- private static final Random r = new Random();
-
- public static String getRandomString()
- {
- StringBuilder sb = new StringBuilder();
- int len = r.nextInt(10);
-
- for (int i = 0; i < len; i++)
- {
- sb.append((char) (63 + r.nextInt(26)));
- }
- return sb.toString();
- }
-
- public static <T> T getRandomElement(List<T> list)
- {
- return list.get(r.nextInt(list.size()));
- }
-
- public static Fqn createRandomFqn(int depth)
- {
- List<String> fqnElements = new ArrayList<String>(depth);
- for (int i = 0; i < depth; i++) fqnElements.add(Integer.toHexString(r.nextInt(Integer.MAX_VALUE)));
- return Fqn.fromList(fqnElements, true);
- }
-
- public static Object createRandomKey()
- {
- return Integer.toHexString(r.nextInt(Integer.MAX_VALUE));
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/profiling/testinternals/Generator.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/profiling/testinternals/Generator.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/testinternals/Generator.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/profiling/testinternals/Generator.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,41 @@
+package org.horizon.profiling.testinternals;
+
+import org.horizon.tree.Fqn;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
+
+public class Generator
+{
+ private static final Random r = new Random();
+
+ public static String getRandomString()
+ {
+ StringBuilder sb = new StringBuilder();
+ int len = r.nextInt(10);
+
+ for (int i = 0; i < len; i++)
+ {
+ sb.append((char) (63 + r.nextInt(26)));
+ }
+ return sb.toString();
+ }
+
+ public static <T> T getRandomElement(List<T> list)
+ {
+ return list.get(r.nextInt(list.size()));
+ }
+
+ public static Fqn createRandomFqn(int depth)
+ {
+ List<String> fqnElements = new ArrayList<String>(depth);
+ for (int i = 0; i < depth; i++) fqnElements.add(Integer.toHexString(r.nextInt(Integer.MAX_VALUE)));
+ return Fqn.fromList(fqnElements, true);
+ }
+
+ public static Object createRandomKey()
+ {
+ return Integer.toHexString(r.nextInt(Integer.MAX_VALUE));
+ }
+}
Modified: core/branches/flat/src/test/java/org/horizon/profiling/testinternals/TaskRunner.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/profiling/testinternals/TaskRunner.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/profiling/testinternals/TaskRunner.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,4 +1,4 @@
-package org.jboss.starobrno.profiling.testinternals;
+package org.horizon.profiling.testinternals;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
Copied: core/branches/flat/src/test/java/org/horizon/replication (from rev 7484, core/branches/flat/src/test/java/org/jboss/starobrno/replication)
Deleted: core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/replication/AsyncReplTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,232 +0,0 @@
-/*
- *
- * JBoss, the OpenSource J2EE webOS
- *
- * Distributable under LGPL license.
- * See terms of license at gnu.org.
- */
-
-package org.jboss.starobrno.replication;
-
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.CacheSPI;
-import org.jboss.starobrno.UnitTestCacheManager;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.transaction.DummyTransactionManagerLookup;
-import org.jboss.starobrno.util.TestingUtil;
-import org.jboss.starobrno.util.internals.ReplicationListener;
-import static org.testng.AssertJUnit.*;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import javax.transaction.TransactionManager;
-
-/**
- * Unit test for replicated async CacheSPI. Use locking and multiple threads to test
- * concurrent access to the tree.
- */
- at Test(groups = {"functional", "jgroups"})
-public class AsyncReplTest
-{
-
- private class AsyncReplTestTL
- {
- private Configuration configuration;
- private CacheSPI<Object, Object> cache1, cache2;
- private UnitTestCacheManager cacheManager1, cacheManager2;
- private ReplicationListener replListener1, replListener2;
- }
-
- private ThreadLocal<AsyncReplTestTL> threadLocal = new ThreadLocal<AsyncReplTestTL>();
-
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
- AsyncReplTestTL tl = new AsyncReplTestTL();
- threadLocal.set(tl);
-
- tl.configuration = new Configuration();
- tl.configuration.setCacheMode(Configuration.CacheMode.REPL_ASYNC);
- tl.configuration.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
-
- log("creating cache1");
- tl.cacheManager1 = new UnitTestCacheManager(tl.configuration);
- tl.cache1 = (CacheSPI) tl.cacheManager1.createCache("testCache");
- tl.replListener1 = new ReplicationListener(tl.cache1);
-
- log("creating cache2");
- tl.cacheManager2 = new UnitTestCacheManager(tl.configuration);
- tl.cache2 = (CacheSPI) tl.cacheManager2.createCache("testCache");
- tl.replListener2 = new ReplicationListener(tl.cache2);
- }
-
- /**
- * 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
- }
-
- /**
- * Provides a hook to check that the cache's channel came from the
- * multiplexer, or not, as expected. This default impl asserts that
- * the channel did not come from the multiplexer.
- *
- * @param cache a cache that has already been started
- */
- protected void validateMultiplexer(Cache cache)
- {
- assertFalse("Cache is not using multiplexer", cache.getConfiguration().isUsingMultiplexer());
- }
-
- @AfterMethod(alwaysRun = true)
- public void tearDown() throws Exception
- {
- AsyncReplTestTL tl = threadLocal.get();
- TestingUtil.killCaches(tl.cache1, tl.cache2);
- threadLocal.set(null);
- }
-
- 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;
-
- String key = "key";
-
- replListener2.expectAny();
- cache1.put(key, "value1");
- // allow for replication
- replListener2.waitForReplicationToOccur(500);
- assertEquals("value1", cache1.get(key));
- assertEquals("value1", cache2.get(key));
-
- TransactionManager mgr = cache1.getTransactionManager();
- mgr.begin();
-
- replListener2.expectAny();
- cache1.put(key, "value2");
- assertEquals("value2", cache1.get(key));
- assertEquals("value1", cache2.get(key));
-
- mgr.commit();
-
- replListener2.waitForReplicationToOccur(500);
-
- assertEquals("value2", cache1.get(key));
- assertEquals("value2", cache2.get(key));
-
- mgr.begin();
- cache1.put(key, "value3");
- assertEquals("value3", cache1.get(key));
- assertEquals("value2", cache2.get(key));
-
- mgr.rollback();
-
- 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
- {
- 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);
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/replication/AsyncReplTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,232 @@
+/*
+ *
+ * JBoss, the OpenSource J2EE webOS
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+
+package org.horizon.replication;
+
+import org.horizon.Cache;
+import org.horizon.CacheSPI;
+import org.horizon.UnitTestCacheManager;
+import org.horizon.config.Configuration;
+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 org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import javax.transaction.TransactionManager;
+
+/**
+ * Unit test for replicated async CacheSPI. Use locking and multiple threads to test
+ * concurrent access to the tree.
+ */
+ at Test(groups = {"functional", "jgroups"})
+public class AsyncReplTest
+{
+
+ private class AsyncReplTestTL
+ {
+ private Configuration configuration;
+ private CacheSPI<Object, Object> cache1, cache2;
+ private UnitTestCacheManager cacheManager1, cacheManager2;
+ private ReplicationListener replListener1, replListener2;
+ }
+
+ private ThreadLocal<AsyncReplTestTL> threadLocal = new ThreadLocal<AsyncReplTestTL>();
+
+ @BeforeMethod(alwaysRun = true)
+ public void setUp() throws Exception
+ {
+ AsyncReplTestTL tl = new AsyncReplTestTL();
+ threadLocal.set(tl);
+
+ tl.configuration = new Configuration();
+ tl.configuration.setCacheMode(Configuration.CacheMode.REPL_ASYNC);
+ tl.configuration.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+
+ log("creating cache1");
+ tl.cacheManager1 = new UnitTestCacheManager(tl.configuration);
+ tl.cache1 = (CacheSPI) tl.cacheManager1.createCache("testCache");
+ tl.replListener1 = new ReplicationListener(tl.cache1);
+
+ log("creating cache2");
+ tl.cacheManager2 = new UnitTestCacheManager(tl.configuration);
+ tl.cache2 = (CacheSPI) tl.cacheManager2.createCache("testCache");
+ tl.replListener2 = new ReplicationListener(tl.cache2);
+ }
+
+ /**
+ * 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
+ }
+
+ /**
+ * Provides a hook to check that the cache's channel came from the
+ * multiplexer, or not, as expected. This default impl asserts that
+ * the channel did not come from the multiplexer.
+ *
+ * @param cache a cache that has already been started
+ */
+ protected void validateMultiplexer(Cache cache)
+ {
+ assertFalse("Cache is not using multiplexer", cache.getConfiguration().isUsingMultiplexer());
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown() throws Exception
+ {
+ AsyncReplTestTL tl = threadLocal.get();
+ TestingUtil.killCaches(tl.cache1, tl.cache2);
+ threadLocal.set(null);
+ }
+
+ 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;
+
+ String key = "key";
+
+ replListener2.expectAny();
+ cache1.put(key, "value1");
+ // allow for replication
+ replListener2.waitForReplicationToOccur(500);
+ assertEquals("value1", cache1.get(key));
+ assertEquals("value1", cache2.get(key));
+
+ TransactionManager mgr = cache1.getTransactionManager();
+ mgr.begin();
+
+ replListener2.expectAny();
+ cache1.put(key, "value2");
+ assertEquals("value2", cache1.get(key));
+ assertEquals("value1", cache2.get(key));
+
+ mgr.commit();
+
+ replListener2.waitForReplicationToOccur(500);
+
+ assertEquals("value2", cache1.get(key));
+ assertEquals("value2", cache2.get(key));
+
+ mgr.begin();
+ cache1.put(key, "value3");
+ assertEquals("value3", cache1.get(key));
+ assertEquals("value2", cache2.get(key));
+
+ mgr.rollback();
+
+ 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
+ {
+ 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);
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/replication/ExceptionTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,98 +0,0 @@
-package org.jboss.starobrno.replication;
-
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.UnitTestCacheManager;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.lock.TimeoutException;
-import org.jboss.starobrno.transaction.DummyTransactionManagerLookup;
-import org.jboss.starobrno.util.TestingUtil;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.Test;
-
-import javax.transaction.Transaction;
-import javax.transaction.TransactionManager;
-
-/**
- * Tests the type of exceptions thrown for Lock Acquisition Timeouts versus Sync Repl Timeouts
- *
- * @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
- */
- at Test(groups = {"functional"}, sequential = true)
-public class ExceptionTest
-{
- 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)
- {
- Configuration c = new Configuration();
- c.setSyncCommitPhase(true);
- c.setSyncRollbackPhase(true);
- c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
- 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;
- }
-
- @Test(groups = {"functional"}, expectedExceptions = {TimeoutException.class})
- public void testSyncReplTimeout()
- {
- cache1 = createCache(DELAYED_CLUSTER_CONFIG);
- cache2 = createCache(DELAYED_CLUSTER_CONFIG);
-
- cache1.getConfiguration().setSyncReplTimeout(1); // 1ms. this is *bound* to fail.
- cache2.getConfiguration().setSyncReplTimeout(1);
-
- cache1.start();
- cache2.start();
-
- TestingUtil.blockUntilViewsReceived(60000, cache1, cache2);
-
- cache1.put("k", "v");
- }
-
- @Test(groups = {"functional"}, expectedExceptions = {TimeoutException.class})
- public void testLockAcquisitionTimeout() throws Exception
- {
- cache1 = createCache(null);
- cache2 = createCache(null);
- cache2.getConfiguration().setLockAcquisitionTimeout(1);
-
- cache1.start();
- cache2.start();
-
- TestingUtil.blockUntilViewsReceived(10000, cache1, cache2);
-
- // get a lock on cache 2 and hold on to it.
- TransactionManager tm = cache2.getConfiguration().getRuntimeConfig().getTransactionManager();
- tm.begin();
- cache2.put("block", "block");
- Transaction t = tm.suspend();
- cache1.put("block", "v");
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/replication/ExceptionTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,98 @@
+package org.horizon.replication;
+
+import org.horizon.Cache;
+import org.horizon.UnitTestCacheManager;
+import org.horizon.config.Configuration;
+import org.horizon.lock.TimeoutException;
+import org.horizon.transaction.DummyTransactionManagerLookup;
+import org.horizon.util.TestingUtil;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.Test;
+
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
+
+/**
+ * Tests the type of exceptions thrown for Lock Acquisition Timeouts versus Sync Repl Timeouts
+ *
+ * @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
+ */
+ at Test(groups = {"functional"}, sequential = true)
+public class ExceptionTest
+{
+ 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)
+ {
+ Configuration c = new Configuration();
+ c.setSyncCommitPhase(true);
+ c.setSyncRollbackPhase(true);
+ c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
+ 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;
+ }
+
+ @Test(groups = {"functional"}, expectedExceptions = {TimeoutException.class})
+ public void testSyncReplTimeout()
+ {
+ cache1 = createCache(DELAYED_CLUSTER_CONFIG);
+ cache2 = createCache(DELAYED_CLUSTER_CONFIG);
+
+ cache1.getConfiguration().setSyncReplTimeout(1); // 1ms. this is *bound* to fail.
+ cache2.getConfiguration().setSyncReplTimeout(1);
+
+ cache1.start();
+ cache2.start();
+
+ TestingUtil.blockUntilViewsReceived(60000, cache1, cache2);
+
+ cache1.put("k", "v");
+ }
+
+ @Test(groups = {"functional"}, expectedExceptions = {TimeoutException.class})
+ public void testLockAcquisitionTimeout() throws Exception
+ {
+ cache1 = createCache(null);
+ cache2 = createCache(null);
+ cache2.getConfiguration().setLockAcquisitionTimeout(1);
+
+ cache1.start();
+ cache2.start();
+
+ TestingUtil.blockUntilViewsReceived(10000, cache1, cache2);
+
+ // get a lock on cache 2 and hold on to it.
+ TransactionManager tm = cache2.getConfiguration().getRuntimeConfig().getTransactionManager();
+ tm.begin();
+ cache2.put("block", "block");
+ Transaction t = tm.suspend();
+ cache1.put("block", "v");
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/replication/ReplicationExceptionTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,175 +0,0 @@
-/*
- *
- * JBoss, the OpenSource J2EE webOS
- *
- * Distributable under LGPL license.
- * See terms of license at gnu.org.
- */
-package org.jboss.starobrno.replication;
-
-import org.jboss.cache.lock.IsolationLevel;
-import org.jboss.starobrno.CacheSPI;
-import org.jboss.starobrno.UnitTestCacheManager;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.transaction.DummyTransactionManager;
-import org.jboss.starobrno.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.naming.Context;
-import javax.transaction.NotSupportedException;
-import javax.transaction.RollbackException;
-import javax.transaction.SystemException;
-import javax.transaction.TransactionManager;
-import java.io.NotSerializableException;
-import java.io.Serializable;
-
-/**
- * Teting of replication exception for a Nonerislizable object
- *
- * @author Ben Wang
- * @version $Revision$
- */
- at Test(groups = {"functional"}, sequential = true)
-public class ReplicationExceptionTest
-{
- private CacheSPI<String, ContainerData> cache1, cache2;
-
- //String old_factory = null;
- final String FACTORY = "org.jboss.cache.transaction.DummyContextFactory";
-
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
- //old_factory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY);
- System.setProperty(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
- }
-
- @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;
- }
- */
- }
-
- private TransactionManager beginTransaction() throws SystemException, NotSupportedException
- {
- TransactionManager mgr = cache1.getConfiguration().getRuntimeConfig().getTransactionManager();
- mgr.begin();
- return mgr;
- }
-
- private void initCaches(Configuration.CacheMode cachingMode)
- {
- Configuration conf1 = new Configuration();
- Configuration conf2 = new Configuration();
-
- conf1.setCacheMode(cachingMode);
- conf2.setCacheMode(cachingMode);
- conf1.setIsolationLevel(IsolationLevel.SERIALIZABLE);
- conf2.setIsolationLevel(IsolationLevel.SERIALIZABLE);
-
- conf1.setTransactionManagerLookupClass("org.jboss.starobrno.transaction.DummyTransactionManagerLookup");
- conf2.setTransactionManagerLookupClass("org.jboss.starobrno.transaction.DummyTransactionManagerLookup");
- /*
- cache1.setTransactionManagerLookupClass("org.jboss.starobrno.transaction.GenericTransactionManagerLookup");
- cache2.setTransactionManagerLookupClass("org.jboss.starobrno.transaction.GenericTransactionManagerLookup");
- */
- conf1.setLockAcquisitionTimeout(5000);
- conf2.setLockAcquisitionTimeout(5000);
-
- cache1 = (CacheSPI) new UnitTestCacheManager(conf1).createCache("testCache");
- cache2 = (CacheSPI) new UnitTestCacheManager(conf2).createCache("testCache");
-
-
- cache1.start();
- cache2.start();
- }
-
- void destroyCaches() throws Exception
- {
- TestingUtil.killCaches(cache1, cache2);
- cache1 = null;
- cache2 = null;
- }
-
- public void testNonSerializableRepl() throws Exception
- {
- try
- {
- initCaches(Configuration.CacheMode.REPL_SYNC);
-
- cache1.put("test", new ContainerData());
-
- // We should not come here.
- assertNotNull("NonSerializableData should not be null on cache2", cache2.get("test"));
- }
- catch (RuntimeException runtime)
- {
- Throwable t = runtime.getCause();
- if (t instanceof NotSerializableException)
- {
- System.out.println("received NotSerializableException - as expected");
- }
- else
- {
- throw runtime;
- }
- }
- }
-
- public void testNonSerializableReplWithTx() throws Exception
- {
- TransactionManager tm;
-
- try
- {
- initCaches(Configuration.CacheMode.REPL_SYNC);
-
- tm = beginTransaction();
- cache1.put("test", new ContainerData());
- tm.commit();
-
- // We should not come here.
- assertNotNull("NonSerializableData should not be null on cache2", cache2.get("test"));
- }
- catch (RollbackException rollback)
- {
- System.out.println("received RollbackException - as expected");
- }
- catch (Exception e)
- {
- // We should also examine that it is indeed throwing a NonSerilaizable exception.
- fail(e.toString());
- }
- }
-
- static class NonSerializabeData
- {
- int i;
- }
-
- static class ContainerData implements Serializable
- {
- int i;
- NonSerializabeData non_serializable_data;
- private static final long serialVersionUID = -8322197791060897247L;
-
- public ContainerData()
- {
- i = 99;
- non_serializable_data = new NonSerializabeData();
- }
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/replication/ReplicationExceptionTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,160 @@
+/*
+ *
+ * JBoss, the OpenSource J2EE webOS
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.horizon.replication;
+
+import org.horizon.CacheSPI;
+import org.horizon.UnitTestCacheManager;
+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.Test;
+
+import javax.transaction.NotSupportedException;
+import javax.transaction.RollbackException;
+import javax.transaction.SystemException;
+import javax.transaction.TransactionManager;
+import java.io.NotSerializableException;
+import java.io.Serializable;
+
+/**
+ * Teting of replication exception for a Nonerislizable object
+ *
+ * @author Ben Wang
+ * @version $Revision$
+ */
+ at Test(groups = {"functional"}, sequential = true)
+public class ReplicationExceptionTest
+{
+ private CacheSPI<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;
+ }
+ */
+ }
+
+ private TransactionManager beginTransaction() throws SystemException, NotSupportedException
+ {
+ TransactionManager mgr = cache1.getConfiguration().getRuntimeConfig().getTransactionManager();
+ mgr.begin();
+ return mgr;
+ }
+
+ private void initCaches(Configuration.CacheMode cachingMode)
+ {
+ Configuration conf1 = new Configuration();
+ Configuration conf2 = new Configuration();
+
+ conf1.setCacheMode(cachingMode);
+ conf2.setCacheMode(cachingMode);
+ conf1.setIsolationLevel(IsolationLevel.SERIALIZABLE);
+ conf2.setIsolationLevel(IsolationLevel.SERIALIZABLE);
+
+ 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();
+ }
+
+ void destroyCaches() throws Exception
+ {
+ TestingUtil.killCaches(cache1, cache2);
+ cache1 = null;
+ cache2 = null;
+ }
+
+ public void testNonSerializableRepl() throws Exception
+ {
+ try
+ {
+ initCaches(Configuration.CacheMode.REPL_SYNC);
+
+ cache1.put("test", new ContainerData());
+
+ // We should not come here.
+ assertNotNull("NonSerializableData should not be null on cache2", cache2.get("test"));
+ }
+ catch (RuntimeException runtime)
+ {
+ Throwable t = runtime.getCause();
+ if (t instanceof NotSerializableException)
+ {
+ System.out.println("received NotSerializableException - as expected");
+ }
+ else
+ {
+ throw runtime;
+ }
+ }
+ }
+
+ public void testNonSerializableReplWithTx() throws Exception
+ {
+ TransactionManager tm;
+
+ try
+ {
+ initCaches(Configuration.CacheMode.REPL_SYNC);
+
+ tm = beginTransaction();
+ cache1.put("test", new ContainerData());
+ tm.commit();
+
+ // We should not come here.
+ assertNotNull("NonSerializableData should not be null on cache2", cache2.get("test"));
+ }
+ catch (RollbackException rollback)
+ {
+ System.out.println("received RollbackException - as expected");
+ }
+ catch (Exception e)
+ {
+ // We should also examine that it is indeed throwing a NonSerilaizable exception.
+ fail(e.toString());
+ }
+ }
+
+ static class NonSerializabeData
+ {
+ int i;
+ }
+
+ static class ContainerData implements Serializable
+ {
+ int i;
+ NonSerializabeData non_serializable_data;
+ private static final long serialVersionUID = -8322197791060897247L;
+
+ public ContainerData()
+ {
+ i = 99;
+ non_serializable_data = new NonSerializabeData();
+ }
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/replication/SyncCacheListenerTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,255 +0,0 @@
-/*
- *
- * JBoss, the OpenSource J2EE webOS
- *
- * Distributable under LGPL license.
- * See terms of license at gnu.org.
- */
-package org.jboss.starobrno.replication;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.cache.lock.IsolationLevel;
-import org.jboss.starobrno.CacheException;
-import org.jboss.starobrno.CacheSPI;
-import org.jboss.starobrno.UnitTestCacheManager;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.notifications.annotation.CacheEntryModified;
-import org.jboss.starobrno.notifications.annotation.CacheEntryRemoved;
-import org.jboss.starobrno.notifications.annotation.CacheListener;
-import org.jboss.starobrno.notifications.event.Event;
-import org.jboss.starobrno.notifications.event.TransactionalEvent;
-import org.jboss.starobrno.transaction.DummyTransactionManager;
-import org.jboss.starobrno.transaction.DummyTransactionManagerLookup;
-import org.jboss.starobrno.util.TestingUtil;
-import static org.testng.AssertJUnit.*;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import javax.naming.Context;
-import javax.transaction.Transaction;
-import javax.transaction.TransactionManager;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Test out the TreeCacheListener
- *
- * @version $Revision$
- */
- at Test(groups = {"functional"}, sequential = true)
-public class SyncCacheListenerTest
-{
- private CacheSPI<Object, Object> cache1, cache2;
- private final static Log log_ = LogFactory.getLog(SyncCacheListenerTest.class);
- //private String old_factory = null;
- private final static String FACTORY = "org.jboss.cache.transaction.DummyContextFactory";
-
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
- System.out.println("*** starting setUp()");
- //old_factory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY);
- System.setProperty(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
-
- 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);
- conf.setIsolationLevel(IsolationLevel.SERIALIZABLE);
- 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);
- }
-
- private void destroyCaches()
- {
- TestingUtil.killCaches(cache1, cache2);
- cache1 = null;
- cache2 = null;
- }
-
- public void testSyncTxRepl() throws Exception
- {
- Integer age;
- TransactionManager tm = cache1.getTransactionManager();
-
- tm.begin();
- Transaction tx = tm.getTransaction();
- Listener lis = new Listener();
- cache1.getNotifier().addCacheListener(lis);
- lis.put("age", 38);
-
- tm.suspend();
- assertNull("age on cache2 must be null as the TX has not yet been committed", cache2.get("age"));
- tm.resume(tx);
- tm.commit();
-
- // value on cache2 must be 38
- age = (Integer) cache2.get("age");
- assertNotNull("\"age\" obtained from cache2 must be non-null ", age);
- assertTrue("\"age\" must be 38", age == 38);
- }
-
- public void testRemoteCacheListener() throws Exception
- {
- Integer age;
- RemoteListener lis = new RemoteListener();
- cache2.getNotifier().addCacheListener(lis);
- cache1.put("age", 38);
-
- // value on cache2 must be 38
- age = (Integer) cache2.get("age");
- assertNotNull("\"age\" obtained from cache2 must be non-null ", age);
- assertTrue("\"age\" must be 38", age == 38);
- cache1.remove("age");
- }
-
- public void testSyncRepl() throws Exception
- {
- Integer age;
- Listener lis = new Listener();
- cache1.addCacheListener(lis);
- lis.put("age", 38);
-
- // value on cache2 must be 38
- age = (Integer) cache2.get("age");
- assertNotNull("\"age\" obtained from cache2 must be non-null ", age);
- assertTrue("\"age\" must be 38", age == 38);
- }
-
-
- public void simpleReplicationTest() throws Exception
- {
- TransactionManager tm = cache1.getConfiguration().getRuntimeConfig().getTransactionManager();
- tm.begin();
- cache1.put("key", "value");
- tm.commit();
-
- assert cache2.get("key").equals("value");
-
- }
-
- public void testSyncTxReplMap() throws Exception
- {
- Integer age;
- TransactionManager tm = cache1.getConfiguration().getRuntimeConfig().getTransactionManager();
- tm.begin();
- Transaction tx = tm.getTransaction();
- Listener lis = new Listener();
-
- cache1.put("age", 38);
- lis.put("name", "Ben");
-
- assert cache1.get("age").equals(38);
- tm.suspend();
- assertNull("age on cache2 must be null as the TX has not yet been committed", cache2.get("age"));
- assertNull("age on cache1 must be null as the TX has been resumed", cache1.get("age"));
- tm.resume(tx);
- assertNotNull("age on cache1 must be not be null", cache1.get("age"));
- tm.commit();
- assertNotNull("age on cache1 must be not be null", cache1.get("age"));
-
- System.out.println(" ********************** ");
- // value on cache2 must be 38
- age = (Integer) cache2.get("age");
- assertNotNull("\"age\" obtained from cache2 must be non-null ", age);
- assertTrue("\"age\" must be 38", age == 38);
- }
-
- public void testSyncReplMap() throws Exception
- {
- Integer age;
-
- Listener lis = new Listener();
- cache1.getNotifier().addCacheListener(lis);
- lis.put("age", 38);
-
- cache1.put("name", "Ben");
- // value on cache2 must be 38
- age = (Integer) cache2.get("age");
- assertNotNull("\"age\" obtained from cache2 must be non-null ", age);
- assertTrue("\"age\" must be 38", age == 38);
- }
-
- @CacheListener
- public class Listener
- {
- Object key = null;
-
- public void put(Object key, Object val)
- {
- this.key = key;
- cache1.put(key, val);
- }
-
- public void put(String fqn, Map map)
- {
- if (map.size() == 0)
- fail("put(): map size can't be 0");
- Set<String> set = map.keySet();
- key = set.iterator().next();// take anyone
- cache1.put(fqn, map);
- }
-
- @CacheEntryModified
- public void nodeModified(Event ne)
- {
- if (!ne.isPre())
- {
- 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);
- }
- catch (CacheException e)
- {
- e.printStackTrace();//To change body of catch statement use File | Settings | File Templates.
- fail("nodeModified: test failed with exception: " + e);
- }
- }
- }
-
- }
-
- @CacheListener
- public class RemoteListener
- {
-
- @CacheEntryRemoved
- @CacheEntryModified
- public void callback(TransactionalEvent e)
- {
- System.out.println("Callback got event " + e);
- log_.debug("Callback got event " + e);
- assertFalse("node was removed on remote cache so isLocal should be false", e.isOriginLocal());
- }
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/replication/SyncCacheListenerTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,249 @@
+/*
+ *
+ * JBoss, the OpenSource J2EE webOS
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.horizon.replication;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+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.notifications.annotation.CacheEntryModified;
+import org.horizon.notifications.annotation.CacheEntryRemoved;
+import org.horizon.notifications.annotation.CacheListener;
+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.Map;
+import java.util.Set;
+
+/**
+ * Test out the TreeCacheListener
+ *
+ * @version $Revision$
+ */
+ at Test(groups = {"functional"}, sequential = true)
+public class SyncCacheListenerTest
+{
+ private CacheSPI<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);
+ conf.setIsolationLevel(IsolationLevel.SERIALIZABLE);
+ 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);
+ }
+
+ private void destroyCaches()
+ {
+ TestingUtil.killCaches(cache1, cache2);
+ cache1 = null;
+ cache2 = null;
+ }
+
+ public void testSyncTxRepl() throws Exception
+ {
+ Integer age;
+ TransactionManager tm = cache1.getTransactionManager();
+
+ tm.begin();
+ Transaction tx = tm.getTransaction();
+ Listener lis = new Listener();
+ cache1.getNotifier().addCacheListener(lis);
+ lis.put("age", 38);
+
+ tm.suspend();
+ assertNull("age on cache2 must be null as the TX has not yet been committed", cache2.get("age"));
+ tm.resume(tx);
+ tm.commit();
+
+ // value on cache2 must be 38
+ age = (Integer) cache2.get("age");
+ assertNotNull("\"age\" obtained from cache2 must be non-null ", age);
+ assertTrue("\"age\" must be 38", age == 38);
+ }
+
+ public void testRemoteCacheListener() throws Exception
+ {
+ Integer age;
+ RemoteListener lis = new RemoteListener();
+ cache2.getNotifier().addCacheListener(lis);
+ cache1.put("age", 38);
+
+ // value on cache2 must be 38
+ age = (Integer) cache2.get("age");
+ assertNotNull("\"age\" obtained from cache2 must be non-null ", age);
+ assertTrue("\"age\" must be 38", age == 38);
+ cache1.remove("age");
+ }
+
+ public void testSyncRepl() throws Exception
+ {
+ Integer age;
+ Listener lis = new Listener();
+ cache1.addCacheListener(lis);
+ lis.put("age", 38);
+
+ // value on cache2 must be 38
+ age = (Integer) cache2.get("age");
+ assertNotNull("\"age\" obtained from cache2 must be non-null ", age);
+ assertTrue("\"age\" must be 38", age == 38);
+ }
+
+
+ public void simpleReplicationTest() throws Exception
+ {
+ TransactionManager tm = cache1.getConfiguration().getRuntimeConfig().getTransactionManager();
+ tm.begin();
+ cache1.put("key", "value");
+ tm.commit();
+
+ assert cache2.get("key").equals("value");
+
+ }
+
+ public void testSyncTxReplMap() throws Exception
+ {
+ Integer age;
+ TransactionManager tm = cache1.getConfiguration().getRuntimeConfig().getTransactionManager();
+ tm.begin();
+ Transaction tx = tm.getTransaction();
+ Listener lis = new Listener();
+
+ cache1.put("age", 38);
+ lis.put("name", "Ben");
+
+ assert cache1.get("age").equals(38);
+ tm.suspend();
+ assertNull("age on cache2 must be null as the TX has not yet been committed", cache2.get("age"));
+ assertNull("age on cache1 must be null as the TX has been resumed", cache1.get("age"));
+ tm.resume(tx);
+ assertNotNull("age on cache1 must be not be null", cache1.get("age"));
+ tm.commit();
+ assertNotNull("age on cache1 must be not be null", cache1.get("age"));
+
+ System.out.println(" ********************** ");
+ // value on cache2 must be 38
+ age = (Integer) cache2.get("age");
+ assertNotNull("\"age\" obtained from cache2 must be non-null ", age);
+ assertTrue("\"age\" must be 38", age == 38);
+ }
+
+ public void testSyncReplMap() throws Exception
+ {
+ Integer age;
+
+ Listener lis = new Listener();
+ cache1.getNotifier().addCacheListener(lis);
+ lis.put("age", 38);
+
+ cache1.put("name", "Ben");
+ // value on cache2 must be 38
+ age = (Integer) cache2.get("age");
+ assertNotNull("\"age\" obtained from cache2 must be non-null ", age);
+ assertTrue("\"age\" must be 38", age == 38);
+ }
+
+ @CacheListener
+ public class Listener
+ {
+ Object key = null;
+
+ public void put(Object key, Object val)
+ {
+ this.key = key;
+ cache1.put(key, val);
+ }
+
+ public void put(String fqn, Map map)
+ {
+ if (map.size() == 0)
+ fail("put(): map size can't be 0");
+ Set<String> set = map.keySet();
+ key = set.iterator().next();// take anyone
+ cache1.put(fqn, map);
+ }
+
+ @CacheEntryModified
+ public void nodeModified(Event ne)
+ {
+ if (!ne.isPre())
+ {
+ 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);
+ }
+ catch (CacheException e)
+ {
+ e.printStackTrace();//To change body of catch statement use File | Settings | File Templates.
+ fail("nodeModified: test failed with exception: " + e);
+ }
+ }
+ }
+
+ }
+
+ @CacheListener
+ public class RemoteListener
+ {
+
+ @CacheEntryRemoved
+ @CacheEntryModified
+ public void callback(TransactionalEvent e)
+ {
+ System.out.println("Callback got event " + e);
+ log_.debug("Callback got event " + e);
+ assertFalse("node was removed on remote cache so isLocal should be false", e.isOriginLocal());
+ }
+ }
+}
Deleted: core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/replication/SyncReplTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,91 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- *
- * Distributable under LGPL license.
- * See terms of license at gnu.org.
- */
-package org.jboss.starobrno.replication;
-
-import static org.testng.AssertJUnit.*;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.jboss.starobrno.Cache;
-import org.jboss.starobrno.UnitTestCacheManager;
-import org.jboss.starobrno.util.TestingUtil;
-import org.jboss.starobrno.config.Configuration;
-
-/**
- * @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
- */
- at Test(groups = {"functional", "jgroups"})
-public class SyncReplTest
-{
- private ThreadLocal<Cache<Object, Object>[]> cachesTL = new ThreadLocal<Cache<Object, Object>[]>();
-
- @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()");
- }
-
- @AfterMethod(alwaysRun = true)
- public void tearDown()
- {
- Cache<Object, Object>[] caches = cachesTL.get();
- if (caches != null) TestingUtil.killCaches(caches);
- cachesTL.set(null);
- }
-
- 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", caches[0].get(k));
- assertNull("Should be null", caches[1].get(k));
-
- caches[0].put(k, v);
-
- assertEquals(v, caches[0].get(k));
- assertEquals("Should have replicated", v, caches[1].get(k));
- }
-
- @SuppressWarnings("unchecked")
- public void testSyncRepl()
- {
- Cache<Object, Object>[] caches = cachesTL.get();
- assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
-
- caches[0].getConfiguration().setSyncCommitPhase(true);
- caches[1].getConfiguration().setSyncCommitPhase(true);
-
- 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"));
- }
-
- private void assertClusterSize(String message, int size)
- {
- Cache<Object, Object>[] caches = cachesTL.get();
- for (Cache c : caches)
- {
- assertClusterSize(message, size, c);
- }
- }
-
- private void assertClusterSize(String message, int size, Cache c)
- {
- assertEquals(message, size, c.getMembers().size());
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/replication/SyncReplTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,91 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.horizon.replication;
+
+import static org.testng.AssertJUnit.*;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.horizon.Cache;
+import org.horizon.UnitTestCacheManager;
+import org.horizon.util.TestingUtil;
+import org.horizon.config.Configuration;
+
+/**
+ * @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
+ */
+ at Test(groups = {"functional", "jgroups"})
+public class SyncReplTest
+{
+ private ThreadLocal<Cache<Object, Object>[]> cachesTL = new ThreadLocal<Cache<Object, Object>[]>();
+
+ @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()");
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown()
+ {
+ Cache<Object, Object>[] caches = cachesTL.get();
+ if (caches != null) TestingUtil.killCaches(caches);
+ cachesTL.set(null);
+ }
+
+ 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", caches[0].get(k));
+ assertNull("Should be null", caches[1].get(k));
+
+ caches[0].put(k, v);
+
+ assertEquals(v, caches[0].get(k));
+ assertEquals("Should have replicated", v, caches[1].get(k));
+ }
+
+ @SuppressWarnings("unchecked")
+ public void testSyncRepl()
+ {
+ Cache<Object, Object>[] caches = cachesTL.get();
+ assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
+
+ caches[0].getConfiguration().setSyncCommitPhase(true);
+ caches[1].getConfiguration().setSyncCommitPhase(true);
+
+ 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"));
+ }
+
+ private void assertClusterSize(String message, int size)
+ {
+ Cache<Object, Object>[] caches = cachesTL.get();
+ for (Cache c : caches)
+ {
+ assertClusterSize(message, size, c);
+ }
+ }
+
+ private void assertClusterSize(String message, int size, Cache c)
+ {
+ assertEquals(message, size, c.getMembers().size());
+ }
+}
Copied: core/branches/flat/src/test/java/org/horizon/tx (from rev 7484, core/branches/flat/src/test/java/org/jboss/starobrno/tx)
Deleted: core/branches/flat/src/test/java/org/horizon/tx/LocalModeTxTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/tx/LocalModeTxTest.java 2009-01-16 11:59:25 UTC (rev 7484)
+++ core/branches/flat/src/test/java/org/horizon/tx/LocalModeTxTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,90 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.starobrno.tx;
-
-import org.jboss.starobrno.CacheSPI;
-import org.jboss.starobrno.UnitTestCacheManager;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.transaction.DummyTransactionManagerLookup;
-import org.jboss.starobrno.util.TestingUtil;
-import org.testng.annotations.Test;
-
-import javax.transaction.Transaction;
-import javax.transaction.TransactionManager;
-
- at Test(groups = "functional")
-public class LocalModeTxTest
-{
- private CacheSPI<String, String> createCache()
- {
- Configuration cfg = new Configuration();
- cfg.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- UnitTestCacheManager cm = new UnitTestCacheManager(cfg);
- return (CacheSPI<String, String>) cm.createCache("test");
- }
-
- public void testTxCommit1() throws Exception
- {
- CacheSPI c = null;
- try
- {
- c = createCache();
- TransactionManager tm = c.getTransactionManager();
- tm.begin();
- c.put("key", "value");
- Transaction t = tm.suspend();
- assert c.isEmpty();
- tm.resume(t);
- tm.commit();
- assert !c.isEmpty();
- }
- finally
- {
- TestingUtil.killCaches(c);
- }
- }
-
- public void testTxCommit2() throws Exception
- {
- CacheSPI c = null;
- try
- {
- c = createCache();
- TransactionManager tm = c.getTransactionManager();
- c.put("key", "old");
- tm.begin();
- assert c.get("key").equals("old");
- c.put("key", "value");
- assert c.get("key").equals("value");
- Transaction t = tm.suspend();
- assert c.get("key").equals("old");
- tm.resume(t);
- tm.commit();
- assert c.get("key").equals("value");
- assert !c.isEmpty();
- }
- finally
- {
- TestingUtil.killCaches(c);
- }
- }
-}
Copied: core/branches/flat/src/test/java/org/horizon/tx/LocalModeTxTest.java (from rev 7485, core/branches/flat/src/test/java/org/jboss/starobrno/tx/LocalModeTxTest.java)
===================================================================
--- core/branches/flat/src/test/java/org/horizon/tx/LocalModeTxTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/horizon/tx/LocalModeTxTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -0,0 +1,90 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.horizon.tx;
+
+import org.horizon.CacheSPI;
+import org.horizon.UnitTestCacheManager;
+import org.horizon.config.Configuration;
+import org.horizon.transaction.DummyTransactionManagerLookup;
+import org.horizon.util.TestingUtil;
+import org.testng.annotations.Test;
+
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
+
+ at Test(groups = "functional")
+public class LocalModeTxTest
+{
+ private CacheSPI<String, String> createCache()
+ {
+ Configuration cfg = new Configuration();
+ cfg.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ UnitTestCacheManager cm = new UnitTestCacheManager(cfg);
+ return (CacheSPI<String, String>) cm.createCache("test");
+ }
+
+ public void testTxCommit1() throws Exception
+ {
+ CacheSPI c = null;
+ try
+ {
+ c = createCache();
+ TransactionManager tm = c.getTransactionManager();
+ tm.begin();
+ c.put("key", "value");
+ Transaction t = tm.suspend();
+ assert c.isEmpty();
+ tm.resume(t);
+ tm.commit();
+ assert !c.isEmpty();
+ }
+ finally
+ {
+ TestingUtil.killCaches(c);
+ }
+ }
+
+ public void testTxCommit2() throws Exception
+ {
+ CacheSPI c = null;
+ try
+ {
+ c = createCache();
+ TransactionManager tm = c.getTransactionManager();
+ c.put("key", "old");
+ tm.begin();
+ assert c.get("key").equals("old");
+ c.put("key", "value");
+ assert c.get("key").equals("value");
+ Transaction t = tm.suspend();
+ assert c.get("key").equals("old");
+ tm.resume(t);
+ tm.commit();
+ assert c.get("key").equals("value");
+ assert !c.isEmpty();
+ }
+ finally
+ {
+ TestingUtil.killCaches(c);
+ }
+ }
+}
Deleted: core/branches/flat/src/test/java/org/jboss/starobrno/BasicTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/BasicTest.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/BasicTest.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,116 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.starobrno;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.horizon.config.Configuration;
-import org.horizon.manager.CacheManager;
-import org.horizon.manager.NamedCacheNotFoundException;
-import org.horizon.util.TestingUtil;
-import org.horizon.Cache;
-import org.horizon.CacheSPI;
-import org.testng.annotations.Test;
-
- at Test(groups = "functional")
-public class BasicTest
-{
- public void basicTest() throws Exception
- {
- // create a cache manager
- Configuration c = new Configuration(); // LOCAL mode
- c.setFetchInMemoryState(false);
- CacheManager cm = new CacheManager(c);
- try
- {
- cm.start();
- Cache cache = cm.getCache("test");
- String key = "key", value = "value";
-
- assert cache.isEmpty();
- assert cache.size() == 0;
- assert !cache.containsKey(key);
-
- cache.put(key, value);
- assert cache.size() == 1;
- assert cache.containsKey(key);
- assert !cache.isEmpty();
-
- assert cache.remove(key).equals(value);
-
- assert cache.isEmpty();
- assert cache.size() == 0;
- assert !cache.containsKey(key);
- }
- finally
- {
- cm.stop();
- }
- }
-
- public static final Log log = LogFactory.getLog(BasicTest.class);
-
- public void testBasicReplication() throws NamedCacheNotFoundException
- {
- Configuration configuration = new Configuration();
- configuration.setCacheMode(Configuration.CacheMode.REPL_SYNC);
-
- CacheManager firstManager = new CacheManager(configuration);
- CacheManager secondManager = new CacheManager(configuration);
-
- try
- {
- firstManager.start();
- secondManager.start();
-
- 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");
- assert firstCache.get("key").equals("value");
- secondCache.put("key", "value2");
- assert firstCache.get("key").equals("value2");
- firstCache.remove("key");
- assert secondCache.get("key") == null;
- }
- finally
- {
- firstManager.stop();
- secondManager.stop();
- }
- }
-
- public void concurrentMapMethodTest()
- {
-
- }
-
- public void transactionalTest()
- {
-
- }
-}
Deleted: core/branches/flat/src/test/java/org/jboss/starobrno/UnitTestCacheFactory.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/UnitTestCacheFactory.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/UnitTestCacheFactory.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,364 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- *
- * Distributable under LGPL license.
- * See terms of license at gnu.org.
- */
-package org.jboss.starobrno;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.cache.CacheFactory;
-import org.horizon.config.Configuration;
-import org.horizon.config.ConfigurationException;
-import org.horizon.config.parsing.XmlConfigurationParserJBC3;
-import org.horizon.manager.CacheManager;
-import org.horizon.util.TestingUtil;
-import org.horizon.Cache;
-import org.jgroups.conf.XmlConfigurator;
-
-import java.io.InputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * @author <a href="mailto:dpospisi at redhat.com">Dominik Pospisil (dpospisi at redhat.com)</a>
- */
-public class UnitTestCacheFactory<K, V> implements CacheFactory<K, V>
-{
-
- private final Log log = LogFactory.getLog(UnitTestCacheFactory.class);
-
-
- /**
- * Holds unique mcast_addr for each thread used for JGroups channel construction.
- */
- private static final ThreadLocal<String> threadMcastIP = new ThreadLocal<String>()
- {
- private final AtomicInteger uniqueAddr = new AtomicInteger(11);
-
- @Override
- protected String initialValue()
- {
- return "228.10.10." + uniqueAddr.getAndIncrement();
- }
- };
-
- /**
- * Holds unique mcast_port for each thread used for JGroups channel construction.
- */
- private static final ThreadLocal<Integer> threadMcastPort = new ThreadLocal<Integer>()
- {
- private final AtomicInteger uniquePort = new AtomicInteger(45589);
-
- @Override
- protected Integer initialValue()
- {
- return uniquePort.getAndIncrement();
- }
- };
-
- /**
- * For each thread holds list of caches created using this factory.
- */
- private static final ThreadLocal<List<Cache>> threadCaches =
- new ThreadLocal<List<Cache>>()
- {
- @Override
- protected List<Cache> initialValue()
- {
- return new ArrayList<Cache>();
- }
- };
-
- private final static List<Cache> allCaches = new ArrayList<Cache>();
-
- /**
- * For each thread holds the name of the test class which executed createCache factory method.
- */
- private static final ThreadLocal<String> threadTestName = new ThreadLocal<String>();
-
- // factory methods
-
- public Cache<K, V> createCache() throws ConfigurationException
- {
- return createCache(true);
- }
-
- public Cache<K, V> createCache(boolean start) throws ConfigurationException
- {
- return createCache(new Configuration(), start);
- }
-
- public Cache<K, V> createCache(String configFileName) throws ConfigurationException
- {
- return createCache(configFileName, true);
- }
-
- public Cache<K, V> createCache(String configFileName, boolean start) throws ConfigurationException
- {
- XmlConfigurationParserJBC3 parser = new XmlConfigurationParserJBC3();
- Configuration c;
- c = parser.parseFile(configFileName);
- return createCache(c, start);
- }
-
- public Cache<K, V> createCache(Configuration configuration) throws ConfigurationException
- {
- return createCache(configuration, true);
- }
-
- public Cache<K, V> createCache(InputStream is) throws ConfigurationException
- {
- return createCache(is, true);
- }
-
- public Cache<K, V> createCache(InputStream is, boolean start) throws ConfigurationException
- {
- XmlConfigurationParserJBC3 parser = new XmlConfigurationParserJBC3();
- Configuration c = parser.parseStream(is);
- return createCache(c, start);
- }
-
- public Cache<K, V> createCache(Configuration configuration, boolean start) throws ConfigurationException
- {
- // - Do not print out this exception - since tests are ALSO run from IDEs on the main thread. - MANIK
-// if (!Thread.currentThread().getName().contains("pool"))
-// {
-// System.out.println("CreateCache called from wrong thread: " + Thread.currentThread().getName());
-// }
-
- checkCaches();
-
- switch (configuration.getCacheMode())
- {
- case LOCAL:
- // local cache, no channel used
- break;
- case REPL_SYNC:
- case REPL_ASYNC:
- case INVALIDATION_ASYNC:
- case INVALIDATION_SYNC:
- // replicated cache, update channel setup
- mangleConfiguration(configuration);
- break;
- default:
- log.info("Unknown cache mode!");
- }
-
-// Cache<K, V> cache = new DefaultCacheFactory<K, V>().createCache(configuration, start);
- CacheManager cm = new CacheManager(configuration);
- Cache<K, V> cache = cm.getCache();
-
- List<Cache> caches = threadCaches.get();
- caches.add(cache);
-
- synchronized (allCaches)
- {
- allCaches.add(cache);
- }
- return cache;
-
- }
-
- /**
- * Destroys all caches created by this factory in the current thread.
- *
- * @return true if some cleanup was actually performed
- */
- public boolean cleanUp()
- {
- List<Cache> caches = new ArrayList<Cache>(threadCaches.get());
- boolean ret = false;
-
- for (Cache cache : caches)
- {
- TestingUtil.killCaches(cache);
- ret = true;
- }
- return ret;
- }
-
- public void removeCache(Cache c)
- {
-
- // - Do not print out this exception - since tests are ALSO run from IDEs on the main thread. - MANIK
-// if (!Thread.currentThread().getName().contains("pool"))
-// {
-// System.out.println("RemoveCache called from wrong thread.");
-// }
-
- List<Cache> caches = threadCaches.get();
- synchronized (allCaches)
- {
- if (caches.contains(c))
- {
- caches.remove(c);
- allCaches.remove(c);
- }
- else if (allCaches.contains(c))
- {
- System.out.println("[" + Thread.currentThread().getName() + "] WARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Remove cache called from different thread.");
- Thread.dumpStack();
- }
- }
- }
-
- /**
- * Updates cluster configuration to ensure mutual thread isolation.
- *
- * @param configuration Configuration to update.
- */
- public void mangleConfiguration(Configuration configuration)
- {
-
- configuration.setClusterConfig(mangleClusterConfiguration(configuration.getClusterConfig()));
- // Check if the cluster name contains thread id. If not, append.
- // We can not just append the threadId, since some of the tests are crating instances
- // using configurations derived from configurations returned by this factory.
-
- String clusterName = configuration.getClusterName();
-
- // append thread id
- if (clusterName.indexOf(Thread.currentThread().getName()) == -1)
- {
- clusterName = clusterName + "-" + Thread.currentThread().getName();
-// System.out.println(getThreadId() + " Setting cluster name " + newClusterName);
- }
-
-// String testName = extractTestName();
-
- // prepend test name
- /*
- if (clusterName.indexOf(testName) == -1) {
- clusterName = testName + "-" + clusterName;
- }
- */
-
- configuration.setClusterName(clusterName);
-
- }
-
- /**
- * Updates cluster configuration to ensure mutual thread isolation.
- */
- public String mangleClusterConfiguration(String clusterConfig)
- {
- if (clusterConfig == null)
- {
- // No explicit cluster configuration found. we need to resolve the default config
- // now in orded to be able to update it before the cache (and the channel) starts.
-
- clusterConfig = getDefaultClusterConfiguration();
- }
-
- // replace mcast_addr
- Pattern pattern = Pattern.compile("mcast_addr=[^;]*");
- Matcher m = pattern.matcher(clusterConfig);
- if (m.find())
- {
- String origAddr = m.group().substring(m.group().indexOf("=") + 1);
- String newAddr = threadMcastIP.get();
-// System.out.println(getThreadId() + " Replacing mcast_addr " + origAddr + " with " + newAddr);
- clusterConfig = m.replaceFirst("mcast_addr=" + newAddr);
- }
- else
- {
- Thread.dumpStack();
- System.exit(1);
- }
-
- // replace mcast_port
- pattern = Pattern.compile("mcast_port=[^;]*");
- m = pattern.matcher(clusterConfig);
- if (m.find())
- {
-// String origPort = m.group().substring(m.group().indexOf("=") + 1);
- String newPort = threadMcastPort.get().toString();
- // System.out.println(getThreadId() + " Replacing mcast_port " + origPort + " with " + newPort);
- clusterConfig = m.replaceFirst("mcast_port=" + newPort);
- }
-
- return clusterConfig;
- }
-
-// private String getThreadId()
-// {
-// return "[" + Thread.currentThread().getName() + "]";
-// }
-
- private void checkCaches()
- {
- String lastTestName = threadTestName.get();
- String currentTestName = extractTestName();
-
- if ((lastTestName != null) && (!lastTestName.equals(currentTestName)))
- {
-
- String threadId = "[" + Thread.currentThread().getName() + "] ";
-
- // we are running new test class
- // check if there is a cache(s) instance left & kill it if possitive
-
- if (cleanUp())
- {
- System.out.print(threadId + "WARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ");
- System.out.print(threadId + " A test method in " + lastTestName + " did not clean all cache instances properly. ");
- System.out.println(threadId + " Use UnitTestCacheFactory.cleanUp() or TestngUtil.killCaches(...) ");
- }
-
- }
- threadTestName.set(currentTestName);
- }
-
- private String extractTestName()
- {
- StackTraceElement[] stack = Thread.currentThread().getStackTrace();
- if (stack.length == 0) return null;
- for (int i = stack.length - 1; i > 0; i--)
- {
- StackTraceElement e = stack[i];
- String className = e.getClassName();
- if (className.indexOf("org.jboss.cache") != -1) return className; //+ "." + e.getMethodName();
- }
- return null;
- }
-
- private String getDefaultClusterConfiguration()
- {
- return getClusterConfigFromFile(new Configuration().getDefaultClusterConfig());
- }
-
- /**
- * Helper method that takes a <b>JGroups</b> configuration file and creates an old-style JGroups config {@link String} that can be used
- * in {@link org.jboss.cache.config.Configuration#setClusterConfig(String)}. Note that expressions
- * in the file - such as <tt>${jgroups.udp.mcast_port:45588}</tt> are expanded out accordingly.
- *
- * @param url url to the cfg file
- * @return a String
- */
- public static String getClusterConfigFromFile(URL url)
- {
- try
- {
- XmlConfigurator conf = XmlConfigurator.getInstance(url);
- String tmp = conf.getProtocolStackString();
- // parse this string for ${} substitutions
- // Highly crappy approach!!
- tmp = tmp.replace("${jgroups.udp.mcast_addr:228.10.10.10}", "228.10.10.10");
- tmp = tmp.replace("${jgroups.udp.mcast_port:45588}", "45588");
- tmp = tmp.replace("${jgroups.udp.ip_ttl:2}", "2");
-// System.out.println("config string: " + tmp);
- return tmp;
- }
- catch (Exception e)
- {
- throw new RuntimeException("Problems with url " + url, e);
- }
- }
-
-}
Deleted: core/branches/flat/src/test/java/org/jboss/starobrno/UnitTestCacheManager.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/UnitTestCacheManager.java 2009-01-16 14:06:35 UTC (rev 7485)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/UnitTestCacheManager.java 2009-01-16 14:44:15 UTC (rev 7486)
@@ -1,33 +0,0 @@
-/*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
-
-package org.jboss.starobrno;
-
-import org.horizon.config.Configuration;
-import org.horizon.Cache;
-
-/**
- * @author dpospisi
- */
-public class UnitTestCacheManager
-{
- Configuration c;
-
- public UnitTestCacheManager(Configuration c)
- {
- this.c = c.clone();
- }
-
- protected Cache createNewCache()
- {
- UnitTestCacheFactory dcf = new UnitTestCacheFactory();
- return dcf.createCache(c);
- }
-
- public Cache createCache(String name)
- {
- return createNewCache();
- }
-}
More information about the jbosscache-commits
mailing list