[jboss-cvs] JBoss Messaging SVN: r4055 - in trunk: src/main/org/jboss/messaging/core/deployers and 63 other directories.
jboss-cvs-commits at lists.jboss.org
jboss-cvs-commits at lists.jboss.org
Tue Apr 15 05:24:11 EDT 2008
Author: ataylor
Date: 2008-04-15 05:24:10 -0400 (Tue, 15 Apr 2008)
New Revision: 4055
Added:
trunk/tests/src/org/jboss/messaging/tests/
trunk/tests/src/org/jboss/messaging/tests/integration/
trunk/tests/src/org/jboss/messaging/tests/integration/CoreClientTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/ProducerFlowControlTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/
trunk/tests/src/org/jboss/messaging/tests/integration/core/asyncio/
trunk/tests/src/org/jboss/messaging/tests/integration/core/asyncio/impl/
trunk/tests/src/org/jboss/messaging/tests/integration/core/asyncio/impl/MultiThreadWriteNativeTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/asyncio/impl/SingleThreadWriteNativeTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/ClientExitTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/DummyInterceptor.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/DummyInterceptorB.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/GracefulClient.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/PacketFilterTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/ClientKeepAliveTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/FilterChainSupportTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaHandlerOrderingTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaHandlerTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaInspectorTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaKeepAliveFactoryTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaRemotingBufferTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaServiceTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaSessionTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/ReversePacketHandler.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/ServerKeepAliveTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/TestSupport.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/ssl/
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/ssl/CoreClientOverSSL.java
trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/ssl/CoreClientOverSSLTest.java
trunk/tests/src/org/jboss/messaging/tests/integration/jms/
trunk/tests/src/org/jboss/messaging/tests/integration/jms/server/
trunk/tests/src/org/jboss/messaging/tests/integration/jms/server/impl/
trunk/tests/src/org/jboss/messaging/tests/integration/jms/server/impl/JMSServerManagerimplTest.java
trunk/tests/src/org/jboss/messaging/tests/stress/
trunk/tests/src/org/jboss/messaging/tests/stress/core/
trunk/tests/src/org/jboss/messaging/tests/stress/core/remoting/
trunk/tests/src/org/jboss/messaging/tests/stress/core/remoting/mina/
trunk/tests/src/org/jboss/messaging/tests/stress/core/remoting/mina/PacketStressTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/
trunk/tests/src/org/jboss/messaging/tests/unit/core/
trunk/tests/src/org/jboss/messaging/tests/unit/core/config/
trunk/tests/src/org/jboss/messaging/tests/unit/core/config/impl/
trunk/tests/src/org/jboss/messaging/tests/unit/core/config/impl/ConfigurationTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/
trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/
trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/DeployerTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/QueueSettingsDeployerTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/SecurityDeployerTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/SecurityManagerDeployerTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/filter/
trunk/tests/src/org/jboss/messaging/tests/unit/core/filter/impl/
trunk/tests/src/org/jboss/messaging/tests/unit/core/filter/impl/FilterParserTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/filter/impl/FilterTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/FakeJournalImplTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/FakeSequentialFileFactoryTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/JournalImplTestBase.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/JournalImplTestUnit.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/NIOSequentialFileFactoryTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/RealJournalImplTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/ReclaimerTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/SequentialFileFactoryTestBase.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/fakes/
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/fakes/FakeSequentialFile.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/fakes/FakeSequentialFileFactory.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/timing/
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/timing/FakeJournalImplTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/timing/JournalImplTestUnit.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/timing/RealJournalImplTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/list/
trunk/tests/src/org/jboss/messaging/tests/unit/core/list/impl/
trunk/tests/src/org/jboss/messaging/tests/unit/core/list/impl/PriorityLinkedListTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/message/
trunk/tests/src/org/jboss/messaging/tests/unit/core/message/impl/
trunk/tests/src/org/jboss/messaging/tests/unit/core/message/impl/MessageTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/postoffice/
trunk/tests/src/org/jboss/messaging/tests/unit/core/postoffice/impl/
trunk/tests/src/org/jboss/messaging/tests/unit/core/postoffice/impl/PostOfficeTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/
trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/ConnectorRegistryTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/PacketDispatcherTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/RemotingConfigurationValidatorTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/TestPacketHandler.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/
trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/ConfigurationHelper.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/SessionTestBase.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/invm/
trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/invm/INVMSessionTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/ssl/
trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/ssl/SSLSupportTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/wireformat/
trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/wireformat/CodecAssert.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/wireformat/PacketTypeTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/security/
trunk/tests/src/org/jboss/messaging/tests/unit/core/security/impl/
trunk/tests/src/org/jboss/messaging/tests/unit/core/security/impl/JAASSecurityManagerTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/security/impl/JBMSecurityManagerImplTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/security/impl/SecurityStoreImplTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/server/
trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/
trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/QueueTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/RoundRobinDistributionPolicyTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/concurrent/
trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/concurrent/QueueTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/fakes/
trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/fakes/FakeConsumer.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/fakes/FakeFilter.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/fakes/FakeQueueFactory.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/timing/
trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/timing/QueueTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/settings/
trunk/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/
trunk/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/QueueSettingsTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/RepositoryTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/transaction/
trunk/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/
trunk/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/MessagingXidTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/TransactionTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/util/
trunk/tests/src/org/jboss/messaging/tests/unit/core/util/SerializedClientSupport.java
trunk/tests/src/org/jboss/messaging/tests/unit/core/util/TokenBucketLimiterTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/jms/
trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/
trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/SelectorTranslatorTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/jms/misc/
trunk/tests/src/org/jboss/messaging/tests/unit/jms/misc/ManifestTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/jms/network/
trunk/tests/src/org/jboss/messaging/tests/unit/jms/network/ClientNetworkFailureTest.java
trunk/tests/src/org/jboss/messaging/tests/unit/jms/network/NetworkFailureFilter.java
trunk/tests/src/org/jboss/messaging/tests/unit/jms/server/
trunk/tests/src/org/jboss/messaging/tests/unit/jms/server/ConnectionManagerTest.java
trunk/tests/src/org/jboss/messaging/tests/util/
trunk/tests/src/org/jboss/messaging/tests/util/InVMContext.java
trunk/tests/src/org/jboss/messaging/tests/util/InVMNameParser.java
trunk/tests/src/org/jboss/messaging/tests/util/InVMSingleInitialContextFactory.java
trunk/tests/src/org/jboss/messaging/tests/util/NonSerializableFactory.java
trunk/tests/src/org/jboss/messaging/tests/util/RandomUtil.java
trunk/tests/src/org/jboss/messaging/tests/util/UnitTestCase.java
Removed:
trunk/tests/src/org/jboss/messaging/core/
trunk/tests/src/org/jboss/messaging/jms/
trunk/tests/src/org/jboss/messaging/test/
trunk/tests/src/org/jboss/test/
Modified:
trunk/build-messaging.xml
trunk/src/main/org/jboss/messaging/core/deployers/DeploymentManager.java
trunk/src/main/org/jboss/messaging/core/filter/impl/FilterImpl.java
trunk/src/main/org/jboss/messaging/core/message/Message.java
trunk/src/main/org/jboss/messaging/core/remoting/ConnectorRegistry.java
trunk/src/main/org/jboss/messaging/microcontainer/JBMBootstrapServer.java
Log:
repacked tests and added javadocs to distro build target
Modified: trunk/build-messaging.xml
===================================================================
--- trunk/build-messaging.xml 2008-04-15 08:19:01 UTC (rev 4054)
+++ trunk/build-messaging.xml 2008-04-15 09:24:10 UTC (rev 4055)
@@ -47,11 +47,15 @@
<property name="messaging.version.minor" value="0"/>
<property name="messaging.version.micro" value="0"/>
<property name="messaging.version.suffix" value="alpha1"/>
+ <property name="messaging.version.tag" value="alpha1"/>
+ <property name="messaging.version.revision" value="0"/>
<property name="messaging.version.incrementing" value="100"/>
<property name="messaging.version.name" value="Stilton"/>
<property name="messaging.version.svnurl" value="https://svn.jboss.org/repos/messaging/trunk"/>
<property name="messaging.version.string"
value="${messaging.version.major}.${messaging.version.minor}.${messaging.version.micro}.${messaging.version.suffix} (${messaging.version.name}, ${messaging.version.incrementing})"/>
+ <property name="module.version"
+ value="${messaging.version.major}.${messaging.version.minor}.${messaging.version.revision}.${messaging.version.tag}"/>
<!--source and build dirs-->
@@ -63,13 +67,16 @@
<property name="src.main.dir" value="${src.dir}/main"/>
<property name="src.etc.dir" value="${src.dir}/etc"/>
<property name="src.bin.dir" value="${src.dir}/bin"/>
+ <property name="doc.dir" value="docs"/>
+ <property name="doc.build.dir" value="${doc.dir}/userguide/build"/>
+ <property name="build.api.dir" value="${build.dir}/api"/>
-
<property name="build.distro.dir"
value="${build.dir}/${module.name}-${messaging.version.major}.${messaging.version.minor}.${messaging.version.micro}.${messaging.version.suffix}"/>
<property name="build.distro.lib.dir" value="${build.distro.dir}/lib"/>
<property name="build.distro.config.dir" value="${build.distro.dir}/config"/>
<property name="build.distro.bin.dir" value="${build.distro.dir}/bin"/>
+ <property name="build.distro.api.dir" value="${build.distro.dir}/api"/>
<!-- ======================================================================================== -->
<!-- Thirdparty Dependency Definitions -->
<!-- ======================================================================================== -->
@@ -188,6 +195,11 @@
<path refid="jboss.dependencies.classpath"/>
</path>
+ <path id="javadoc.classpath">
+ <path refid="compilation.classpath"/>
+ <path location="${build.classes.dir}"/>
+ </path>
+
<path id="test.compilation.classpath">
<path refid="compilation.classpath"/>
<path location="${build.jars.dir}/jboss-${module.name}.jar"/>
@@ -251,7 +263,7 @@
parent, as project root. DO NOT change this.
-->
<property name="external.project" value="true"/>
- <!--
+ <!--
Setting "nodownload" to true inhibits downloading of up-to-date dependencies.
-->
<property name="nodownload" value="false"/>
@@ -351,6 +363,7 @@
<mkdir dir="${build.distro.lib.dir}"/>
<mkdir dir="${build.distro.config.dir}"/>
<mkdir dir="${build.distro.bin.dir}"/>
+ <mkdir dir="${build.distro.api.dir}"/>
<copy todir="${build.distro.lib.dir}">
<fileset dir="${build.jars.dir}">
@@ -452,12 +465,43 @@
</fileset>
</chmod>
+ <antcall target="userdoc"/>
+ <copy todir="${build.distro.dir}/docs/userguide">
+ <fileset dir="${doc.build.dir}">
+ <include name="**"/>
+ </fileset>
+ </copy>
+ <antcall target="javadoc"/>
+ <copy todir="${build.distro.api.dir}/">
+ <fileset dir="${build.api.dir}">
+ <include name="**"/>
+ </fileset>
+ </copy>
</target>
+ <target name="userdoc">
+ <ant dir="./docs/userguide" antfile="build.xml" target="all"/>
+ </target>
+ <target name="javadoc">
+
+ <javadoc destdir="${build.api.dir}" author="true" version="true" use="true"
+ windowtitle="JBoss Messaging ${module.version}">
+
+ <packageset dir="${src.main.dir}" defaultexcludes="yes">
+ <include name="org/jboss/**"/>
+ </packageset>
+ <classpath refid="javadoc.classpath"/>
+ <doctitle><![CDATA[<h2>JBoss Messaging ${module.version}</h2>]]></doctitle>
+ <bottom><![CDATA[<i>Copyright © 2006 JBoss Inc. All Rights Reserved.</i>]]></bottom>
+ <tag name="todo" scope="all" description="To do:"/>
+ <group title="JMS Facade" packages="org.jboss.jms.*"/>
+ <group title="Messaging Core" packages="org.jboss.messaging.*"/>
+ </javadoc>
+ </target>
+
<!-- test targets -->
-
<target name="compile-unit-tests">
<mkdir dir="${test.classes.dir}"/>
<javac target="${javac.target}"
@@ -533,8 +577,8 @@
haltonerror="${junit.batchtest.haltonerror}">
<formatter type="plain" usefile="${junit.formatter.usefile}"/>
<fileset dir="${test.classes.dir}">
- <include name="**/org/jboss/**/*${test-mask}.class"/>
- <exclude name="**/org/jboss/**/PacketStressTest.class"/>
+ <include name="**/org/jboss/messaging/tests/integration/**/*${test-mask}.class"/>
+ <include name="**/org/jboss/messaging/tests/unit/**/*${test-mask}.class"/>
</fileset>
</batchtest>
</junit>
@@ -565,7 +609,7 @@
<jvmarg value="-Xmx1024M"/>
<!--<jvmarg line="-Xmx512M -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"/>-->
<!--<jvmarg value="-ea"/>-->
- <sysproperty key="jbm.remoting.disable.invm" value="${disable.invm}" />
+ <sysproperty key="jbm.remoting.disable.invm" value="${disable.invm}"/>
<classpath refid="jms.test.execution.classpath"/>
<formatter type="xml" usefile="${junit.formatter.usefile}"/>
<batchtest todir="${junit.batchtest.todir}"
@@ -600,6 +644,38 @@
<antcall target="compile-reports"/>
</target>
+ <target name="stress-tests" depends="jar, compile-unit-tests">
+ <echo message=""/>
+ <echo message="Running unit tests, fork=${junit.fork}, junit.batchtest.fork=${junit.batchtest.fork}"/>
+ <echo message=""/>
+ <mkdir dir="${test.output.dir}"/>
+ <mkdir dir="${test.reports.dir}"/>
+ <junit printsummary="${junit.printsummary}"
+ fork="on"
+ forkMode="once"
+ includeantruntime="${junit.includeantruntime}"
+ haltonerror="${junit.haltonerror}"
+ haltonfailure="${junit.haltonfailure}"
+ showoutput="${junit.showoutput}"
+ timeout="${junit.timeout}">
+
+ <jvmarg value="-Xmx1024M"/>
+ <!--<jvmarg line="-Xmx512M -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"/>-->
+ <!--<jvmarg value="-ea"/>-->
+ <classpath refid="unit.test.execution.classpath"/>
+ <formatter type="xml" usefile="${junit.formatter.usefile}"/>
+ <batchtest todir="${junit.batchtest.todir}"
+ haltonfailure="${junit.batchtest.haltonfailure}"
+ haltonerror="${junit.batchtest.haltonerror}">
+ <formatter type="plain" usefile="${junit.formatter.usefile}"/>
+ <fileset dir="${test.classes.dir}">
+ <include name="**/org/jboss/messaging/tests/stress/**/*${test-mask}.class"/>
+ </fileset>
+ </batchtest>
+ </junit>
+ <antcall target="compile-reports"/>
+ </target>
+
<target name="all-tests" depends="unit-tests, jms-tests"/>
<target name="compile-reports">
Modified: trunk/src/main/org/jboss/messaging/core/deployers/DeploymentManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/deployers/DeploymentManager.java 2008-04-15 08:19:01 UTC (rev 4054)
+++ trunk/src/main/org/jboss/messaging/core/deployers/DeploymentManager.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -33,7 +33,7 @@
/**
* registers a deployable object which will handle the deployment of URL's
*
- * @param deployable The deployable object
+ * @param deployer The deployable object
* @throws Exception .
*/
public void registerDeployer(Deployer deployer) throws Exception;
@@ -41,7 +41,7 @@
/**
* unregisters a deployable object which will handle the deployment of URL's
*
- * @param deployable The deployable object
+ * @param deployer The deployable object
* @throws Exception .
*/
public void unregisterDeployer(Deployer deployer);
Modified: trunk/src/main/org/jboss/messaging/core/filter/impl/FilterImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/filter/impl/FilterImpl.java 2008-04-15 08:19:01 UTC (rev 4054)
+++ trunk/src/main/org/jboss/messaging/core/filter/impl/FilterImpl.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -51,7 +51,7 @@
* @author <a href="mailto:jplindfo at helsinki.fi">Juha Lindfors</a>
* @author <a href="mailto:jason at planet57.com">Jason Dillon</a>
* @author <a href="mailto:Scott.Stark at jboss.org">Scott Stark</a>
-* @authro <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+* @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
*
* @version $Revision: 3569 $
*
Modified: trunk/src/main/org/jboss/messaging/core/message/Message.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/message/Message.java 2008-04-15 08:19:01 UTC (rev 4054)
+++ trunk/src/main/org/jboss/messaging/core/message/Message.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -61,7 +61,7 @@
/**
* Set whether message is durable
- * @param reliable
+ * @param durable
*/
void setDurable(boolean durable);
@@ -186,7 +186,7 @@
/**
* Get the connection id
- * @return
+ * @return the connection id
*/
long getConnectionID();
@@ -214,7 +214,7 @@
/**
* Get the current durable reference count
- * @return
+ * @return the durable ref count
*/
int getDurableRefCount();
Modified: trunk/src/main/org/jboss/messaging/core/remoting/ConnectorRegistry.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/ConnectorRegistry.java 2008-04-15 08:19:01 UTC (rev 4054)
+++ trunk/src/main/org/jboss/messaging/core/remoting/ConnectorRegistry.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -16,7 +16,7 @@
*
* When a {@link MinaService} is started, it register its {@link Configuration}.
*
- * When a {@link ClientImpl} is created, it gets its {@link NIOConnector} from the
+ * When a client is created, it gets its {@link NIOConnector} from the
* ConnectorRegistry using the {@link Configuration} corresponding to the server
* it wants to connect to. If the ConnectionRegistry contains this Configuration, it
* implies that the Client is in the same VM than the server. In that case, we
@@ -52,7 +52,7 @@
* If there is only one reference, remove it from the connectors Map and
* returns it. Otherwise return null.
*
- * @param remotingConfig
+ * @param config
* a Configuration
* @return the NIOConnector if there is no longer any references to it or
* <code>null</code>
Modified: trunk/src/main/org/jboss/messaging/microcontainer/JBMBootstrapServer.java
===================================================================
--- trunk/src/main/org/jboss/messaging/microcontainer/JBMBootstrapServer.java 2008-04-15 08:19:01 UTC (rev 4054)
+++ trunk/src/main/org/jboss/messaging/microcontainer/JBMBootstrapServer.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -152,7 +152,7 @@
/**
* Deploys a XML on the container
- * @author clebert.suconic at jboss.com
+ *
*/
public KernelDeployment deploy(String name, String xml) throws Throwable
{
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/CoreClientTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/integration/test/CoreClientTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/CoreClientTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/CoreClientTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,86 @@
+package org.jboss.messaging.tests.integration;
+
+import static org.jboss.messaging.core.remoting.TransportType.INVM;
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.client.ClientConnection;
+import org.jboss.messaging.core.client.ClientConnectionFactory;
+import org.jboss.messaging.core.client.ClientConsumer;
+import org.jboss.messaging.core.client.ClientProducer;
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.client.impl.ClientConnectionFactoryImpl;
+import org.jboss.messaging.core.config.impl.ConfigurationImpl;
+import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.core.message.impl.MessageImpl;
+import org.jboss.messaging.core.server.impl.MessagingServerImpl;
+import org.jboss.messaging.jms.client.JBossTextMessage;
+
+public class CoreClientTest extends TestCase
+{
+ // Constants -----------------------------------------------------
+
+ private final String QUEUE = "CoreClientTestQueue";
+ // Attributes ----------------------------------------------------
+
+ private ConfigurationImpl conf;
+ private MessagingServerImpl invmServer;
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+
+ conf = new ConfigurationImpl();
+ conf.setInvmDisabled(false);
+ conf.setTransport(INVM);
+ invmServer = new MessagingServerImpl(conf);
+ invmServer.start();
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ invmServer.stop();
+
+ super.tearDown();
+ }
+
+
+ public void testINVMCoreClient() throws Exception
+ {
+ ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0, invmServer.getConfiguration(), invmServer.getVersion());
+ ClientConnection conn = cf.createConnection();
+
+ ClientSession session = conn.createClientSession(false, true, true, -1, false, false);
+ session.createQueue(QUEUE, QUEUE, null, false, false);
+
+ ClientProducer producer = session.createProducer(QUEUE);
+
+ Message message = new MessageImpl(JBossTextMessage.TYPE, false, 0,
+ System.currentTimeMillis(), (byte) 1);
+ message.setPayload("testINVMCoreClient".getBytes());
+ producer.send(message);
+
+ ClientConsumer consumer = session.createConsumer(QUEUE, null, false, false, true);
+ conn.start();
+
+ message = consumer.receive(1000);
+ assertEquals("testINVMCoreClient", new String(message.getPayload()));
+
+ conn.close();
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/ProducerFlowControlTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/integration/test/ProducerFlowControlTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/ProducerFlowControlTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/ProducerFlowControlTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,279 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.integration;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.client.ClientProducer;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.core.message.impl.MessageImpl;
+
+/**
+ *
+ * A ProducerFlowControlTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class ProducerFlowControlTest extends TestCase
+{
+ private static final Logger log = Logger.getLogger(ProducerFlowControlTest.class);
+
+
+// public void testFlowControl() throws Exception
+// {
+// ClientConnection conn = null;
+//
+// MessagingServer server = null;
+//
+// try
+// {
+// RemotingConfiguration remotingConf = new RemotingConfiguration(TransportType.TCP, "localhost", 7654);
+//
+// remotingConf.setInvmDisabled(true);
+//
+// server = new MessagingServerImpl(remotingConf);
+//
+// QueueSettings settings = new QueueSettings();
+//
+// settings.setMaxSize(10);
+//
+// server.getQueueSettingsRepository().addMatch("queue1", settings);
+//
+// server.start();
+//
+// ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0, remotingConf, server.getVersion());
+//
+// conn = cf.createConnection(null, null);
+//
+// final ClientSession session1 = conn.createClientSession(false, true, true, 1, false);
+//
+// session1.createQueue("queue1", "queue1", null, false, false);
+//
+// final ClientSession session2 = conn.createClientSession(false, true, true, 1, false);
+//
+// final ClientSession session3 = conn.createClientSession(false, true, true, 1, false);
+//
+// ClientProducer producer1 = session1.createProducer("queue1");
+//
+// ClientProducer producer2 = session2.createProducer("queue1");
+//
+// ClientProducer producer3 = session3.createProducer("queue1");
+//
+// ClientConsumer consumer =
+// session1.createConsumer("queue1", null, false, false, false);
+//
+// MessageHandler handler = new MessageHandler() {
+// public void onMessage(Message msg)
+// {
+// try
+// {
+// log.info("Got message " + msg.getHeader("count"));
+//
+// Thread.sleep(1000);
+//
+// session1.acknowledge();
+// }
+// catch(Exception e)
+// {
+// e.printStackTrace();
+// }
+// }
+// };
+//
+// consumer.setMessageHandler(handler);
+//
+// conn.start();
+//
+// Thread thread1 = new ProducerThread(producer1, "producer1");
+//
+// Thread thread2 = new ProducerThread(producer2, "producer2");
+//
+// Thread thread3 = new ProducerThread(producer3, "producer3");
+//
+// thread1.start();
+//
+// thread2.start();
+//
+// thread3.start();
+//
+// thread1.join();
+//
+// thread2.join();
+//
+// thread3.join();
+//
+// }
+// finally
+// {
+// if (conn != null)
+// {
+// conn.close();
+// }
+//
+// if (server != null)
+// {
+// server.stop();
+// }
+// }
+//
+//
+// }
+//
+
+// public void testFlowControlRate() throws Exception
+// {
+// ClientConnection conn = null;
+//
+// MessagingServer server = null;
+//
+// try
+// {
+// RemotingConfiguration remotingConf = new RemotingConfiguration(TransportType.TCP, "localhost", 7654);
+//
+// remotingConf.setInvmDisabled(true);
+//
+// server = new MessagingServerImpl(remotingConf);
+//
+// server.start();
+//
+// ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0, remotingConf, server.getVersion());
+//
+// conn = cf.createConnection(null, null);
+//
+// final ClientSession session1 = conn.createClientSession(false, true, true, 1, false);
+//
+// session1.createQueue("queue1", "queue1", null, false, false);
+//
+// final ClientSession session2 = conn.createClientSession(false, true, true, 1, false);
+//
+// final ClientSession session3 = conn.createClientSession(false, true, true, 1, false);
+//
+// ClientProducer producer1 = session1.createRateLimitedProducer("queue1", 10);
+//
+// ClientProducer producer2 = session2.createRateLimitedProducer("queue1", 1);
+//
+// ClientProducer producer3 = session3.createRateLimitedProducer("queue1", 5);
+//
+// ClientConsumer consumer =
+// session1.createConsumer("queue1", null, false, false, false);
+//
+// MessageHandler handler = new MessageHandler() {
+// public void onMessage(Message msg)
+// {
+// try
+// {
+// log.info("Got message " + msg.getHeader("count"));
+//
+// Thread.sleep(1000);
+//
+// session1.acknowledge();
+// }
+// catch(Exception e)
+// {
+// e.printStackTrace();
+// }
+// }
+// };
+//
+// consumer.setMessageHandler(handler);
+//
+// conn.start();
+//
+// Thread thread1 = new ProducerThread(producer1, "producer1");
+//
+// Thread thread2 = new ProducerThread(producer2, "producer2");
+//
+// Thread thread3 = new ProducerThread(producer3, "producer3");
+//
+// thread1.start();
+//
+// thread2.start();
+//
+// thread3.start();
+//
+// thread1.join();
+//
+// thread2.join();
+//
+// thread3.join();
+//
+// }
+// finally
+// {
+// if (conn != null)
+// {
+// conn.close();
+// }
+//
+// if (server != null)
+// {
+// server.stop();
+// }
+// }
+//
+//
+// }
+
+
+ public void testNull()
+ {}
+
+ class ProducerThread extends Thread
+ {
+ final ClientProducer producer;
+
+ final String producerName;
+
+ int count;
+
+ ProducerThread(ClientProducer producer, String producerName)
+ {
+ this.producer = producer;
+
+ this.producerName = producerName;
+ }
+
+ public void run()
+ {
+ try
+ {
+ while (true)
+ {
+ Message message = new MessageImpl(7, false, 0, System.currentTimeMillis(), (byte) 1);
+
+ message.putHeader("count", count++);
+
+ producer.send(message);
+
+ log.info("Producer " + producerName + " sent message " + count);
+ }
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ }
+ }
+ }
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/asyncio/impl/MultiThreadWriteNativeTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/asyncio/impl/test/integration/MultiThreadWriteNativeTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/asyncio/impl/MultiThreadWriteNativeTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/asyncio/impl/MultiThreadWriteNativeTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,308 @@
+/*
+ * JBoss, the OpenSource J2EE webOS
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+
+package org.jboss.messaging.tests.integration.core.asyncio.impl;
+
+import java.io.File;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.asyncio.AIOCallback;
+import org.jboss.messaging.core.asyncio.impl.JlibAIO;
+import org.jboss.messaging.core.logging.Logger;
+
+// you need to define java.library.path=${project-root}/native/src/.libs
+public class MultiThreadWriteNativeTest extends TestCase
+{
+
+ static Logger log = Logger.getLogger(MultiThreadWriteNativeTest.class);
+
+ static AtomicInteger position = new AtomicInteger(0);
+
+ String FILE_NAME="/tmp/libaio.log";
+
+ static final int SIZE = 1024;
+ static final int NUMBER_OF_THREADS = 40;
+ static final int NUMBER_OF_LINES = 5000;
+
+// Executor exec
+
+ static Executor executor = Executors.newSingleThreadExecutor();
+
+ static Semaphore semaphore = new Semaphore(1, false);
+
+
+ static class ExecClass implements Runnable
+ {
+
+ JlibAIO aio;
+ ByteBuffer buffer;
+ AIOCallback callback;
+
+
+ public ExecClass(JlibAIO aio, ByteBuffer buffer, AIOCallback callback)
+ {
+ this.aio = aio;
+ this.buffer = buffer;
+ this.callback = callback;
+ }
+
+ public void run()
+ {
+ try
+ {
+ aio.write(getNewPosition()*SIZE, SIZE, buffer, callback);
+
+ }
+ catch (Exception e)
+ {
+ callback.onError(-1, e.toString());
+ e.printStackTrace();
+ }
+ finally
+ {
+ try { semaphore.release(); } catch (Exception ignored){}
+ }
+ }
+
+ }
+
+
+
+ private static void addData(JlibAIO aio, ByteBuffer buffer, AIOCallback callback) throws Exception
+ {
+ //aio.write(getNewPosition()*SIZE, SIZE, buffer, callback);
+ executor.execute(new ExecClass(aio, buffer, callback));
+
+ //semaphore.acquire();
+ //try
+ //{
+ //aio.write(getNewPosition()*SIZE, SIZE, buffer, callback);
+ //}
+ //finally
+ //{
+ // semaphore.release();
+ //}
+
+
+
+ }
+
+
+
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+ File file = new File(FILE_NAME);
+ file.delete();
+
+ position.set(0);
+ }
+
+ public void testMultipleASynchronousWrites() throws Throwable
+ {
+ executeTest(false);
+ }
+
+ public void testMultipleSynchronousWrites() throws Throwable
+ {
+ executeTest(true);
+ }
+
+ private void executeTest(boolean sync) throws Throwable
+ {
+ log.info(sync?"Sync test:":"Async test");
+ JlibAIO jlibAIO = new JlibAIO();
+ jlibAIO.open(FILE_NAME, 21000);
+ log.debug("Preallocating file");
+ jlibAIO.preAllocate(NUMBER_OF_THREADS, SIZE * NUMBER_OF_LINES);
+ log.debug("Done Preallocating file");
+
+ CountDownLatch latchStart = new CountDownLatch (NUMBER_OF_THREADS + 1);
+
+ ArrayList<ThreadProducer> list = new ArrayList<ThreadProducer>(NUMBER_OF_THREADS);
+ for(int i=0;i<NUMBER_OF_THREADS;i++)
+ {
+ ThreadProducer producer = new ThreadProducer("Thread " + i, latchStart, jlibAIO, sync);
+ list.add(producer);
+ producer.start();
+ }
+
+ latchStart.countDown();
+ latchStart.await();
+
+
+ long startTime = System.currentTimeMillis();
+
+
+
+ for (ThreadProducer producer: list)
+ {
+ producer.join();
+ if (producer.failed != null)
+ {
+ throw producer.failed;
+ }
+ }
+ long endTime = System.currentTimeMillis();
+
+ log.debug((sync?"Sync result:":"Async result:") + " Records/Second = " + (NUMBER_OF_THREADS * NUMBER_OF_LINES * 1000 / (endTime - startTime)) + " total time = " + (endTime - startTime) + " total number of records = " + (NUMBER_OF_THREADS * NUMBER_OF_LINES));
+
+ jlibAIO.close();
+
+ }
+
+
+
+
+ private static int getNewPosition()
+ {
+ return position.addAndGet(1);
+ }
+
+ static class ThreadProducer extends Thread
+ {
+
+ Throwable failed = null;
+ CountDownLatch latchStart;
+ boolean sync;
+ JlibAIO libaio;
+
+ public ThreadProducer(String name, CountDownLatch latchStart, JlibAIO libaio, boolean sync)
+ {
+ super(name);
+ this.latchStart = latchStart;
+ this.libaio = libaio;
+ this.sync = sync;
+ }
+
+ public void run()
+ {
+ super.run();
+
+
+ try
+ {
+
+ ByteBuffer buffer = libaio.newBuffer(SIZE);
+
+ // I'm aways reusing the same buffer, as I don't want any noise from malloc on the measurement
+ // Encoding buffer
+ addString ("Thread name=" + Thread.currentThread().getName() + ";" + "\n", buffer);
+ for (int local = buffer.position(); local < buffer.capacity() - 1; local++)
+ {
+ buffer.put((byte)' ');
+ }
+ buffer.put((byte)'\n');
+
+
+ latchStart.countDown();
+ latchStart.await();
+
+ long startTime = System.currentTimeMillis();
+
+
+ CountDownLatch latchFinishThread = null;
+
+ if (!sync) latchFinishThread = new CountDownLatch(NUMBER_OF_LINES);
+
+ LinkedList<LocalCallback> list = new LinkedList<LocalCallback>();
+
+ for (int i=0;i<NUMBER_OF_LINES;i++)
+ {
+
+ if (sync) latchFinishThread = new CountDownLatch(1);
+ LocalCallback callback = new LocalCallback(latchFinishThread, buffer, libaio);
+ if (!sync) list.add(callback);
+ addData(libaio, buffer,callback);
+ if (sync)
+ {
+ latchFinishThread.await();
+ assertTrue(callback.doneCalled);
+ assertFalse(callback.errorCalled);
+ }
+ }
+ if (!sync) latchFinishThread.await();
+ for (LocalCallback callback: list)
+ {
+ assertTrue (callback.doneCalled);
+ assertFalse (callback.errorCalled);
+ }
+
+ long endtime = System.currentTimeMillis();
+
+ log.debug(Thread.currentThread().getName() + " Rec/Sec= " + (NUMBER_OF_LINES * 1000 / (endtime-startTime)) + " total time = " + (endtime-startTime) + " number of lines=" + NUMBER_OF_LINES);
+
+ libaio.destroyBuffer(buffer);
+
+
+ for (LocalCallback callback: list)
+ {
+ assertTrue (callback.doneCalled);
+ assertFalse (callback.errorCalled);
+ }
+
+ }
+ catch (Throwable e)
+ {
+ e.printStackTrace();
+ failed = e;
+ }
+
+ }
+ }
+
+ private static void addString(String str, ByteBuffer buffer)
+ {
+ byte bytes[] = str.getBytes();
+ //buffer.putInt(bytes.length);
+ buffer.put(bytes);
+ //CharBuffer charBuffer = CharBuffer.wrap(str);
+ //UTF_8_ENCODER.encode(charBuffer, buffer, true);
+
+ }
+
+ static class LocalCallback implements AIOCallback
+ {
+ boolean doneCalled = false;
+ boolean errorCalled = false;
+ CountDownLatch latchDone;
+ ByteBuffer releaseMe;
+ JlibAIO libaio;
+
+ public LocalCallback(CountDownLatch latchDone, ByteBuffer releaseMe, JlibAIO libaio)
+ {
+ this.latchDone = latchDone;
+ this.releaseMe = releaseMe;
+ this.libaio = libaio;
+ }
+
+ public void done()
+ {
+ doneCalled=true;
+ latchDone.countDown();
+ //libaio.destroyBuffer(releaseMe);
+ }
+
+ public void onError(int errorCode, String errorMessage)
+ {
+ errorCalled=true;
+ latchDone.countDown();
+ libaio.destroyBuffer(releaseMe);
+ }
+
+ }
+}
Property changes on: trunk/tests/src/org/jboss/messaging/tests/integration/core/asyncio/impl/MultiThreadWriteNativeTest.java
___________________________________________________________________
Name: svn:keywords
+ Id LastChangedDate Author Revision
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/asyncio/impl/SingleThreadWriteNativeTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/asyncio/impl/test/integration/SingleThreadWriteNativeTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/asyncio/impl/SingleThreadWriteNativeTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/asyncio/impl/SingleThreadWriteNativeTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,409 @@
+/*
+ * JBoss, the OpenSource J2EE webOS
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+
+package org.jboss.messaging.tests.integration.core.asyncio.impl;
+
+import java.io.File;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetEncoder;
+import java.util.ArrayList;
+import java.util.concurrent.CountDownLatch;
+
+import org.jboss.messaging.core.asyncio.AIOCallback;
+import org.jboss.messaging.core.asyncio.impl.JlibAIO;
+
+import junit.framework.TestCase;
+
+//you need to define java.library.path=${project-root}/native/src/.libs
+public class SingleThreadWriteNativeTest extends TestCase
+{
+ private static CharsetEncoder UTF_8_ENCODER = Charset.forName("UTF-8").newEncoder();
+
+
+ byte commonBuffer[] = null;
+
+ String FILE_NAME="/tmp/libaio.log";
+
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+ LocalAIO.staticDone = 0;
+ File file = new File(FILE_NAME);
+ file.delete();
+ }
+
+ private void encodeBufer(ByteBuffer buffer)
+ {
+ buffer.clear();
+ int size = buffer.limit();
+ for (int i=0;i<size-1;i++)
+ {
+ buffer.put((byte)('a' + (i%20)));
+ }
+
+ buffer.put((byte)'\n');
+
+ }
+
+ public void testAddBeyongSimultaneousLimit() throws Exception
+ {
+ asyncData(150000,1024,100);
+ }
+
+ public void testAddAsyncData() throws Exception
+ {
+ asyncData(150000,1024,20000);
+ }
+
+ public void testRead() throws Exception
+ {
+
+
+
+
+ final JlibAIO controller = new JlibAIO();
+ try
+ {
+
+ final int NUMBER_LINES = 300;
+ final int SIZE = 1024;
+
+ controller.open(FILE_NAME, 10);
+
+ ByteBuffer buffer = controller.newBuffer(SIZE);
+
+
+ for (int i=0; i<NUMBER_LINES; i++)
+ {
+ buffer.clear();
+ addString ("Str value " + i + "\n", buffer);
+ for (int j=buffer.position(); j<buffer.capacity()-1;j++)
+ {
+ buffer.put((byte)' ');
+ }
+ buffer.put((byte)'\n');
+
+
+ CountDownLatch latch = new CountDownLatch(1);
+ LocalAIO aio = new LocalAIO(latch);
+ controller.write(i * SIZE, SIZE, buffer, aio);
+ latch.await();
+ assertFalse(aio.errorCalled);
+ assertTrue(aio.doneCalled);
+ }
+
+ ByteBuffer newBuffer = ByteBuffer.allocateDirect(SIZE);
+
+ for (int i=0; i<NUMBER_LINES; i++)
+ {
+ newBuffer.clear();
+ addString ("Str value " + i + "\n", newBuffer);
+ for (int j=newBuffer.position(); j<newBuffer.capacity()-1;j++)
+ {
+ newBuffer.put((byte)' ');
+ }
+ newBuffer.put((byte)'\n');
+
+
+ CountDownLatch latch = new CountDownLatch(1);
+ LocalAIO aio = new LocalAIO(latch);
+ controller.read(i * SIZE, SIZE, buffer, aio);
+ latch.await();
+ assertFalse(aio.errorCalled);
+ assertTrue(aio.doneCalled);
+
+ byte bytesRead[] = new byte[SIZE];
+ byte bytesCompare[] = new byte[SIZE];
+
+ newBuffer.rewind();
+ newBuffer.get(bytesCompare);
+ buffer.rewind();
+ buffer.get(bytesRead);
+
+ for (int count=0;count<SIZE;count++)
+ {
+ assertEquals("byte position " + count + " differs on line " + i, bytesCompare[count], bytesRead[count]);
+ }
+
+
+ //byte[] byteCompare = new byte[SIZE];
+ //byte[] byteRead = new byte[SIZE];
+
+ assertTrue(buffer.equals(newBuffer));
+ }
+
+ controller.destroyBuffer(buffer);
+ }
+ finally
+ {
+ try { controller.close(); } catch (Throwable ignored){}
+
+ }
+
+ }
+
+ private void asyncData(int numberOfLines, int size, int aioLimit) throws Exception
+ {
+ final JlibAIO controller = new JlibAIO();
+ controller.open(FILE_NAME, aioLimit);
+
+ try
+ {
+ System.out.println("++testDirectDataNoPage"); System.out.flush();
+ CountDownLatch latchDone = new CountDownLatch(numberOfLines);
+
+ ByteBuffer block = controller.newBuffer(size);
+ encodeBufer(block);
+
+ preAlloc(controller, numberOfLines * size);
+
+ ArrayList<LocalAIO> list = new ArrayList<LocalAIO>();
+
+ for (int i=0; i<numberOfLines; i++)
+ {
+ list.add(new LocalAIO(latchDone));
+ }
+
+
+ long valueInitial = System.currentTimeMillis();
+
+ System.out.println("Adding data");
+
+ long lastTime = System.currentTimeMillis();
+ int counter = 0;
+ for (LocalAIO tmp: list)
+ {
+ controller.write(counter * size, size, block, tmp);
+ if (++counter % 5000 == 0)
+ {
+ System.out.println(5000*1000/(System.currentTimeMillis()-lastTime) + " rec/sec (Async)");
+ lastTime = System.currentTimeMillis();
+ }
+
+ }
+
+ System.out.println("Data added " + (System.currentTimeMillis() - valueInitial));
+
+
+ System.out.println("Finished append " + (System.currentTimeMillis() - valueInitial) + " received = " + LocalAIO.staticDone);
+ System.out.println("Flush now");
+ System.out.println("Received " + LocalAIO.staticDone);
+ long timeTotal = System.currentTimeMillis() - valueInitial;
+
+ System.out.println("Asynchronous time = " + timeTotal + " for " + numberOfLines + " registers " + " size each line = " + size + " Records/Sec=" + (numberOfLines*1000/timeTotal) + " (Assynchronous)");
+
+ latchDone.await();
+
+ timeTotal = System.currentTimeMillis() - valueInitial;
+ System.out.println("After completions time = " + timeTotal + " for " + numberOfLines + " registers " + " size each line = " + size + " Records/Sec=" + (numberOfLines*1000/timeTotal) + " (Assynchronous)");
+
+ for (LocalAIO tmp: list)
+ {
+ assertEquals(1, tmp.timesDoneCalled);
+ assertTrue(tmp.doneCalled);
+ assertFalse(tmp.errorCalled);
+ }
+
+ controller.destroyBuffer(block);
+
+ controller.close();
+ }
+ finally
+ {
+ try {controller.close();} catch (Exception ignored){}
+ }
+
+
+ }
+
+ public void testDirectSynchronous() throws Exception
+ {
+ try
+ {
+ System.out.println("++testDirectDataNoPage"); System.out.flush();
+ final int NUMBER_LINES = 10000;
+ final int SIZE = 1024;
+ //final int SIZE = 512;
+
+ final JlibAIO controller = new JlibAIO();
+ controller.open(FILE_NAME, 2000);
+
+ ByteBuffer block = controller.newBuffer(SIZE);
+ encodeBufer(block);
+
+ preAlloc(controller, NUMBER_LINES * SIZE);
+
+ long valueInitial = System.currentTimeMillis();
+
+ System.out.println("Adding data");
+
+ long lastTime = System.currentTimeMillis();
+ int counter = 0;
+
+ for (int i=0; i<NUMBER_LINES; i++)
+ {
+ CountDownLatch latchDone = new CountDownLatch(1);
+ LocalAIO aioBlock = new LocalAIO(latchDone);
+ controller.write(i*512, 512, block, aioBlock);
+ latchDone.await();
+ assertTrue(aioBlock.doneCalled);
+ assertFalse(aioBlock.errorCalled);
+ if (++counter % 500 == 0)
+ {
+ System.out.println(500*1000/(System.currentTimeMillis()-lastTime) + " rec/sec (Synchronous)");
+ lastTime = System.currentTimeMillis();
+ }
+ }
+
+ System.out.println("Data added " + (System.currentTimeMillis() - valueInitial));
+
+
+ System.out.println("Finished append " + (System.currentTimeMillis() - valueInitial) + " received = " + LocalAIO.staticDone);
+ System.out.println("Flush now");
+ System.out.println("Received " + LocalAIO.staticDone);
+
+ long timeTotal = System.currentTimeMillis() - valueInitial;
+ System.out.println("Flushed " + timeTotal);
+ System.out.println("time = " + timeTotal + " for " + NUMBER_LINES + " registers " + " size each line = " + SIZE + " Records/Sec=" + (NUMBER_LINES*1000/timeTotal) + " Synchronous");
+
+ controller.destroyBuffer(block);
+ controller.close();
+ }
+ catch (Exception e)
+ {
+ System.out.println("Received " + LocalAIO.staticDone + " before it failed");
+ throw e;
+ }
+
+ }
+
+ private void preAlloc(JlibAIO controller, long size)
+ {
+ System.out.println("Pre allocating"); System.out.flush();
+ long startPreAllocate = System.currentTimeMillis();
+ controller.preAllocate(1, size);
+ long endPreAllocate = System.currentTimeMillis() - startPreAllocate;
+ if (endPreAllocate != 0) System.out.println("PreAllocated the file in " + endPreAllocate + " seconds, What means " + (size/endPreAllocate) + " bytes per millisecond");
+ }
+
+
+ public void testInvalidWrite() throws Exception
+ {
+ final JlibAIO controller = new JlibAIO();
+ controller.open(FILE_NAME, 2000);
+
+ try
+ {
+
+ final int SIZE=512;
+
+ ByteBuffer block = controller.newBuffer(SIZE);
+ encodeBufer(block);
+
+ preAlloc(controller, 1000 * 512);
+
+
+ CountDownLatch latchDone = new CountDownLatch(1);
+
+ LocalAIO aioBlock = new LocalAIO(latchDone);
+ controller.write(11, 512, block, aioBlock);
+
+ latchDone.await();
+
+ assertTrue (aioBlock.errorCalled);
+ assertFalse(aioBlock.doneCalled);
+
+ controller.destroyBuffer(block);
+ }
+ catch (Exception e)
+ {
+ System.out.println("Received " + LocalAIO.staticDone + " before it failed");
+ throw e;
+ }
+ finally
+ {
+ controller.close();
+ }
+
+ }
+
+ public void testInvalidAlloc() throws Exception
+ {
+ JlibAIO controller = new JlibAIO();
+ try
+ {
+ // You don't need to open the file to alloc it
+ ByteBuffer buffer = controller.newBuffer(300);
+ fail ("Exception expected");
+ }
+ catch (Exception ignored)
+ {
+ }
+
+ }
+
+ private static class LocalAIO implements AIOCallback
+ {
+
+ CountDownLatch latch;
+
+ public LocalAIO(CountDownLatch latch)
+ {
+ this.latch = latch;
+ }
+
+ boolean doneCalled = false;
+ boolean errorCalled = false;
+ int timesDoneCalled = 0;
+ static int staticDone = 0;
+ public void decode(int length, ByteBuffer buffer)
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void done()
+ {
+ //System.out.println("Received Done"); System.out.flush();
+ doneCalled = true;
+ timesDoneCalled++;
+ staticDone++;
+ if (latch != null)
+ {
+ latch.countDown();
+ }
+
+ }
+
+ public void onError(int errorCode, String errorMessage)
+ {
+ errorCalled = true;
+ if (latch != null)
+ {
+ // even thought an error happened, we need to inform the latch, or the test won't finish
+ latch.countDown();
+ }
+ System.out.println("Received an Error - " + errorCode + " message=" + errorMessage);
+
+ }
+
+ }
+
+ private void addString(String str, ByteBuffer buffer)
+ {
+ CharBuffer charBuffer = CharBuffer.wrap(str);
+ UTF_8_ENCODER.encode(charBuffer, buffer, true);
+
+ }
+
+
+
+}
Property changes on: trunk/tests/src/org/jboss/messaging/tests/integration/core/asyncio/impl/SingleThreadWriteNativeTest.java
___________________________________________________________________
Name: svn:keywords
+ Id LastChangedDate Author Revision
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/ClientExitTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/integration/ClientExitTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/ClientExitTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/ClientExitTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,131 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* 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.messaging.tests.integration.core.remoting.impl;
+
+import static org.jboss.messaging.core.remoting.TransportType.TCP;
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.client.ClientConnection;
+import org.jboss.messaging.core.client.ClientConnectionFactory;
+import org.jboss.messaging.core.client.ClientConsumer;
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.client.impl.ClientConnectionFactoryImpl;
+import org.jboss.messaging.core.config.impl.ConfigurationImpl;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.tests.unit.core.remoting.impl.ConfigurationHelper;
+import org.jboss.messaging.tests.unit.core.util.SerializedClientSupport;
+import org.jboss.messaging.core.server.MessagingServer;
+import org.jboss.messaging.core.server.impl.MessagingServerImpl;
+
+/**
+ * A test that makes sure that a Messaging client gracefully exists after the last connection is
+ * closed. Test for http://jira.jboss.org/jira/browse/JBMESSAGING-417.
+ *
+ * This is not technically a crash test, but it uses the same type of topology as the crash tests
+ * (local server, remote VM client).
+ *
+ * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * $Id$
+ */
+public class ClientExitTest extends TestCase
+{
+ // Constants ------------------------------------------------------------------------------------
+
+ public static final String MESSAGE_TEXT = "kolowalu";
+
+ public static final String QUEUE = "ClientExitTestQueue";
+
+ // Static ---------------------------------------------------------------------------------------
+
+ private static final Logger log = Logger.getLogger(ClientExitTest.class);
+
+ // Attributes -----------------------------------------------------------------------------------
+
+ private MessagingServer server;
+
+ private ClientConnection connection;
+
+ private ClientConsumer consumer;
+
+ // Constructors ---------------------------------------------------------------------------------
+
+ // Public ---------------------------------------------------------------------------------------
+
+ public void testGracefulClientExit() throws Exception
+ {
+ // spawn a JVM that creates a JMS client, which sends a test message
+ Process p = SerializedClientSupport.spawnVM(GracefulClient.class.getName());
+
+ // read the message from the queue
+
+ Message message = consumer.receive(15000);
+
+ assertNotNull(message);
+ assertEquals(MESSAGE_TEXT, new String(message.getPayload()));
+
+ // the client VM should exit by itself. If it doesn't, that means we have a problem
+ // and the test will timeout
+ log.info("waiting for the client VM to exit ...");
+ p.waitFor();
+
+ assertEquals(0, p.exitValue());
+ }
+
+ // Package protected ----------------------------------------------------------------------------
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ ConfigurationImpl config = ConfigurationHelper.newConfiguration(TCP,
+ "localhost", 9000);
+ server = new MessagingServerImpl(config);
+ server.start();
+
+ ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0, config, server.getVersion());
+ connection = cf.createConnection(null, null);
+ ClientSession session = connection.createClientSession(false, true, true, -1, false, false);
+ session.createQueue(QUEUE, QUEUE, null, false, false);
+ consumer = session.createConsumer(QUEUE, null, false, false, true);
+ connection.start();
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ consumer.close();
+ connection.close();
+
+ server.stop();
+
+ super.tearDown();
+ }
+
+ // Protected ------------------------------------------------------------------------------------
+
+ // Private --------------------------------------------------------------------------------------
+
+ // Inner classes --------------------------------------------------------------------------------
+
+}
Property changes on: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/ClientExitTest.java
___________________________________________________________________
Name: svn:keywords
+ "Id LastChangedDate Author Revision"
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/DummyInterceptor.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/integration/DummyInterceptor.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/DummyInterceptor.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/DummyInterceptor.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,55 @@
+/*
+ * JBoss, the OpenSource J2EE webOS
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+
+package org.jboss.messaging.tests.integration.core.remoting.impl;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.remoting.Interceptor;
+import org.jboss.messaging.core.remoting.Packet;
+import org.jboss.messaging.core.remoting.impl.wireformat.ConsumerDeliverMessage;
+
+public class DummyInterceptor implements Interceptor
+{
+ protected Logger log = Logger.getLogger(DummyInterceptor.class);
+
+ boolean sendException = false;
+ boolean changeMessage = false;
+ AtomicInteger syncCounter = new AtomicInteger(0);
+
+ public int getCounter()
+ {
+ return syncCounter.get();
+ }
+
+ public void clearCounter()
+ {
+ syncCounter.set(0);
+ }
+
+ public void intercept(Packet packet) throws MessagingException
+ {
+ log.info("DummyFilter packet = " + packet.getClass().getName());
+ syncCounter.addAndGet(1);
+ if (sendException)
+ {
+ throw new MessagingException(MessagingException.INTERNAL_ERROR);
+ }
+ if (changeMessage)
+ {
+ if (packet instanceof ConsumerDeliverMessage)
+ {
+ ConsumerDeliverMessage deliver = (ConsumerDeliverMessage)packet;
+ log.info("msg = " + deliver.getMessage().getClass().getName());
+ deliver.getMessage().getHeaders().put("DummyInterceptor", "was here");
+ }
+ }
+ }
+
+}
Property changes on: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/DummyInterceptor.java
___________________________________________________________________
Name: svn:keywords
+ Id LastChangedDate Author Revision
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/DummyInterceptorB.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/integration/DummyInterceptorB.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/DummyInterceptorB.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/DummyInterceptorB.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,40 @@
+/*
+ * JBoss, the OpenSource J2EE webOS
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+
+package org.jboss.messaging.tests.integration.core.remoting.impl;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.remoting.Interceptor;
+import org.jboss.messaging.core.remoting.Packet;
+
+public class DummyInterceptorB implements Interceptor
+{
+
+ protected Logger log = Logger.getLogger(DummyInterceptorB.class);
+
+ static AtomicInteger syncCounter = new AtomicInteger(0);
+
+ public static int getCounter()
+ {
+ return syncCounter.get();
+ }
+
+ public static void clearCounter()
+ {
+ syncCounter.set(0);
+ }
+
+ public void intercept(Packet packet) throws MessagingException
+ {
+ syncCounter.addAndGet(1);
+ log.info("DummyFilter packet = " + packet);
+ }
+
+}
Property changes on: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/DummyInterceptorB.java
___________________________________________________________________
Name: svn:keywords
+ Id LastChangedDate Author Revision
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/GracefulClient.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/integration/GracefulClient.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/GracefulClient.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/GracefulClient.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,110 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* 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.messaging.tests.integration.core.remoting.impl;
+
+import static org.jboss.messaging.core.remoting.TransportType.TCP;
+import static org.jboss.messaging.tests.integration.core.remoting.impl.ClientExitTest.QUEUE;
+
+import org.jboss.messaging.core.client.ClientConnection;
+import org.jboss.messaging.core.client.ClientConnectionFactory;
+import org.jboss.messaging.core.client.ClientConsumer;
+import org.jboss.messaging.core.client.ClientProducer;
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.client.impl.ClientConnectionFactoryImpl;
+import org.jboss.messaging.core.config.impl.ConfigurationImpl;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.message.impl.MessageImpl;
+import org.jboss.messaging.tests.unit.core.remoting.impl.ConfigurationHelper;
+import org.jboss.messaging.core.server.MessagingServer;
+import org.jboss.messaging.core.server.impl.MessagingServerImpl;
+import org.jboss.messaging.jms.client.JBossTextMessage;
+
+/**
+ * Code to be run in an external VM, via main().
+ *
+ * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ * $Id$
+ */
+public class GracefulClient
+{
+ // Constants ------------------------------------------------------------------------------------
+
+ private static final Logger log = Logger.getLogger(GracefulClient.class);
+
+ // Static ---------------------------------------------------------------------------------------
+
+ public static void main(String[] args) throws Exception
+ {
+ try
+ {
+ ConfigurationImpl config = ConfigurationHelper.newConfiguration(TCP,
+ "localhost", 9000);
+
+ // FIXME there should be another way to get a meaningful Version on the
+ // client side...
+ MessagingServer server = new MessagingServerImpl();
+ ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0, config, server.getVersion());
+ ClientConnection conn = cf.createConnection(null, null);
+ ClientSession session = conn.createClientSession(false, true, true, -1, false, false);
+ ClientProducer producer = session.createProducer(QUEUE);
+ ClientConsumer consumer = session.createConsumer(QUEUE, null, false, false, true);
+
+ MessageImpl message = new MessageImpl(JBossTextMessage.TYPE, false, 0,
+ System.currentTimeMillis(), (byte) 1);
+ message.setPayload(ClientExitTest.MESSAGE_TEXT.getBytes());
+ producer.send(message);
+
+ conn.start();
+
+ // block in receiving for 5 secs, we won't receive anything
+ consumer.receive(5000);
+
+ // this should silence any non-daemon thread and allow for graceful exit
+ conn.close();
+ } catch (Throwable t)
+ {
+ log.error(t.getMessage(), t);
+ System.exit(1);
+ }
+ }
+
+ // Attributes -----------------------------------------------------------------------------------
+
+ // Constructors ---------------------------------------------------------------------------------
+
+ // Command implementation -----------------------------------------------------------------------
+
+ // Public ---------------------------------------------------------------------------------------
+
+ // Package protected ----------------------------------------------------------------------------
+
+ // Protected ------------------------------------------------------------------------------------
+
+ // Private --------------------------------------------------------------------------------------
+
+ // Inner classes --------------------------------------------------------------------------------
+
+}
Property changes on: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/GracefulClient.java
___________________________________________________________________
Name: svn:keywords
+ "Id LastChangedDate Author Revision"
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/PacketFilterTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/integration/PacketFilterTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/PacketFilterTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/PacketFilterTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,208 @@
+/*
+ * JBoss, the OpenSource J2EE webOS
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+
+package org.jboss.messaging.tests.integration.core.remoting.impl;
+
+import java.util.UUID;
+
+import org.jboss.messaging.core.server.impl.MessagingServerImpl;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.tests.unit.core.remoting.impl.ConfigurationHelper;
+import static org.jboss.messaging.core.remoting.TransportType.INVM;
+import org.jboss.messaging.core.client.*;
+import org.jboss.messaging.core.client.impl.ClientConnectionFactoryImpl;
+import org.jboss.messaging.core.message.impl.MessageImpl;
+import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.jms.client.JBossTextMessage;
+import junit.framework.TestCase;
+
+public class PacketFilterTest extends TestCase
+{
+ Logger log = Logger.getLogger(PacketFilterTest.class);
+
+ private MessagingServerImpl server;
+
+
+ public PacketFilterTest(String name)
+ {
+ super(name);
+ }
+
+ protected void setUp() throws Exception
+ {
+ server = new MessagingServerImpl(ConfigurationHelper.newConfiguration(INVM, null, 0));
+ server.start();
+ }
+
+ protected void tearDown() throws Exception
+ {
+ if(server != null)
+ {
+ server.stop();
+ server = null;
+ }
+ }
+
+ public void testFilter() throws Throwable
+ {
+ DummyInterceptor interceptorA = null;
+ DummyInterceptorB interceptorB = null;
+
+ ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0, server.getConfiguration(), server.getVersion());
+ ClientConnection conn = null;
+ try
+ {
+
+ // Deploy using the API
+ interceptorA = new DummyInterceptor();
+ server.getRemotingService().addInterceptor(interceptorA);
+
+
+ interceptorA.sendException=true;
+ try
+ {
+ conn = cf.createConnection();
+ fail("Exception expected");
+ }
+ catch (Exception e)
+ {
+ conn = null;
+ }
+
+ interceptorA.sendException=false;
+
+ conn = cf.createConnection();
+ conn.createClientSession(false, true, true, -1, false, false);
+ conn.close();
+ conn = null;
+
+
+ assertEquals(0, DummyInterceptorB.getCounter());
+ assertTrue(interceptorA.getCounter() > 0);
+
+ interceptorA.clearCounter();
+ DummyInterceptorB.clearCounter();
+ interceptorB = new DummyInterceptorB();
+ server.getRemotingService().addInterceptor(interceptorB);
+ conn = cf.createConnection();
+ conn.createClientSession(false, true, true, -1, false, false);
+ conn.close();
+ conn = null;
+
+ assertTrue(DummyInterceptorB.getCounter() > 0);
+ assertTrue(interceptorA.getCounter() > 0);
+
+ interceptorA.clearCounter();
+ DummyInterceptorB.clearCounter();
+
+ server.getRemotingService().removeInterceptor(interceptorA);
+
+ conn = cf.createConnection();
+ conn.createClientSession(false, true, true, -1, false, false);
+ conn.close();
+ conn = null;
+
+ assertTrue(DummyInterceptorB.getCounter() > 0);
+ assertTrue(interceptorA.getCounter() == 0);
+
+
+ log.info("Undeploying server");
+ server.getRemotingService().removeInterceptor(interceptorB);
+ interceptorB = null;
+ interceptorA.clearCounter();
+ DummyInterceptorB.clearCounter();
+
+ conn = cf.createConnection();
+ conn.createClientSession(false, true, true, -1, false, false);
+ conn.close();
+ conn = null;
+
+ assertEquals(0, interceptorA.getCounter());
+ assertEquals(0, DummyInterceptorB.getCounter());
+
+ interceptorA = null;
+ }
+ finally
+ {
+ if (conn != null)
+ {
+ try{conn.close();} catch (Exception ignored){}
+ }
+ if (interceptorA != null)
+ {
+ server.getRemotingService().removeInterceptor(interceptorA);
+ }
+ if (interceptorB != null)
+ {
+ try{server.getRemotingService().removeInterceptor(interceptorB);} catch (Exception ignored){}
+ }
+ }
+ }
+
+ public void testReceiveMessages() throws Throwable
+ {
+
+ DummyInterceptor interceptor = null;
+ ClientConnection conn = null;
+
+ try
+ {
+
+ interceptor = new DummyInterceptor();
+ server.getRemotingService().addInterceptor(interceptor);
+ server.getPostOffice().addBinding("queue1", "queue1", null, false, false);
+
+ interceptor.sendException=false;
+
+
+ ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0, server.getConfiguration(), server.getVersion());
+ conn = cf.createConnection();
+ conn.start();
+ ClientSession session = conn.createClientSession(false, true, true, -1, false, false);
+ ClientProducer producer = session.createProducer("queue1");
+ String msg = "msg " + UUID.randomUUID().toString();
+
+ interceptor.changeMessage = true;
+ MessageImpl message = new MessageImpl(JBossTextMessage.TYPE, true, 0, System.currentTimeMillis(), (byte) 1);
+ message.setPayload(msg.getBytes());
+ producer.send(message);
+
+ ClientConsumer consumer = session.createConsumer("queue1", null, false, false, true);
+ Message jmsMsg = consumer.receive(100000);
+ assertEquals(jmsMsg.getHeader("DummyInterceptor"), "was here");
+
+
+ assertNotNull(jmsMsg);
+
+ assertEquals(msg, new String(jmsMsg.getPayload()));
+ }
+ finally
+ {
+ try
+ {
+ if (conn != null)
+ {
+ conn.close();
+ }
+ }
+ catch (Exception ignored)
+ {
+ }
+
+ try
+ {
+ if (interceptor != null)
+ {
+ server.getRemotingService().removeInterceptor(interceptor);
+ }
+ }
+ catch (Exception ignored)
+ {
+ }
+ }
+ }
+}
Property changes on: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/impl/PacketFilterTest.java
___________________________________________________________________
Name: svn:keywords
+ Id LastChangedDate Author Revision
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/ClientKeepAliveTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/mina/integration/test/ClientKeepAliveTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/ClientKeepAliveTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/ClientKeepAliveTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,280 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.integration.core.remoting.mina;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.easymock.EasyMock.anyLong;
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.isA;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
+import static org.jboss.messaging.core.remoting.TransportType.TCP;
+import static org.jboss.messaging.tests.util.RandomUtil.randomLong;
+
+import java.util.concurrent.CountDownLatch;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.client.FailureListener;
+import org.jboss.messaging.core.config.impl.ConfigurationImpl;
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.remoting.KeepAliveFactory;
+import org.jboss.messaging.core.remoting.NIOSession;
+import org.jboss.messaging.core.remoting.RemotingException;
+import org.jboss.messaging.tests.unit.core.remoting.impl.ConfigurationHelper;
+import org.jboss.messaging.core.remoting.impl.PacketDispatcherImpl;
+import org.jboss.messaging.core.remoting.impl.mina.ClientKeepAliveFactory;
+import org.jboss.messaging.core.remoting.impl.mina.MinaConnector;
+import org.jboss.messaging.core.remoting.impl.mina.MinaService;
+import org.jboss.messaging.core.remoting.impl.wireformat.Ping;
+import org.jboss.messaging.core.remoting.impl.wireformat.Pong;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class ClientKeepAliveTest extends TestCase
+{
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ private MinaService service;
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ ConfigurationImpl config = ConfigurationHelper.newConfiguration(TCP, "localhost", TestSupport.PORT);
+ config.setKeepAliveInterval(TestSupport.KEEP_ALIVE_INTERVAL);
+ config.setKeepAliveTimeout(TestSupport.KEEP_ALIVE_TIMEOUT);
+ service = new MinaService(config);
+ service.start();
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ service.stop();
+ service = null;
+ }
+
+ public void testKeepAliveWithClientOK() throws Exception
+ {
+ KeepAliveFactory factory = createMock(KeepAliveFactory.class);
+
+ // client never send ping
+ expect(factory.ping(anyLong())).andStubReturn(null);
+ expect(factory.isPing(anyLong(), isA(Ping.class))).andStubReturn(true);
+ expect(factory.isPing(anyLong(), isA(Object.class))).andStubReturn(false);
+ // client is responding
+ expect(factory.pong(anyLong(), isA(Ping.class))).andReturn(new Pong(randomLong(), false)).atLeastOnce();
+
+ replay(factory);
+
+ final CountDownLatch latch = new CountDownLatch(1);
+
+ FailureListener listener = new FailureListener() {
+ public void onFailure(MessagingException me)
+ {
+ assertTrue(me instanceof RemotingException);
+ latch.countDown();
+ }
+ };
+ service.addFailureListener(listener);
+
+ MinaConnector connector = new MinaConnector(service.getConfiguration(), new PacketDispatcherImpl(null), factory);
+ connector.connect();
+
+ boolean firedKeepAliveNotification = latch.await(TestSupport.KEEP_ALIVE_INTERVAL
+ + TestSupport.KEEP_ALIVE_TIMEOUT + 2, SECONDS);
+ assertFalse(firedKeepAliveNotification);
+
+ service.removeFailureListener(listener);
+ connector.disconnect();
+
+ verify(factory);
+ }
+
+ public void testKeepAliveWithClientNotResponding() throws Exception
+ {
+ KeepAliveFactory factory = new ClientKeepAliveFactoryNotResponding();
+
+ final long[] clientSessionIDNotResponding = new long[1];
+ final CountDownLatch latch = new CountDownLatch(1);
+
+ FailureListener listener = new FailureListener() {
+ public void onFailure(MessagingException me)
+ {
+ assertTrue(me instanceof RemotingException);
+ RemotingException re = (RemotingException) me;
+ clientSessionIDNotResponding[0] = re.getSessionID();
+ latch.countDown();
+ }
+ };
+ service.addFailureListener(listener);
+
+ MinaConnector connector = new MinaConnector(service.getConfiguration(), new PacketDispatcherImpl(null), factory);
+
+ NIOSession session = connector.connect();
+ long clientSessionID = session.getID();
+
+ boolean firedKeepAliveNotification = latch.await(TestSupport.KEEP_ALIVE_INTERVAL
+ + TestSupport.KEEP_ALIVE_TIMEOUT + 2, SECONDS);
+ assertTrue("notification has not been received", firedKeepAliveNotification);
+ assertNotNull(clientSessionIDNotResponding[0]);
+ assertEquals(clientSessionID, clientSessionIDNotResponding[0]);
+
+ service.removeFailureListener(listener);
+ connector.disconnect();
+ }
+
+ public void testKeepAliveWithClientTooLongToRespond() throws Exception
+ {
+ KeepAliveFactory factory = new KeepAliveFactory()
+ {
+ public Ping ping(long sessionID)
+ {
+ return null;
+ }
+
+ public boolean isPing(long sessionID, Object message)
+ {
+ return (message instanceof Ping);
+ }
+
+ public synchronized Pong pong(long sessionID, Ping ping)
+ {
+ // like a TCP timeout, there is no response in the next 2 hours
+ try
+ {
+ wait(2 * 3600);
+ } catch (InterruptedException e)
+ {
+ e.printStackTrace();
+ }
+ return new Pong(randomLong(), false);
+ }
+ };
+
+ try
+ {
+ MinaConnector connector = new MinaConnector(service.getConfiguration(),
+ new PacketDispatcherImpl(null), factory);
+
+ NIOSession session = connector.connect();
+ long clientSessionID = session.getID();
+
+ final long[] clientSessionIDNotResponding = new long[1];
+ final CountDownLatch latch = new CountDownLatch(1);
+
+ FailureListener listener = new FailureListener() {
+ public void onFailure(MessagingException me)
+ {
+ assertTrue(me instanceof RemotingException);
+ RemotingException re = (RemotingException) me;
+ clientSessionIDNotResponding[0] = re.getSessionID();
+ latch.countDown();
+ }
+ };
+ service.addFailureListener(listener);
+
+ boolean firedKeepAliveNotification = latch.await(TestSupport.KEEP_ALIVE_INTERVAL
+ + TestSupport.KEEP_ALIVE_TIMEOUT + 2, SECONDS);
+ assertTrue("notification has not been received", firedKeepAliveNotification);
+ assertNotNull(clientSessionIDNotResponding[0]);
+ assertEquals(clientSessionID, clientSessionIDNotResponding[0]);
+
+ service.removeFailureListener(listener);
+ connector.disconnect();
+
+ } finally
+ {
+ // test is done: wake up the factory
+ synchronized (factory)
+ {
+ factory.notify();
+ }
+ }
+ }
+
+ public void testKeepAliveWithClientRespondingAndClientNotResponding()
+ throws Exception
+ {
+ KeepAliveFactory notRespondingfactory = new ClientKeepAliveFactoryNotResponding();
+ KeepAliveFactory respondingfactory = new ClientKeepAliveFactory();
+
+ final long[] sessionIDNotResponding = new long[1];
+ final CountDownLatch latch = new CountDownLatch(1);
+
+ FailureListener listener = new FailureListener() {
+ public void onFailure(MessagingException me)
+ {
+ assertTrue(me instanceof RemotingException);
+ RemotingException re = (RemotingException) me;
+ sessionIDNotResponding[0] = re.getSessionID();
+ latch.countDown();
+ }
+ };
+ service.addFailureListener(listener);
+
+ MinaConnector connectorNotResponding = new MinaConnector(service
+ .getConfiguration(), new PacketDispatcherImpl(null), notRespondingfactory);
+ MinaConnector connectorResponding = new MinaConnector(service
+ .getConfiguration(), new PacketDispatcherImpl(null), respondingfactory);
+
+ NIOSession sessionNotResponding = connectorNotResponding.connect();
+ long clientSessionIDNotResponding = sessionNotResponding.getID();
+
+
+ NIOSession sessionResponding = connectorResponding.connect();
+ long clientSessionIDResponding = sessionResponding.getID();
+
+ boolean firedKeepAliveNotification = latch.await(TestSupport.KEEP_ALIVE_INTERVAL
+ + TestSupport.KEEP_ALIVE_TIMEOUT + 2, SECONDS);
+ assertTrue("notification has not been received", firedKeepAliveNotification);
+
+ assertNotNull(sessionIDNotResponding[0]);
+ assertEquals(clientSessionIDNotResponding, sessionIDNotResponding[0]);
+ assertNotSame(clientSessionIDResponding, sessionIDNotResponding[0]);
+
+ service.removeFailureListener(listener);
+ connectorNotResponding.disconnect();
+ connectorResponding.disconnect();
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+
+ private class ClientKeepAliveFactoryNotResponding extends ClientKeepAliveFactory
+ {
+ @Override
+ public Ping ping(long clientSessionID)
+ {
+ return null;
+ }
+
+ @Override
+ public Pong pong(long sessionID, Ping ping)
+ {
+ return null;
+ }
+ }
+}
\ No newline at end of file
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/FilterChainSupportTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/mina/integration/test/FilterChainSupportTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/FilterChainSupportTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/FilterChainSupportTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,150 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.integration.core.remoting.mina;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
+import static org.jboss.messaging.core.remoting.impl.mina.FilterChainSupport.addCodecFilter;
+import static org.jboss.messaging.core.remoting.impl.mina.FilterChainSupport.addSSLFilter;
+import static org.jboss.messaging.tests.util.RandomUtil.randomLong;
+
+import java.net.InetSocketAddress;
+import java.util.concurrent.CountDownLatch;
+
+import javax.net.ssl.SSLException;
+
+import junit.framework.TestCase;
+
+import org.apache.mina.common.ConnectFuture;
+import org.apache.mina.common.DefaultIoFilterChainBuilder;
+import org.apache.mina.common.IoHandlerAdapter;
+import org.apache.mina.common.IoSession;
+import org.apache.mina.filter.ssl.SslFilter;
+import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
+import org.apache.mina.transport.socket.nio.NioSocketConnector;
+import org.jboss.messaging.core.remoting.KeepAliveFactory;
+import org.jboss.messaging.core.remoting.impl.mina.FailureNotifier;
+import org.jboss.messaging.core.remoting.impl.mina.FilterChainSupport;
+import org.jboss.messaging.core.remoting.impl.wireformat.Ping;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class FilterChainSupportTest extends TestCase
+{
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ private String keystorePath;
+ private String keystorePassword;
+ private String trustStorePath;
+ private String trustStorePassword;
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+
+ keystorePath = "messaging.keystore";
+ keystorePassword = "secureexample";
+ trustStorePath = "messaging.truststore";
+ trustStorePassword = keystorePassword;
+ }
+
+ public void testAddKeepAliveFilterWithIncorrectParameters() throws Exception
+ {
+ int keepAliveInterval = 5; // seconds
+ int keepAliveTimeout = 10; // seconds
+
+ DefaultIoFilterChainBuilder filterChain = new DefaultIoFilterChainBuilder();
+ KeepAliveFactory factory = createMock(KeepAliveFactory.class);
+ FailureNotifier notifier = createMock(FailureNotifier.class);
+
+ replay(factory, notifier);
+
+ try
+ {
+ FilterChainSupport.addKeepAliveFilter(filterChain, factory,
+ keepAliveInterval, keepAliveTimeout, notifier);
+ fail("the interval must be greater than the timeout");
+ } catch (IllegalArgumentException e)
+ {
+ }
+
+ verify(factory, notifier);
+ }
+
+ public void testSSLFilter() throws Exception
+ {
+ InetSocketAddress address = new InetSocketAddress("localhost", 9091);
+ NioSocketAcceptor acceptor = new NioSocketAcceptor();
+ addSSLFilter(acceptor.getFilterChain(), false, keystorePath,
+ keystorePassword, trustStorePath, trustStorePassword);
+ addCodecFilter(acceptor.getFilterChain());
+ acceptor.setDefaultLocalAddress(address);
+
+ final CountDownLatch latch = new CountDownLatch(1);
+
+ acceptor.setHandler(new IoHandlerAdapter()
+ {
+ @Override
+ public void messageReceived(IoSession session, Object message)
+ throws Exception
+ {
+ latch.countDown();
+ }
+ });
+ acceptor.bind();
+
+ NioSocketConnector connector = new NioSocketConnector();
+ addSSLFilter(connector.getFilterChain(), true,
+ keystorePath, keystorePassword, null, null);
+ addCodecFilter(connector.getFilterChain());
+ connector.setHandler(new IoHandlerAdapter());
+ ConnectFuture future = connector.connect(address).awaitUninterruptibly();
+ IoSession session = future.getSession();
+ session.write(new Ping(randomLong()));
+
+ boolean gotMessage = latch.await(500, MILLISECONDS);
+ assertTrue(gotMessage);
+
+ SslFilter sslFilter = ((SslFilter)session.getFilterChain().get("ssl"));
+ if (sslFilter != null)
+ {
+ try
+ {
+ sslFilter.stopSsl(session);
+ } catch (SSLException e)
+ {
+ fail(e.getMessage());
+ }
+ }
+
+ boolean sessionClosed = session.close().await(500, MILLISECONDS);
+ assertTrue(sessionClosed);
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaHandlerOrderingTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/mina/integration/test/MinaHandlerOrderingTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaHandlerOrderingTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaHandlerOrderingTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,146 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.integration.core.remoting.mina;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.remoting.Packet;
+import org.jboss.messaging.core.remoting.PacketDispatcher;
+import org.jboss.messaging.core.remoting.PacketSender;
+import org.jboss.messaging.core.remoting.impl.PacketDispatcherImpl;
+import org.jboss.messaging.core.remoting.impl.mina.MinaHandler;
+import org.jboss.messaging.core.remoting.impl.wireformat.TextPacket;
+import org.jboss.messaging.tests.unit.core.remoting.TestPacketHandler;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class MinaHandlerOrderingTest extends TestCase
+{
+
+ private MinaHandler handler;
+ private ExecutorService threadPool;
+
+ private TestPacketHandler handler_1;
+ private TestPacketHandler handler_2;
+ private PacketDispatcher clientDispatcher;
+
+ // Constants -----------------------------------------------------
+
+ private static final int MANY_MESSAGES = 50;
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ /**
+ * Test that when messages are sent to 2 different targetIDs,
+ * the messages are handled concurrently by the 2 PacketHandlers
+ */
+ public void testSerializationOrder() throws Exception
+ {
+ handler_1.expectMessage(2);
+ handler_2.expectMessage(MANY_MESSAGES);
+
+ TextPacket packet_1 = new TextPacket("testSerializationOrder handled by handle_1");
+ packet_1.setTargetID(handler_1.getID());
+ packet_1.setExecutorID(handler_1.getID());
+
+ // we send 1 packet to handler_1
+ // then many packets to handler_2
+ // and again 1 packet to handler_1
+ handler.messageReceived(null, packet_1);
+ for (int i = 0; i < MANY_MESSAGES; i++)
+ {
+ TextPacket packet_2 = new TextPacket(Integer.toString(i));
+ packet_2.setTargetID(handler_2.getID());
+ packet_2.setExecutorID(handler_2.getID());
+ handler.messageReceived(null, packet_2);
+ }
+ handler.messageReceived(null, packet_1);
+
+ // we expect to receive the 2 packets on handler_1
+ // *before* handler_2 received all its packets
+ assertTrue(handler_1.await(50, MILLISECONDS));
+ int size = handler_2.getPackets().size();
+ assertTrue("handler_2 should not have received all its message (size:" + size + ")", size < MANY_MESSAGES);
+
+ assertTrue(handler_2.await(2, SECONDS));
+ List<TextPacket> packetsReceivedByHandler_2 = handler_2.getPackets();
+ assertEquals(MANY_MESSAGES, packetsReceivedByHandler_2.size());
+ // we check that handler_2 receives all its messages in order:
+ for (int i = 0; i < MANY_MESSAGES; i++)
+ {
+ TextPacket p = packetsReceivedByHandler_2.get(i);
+ assertEquals(Integer.toString(i), p.getText());
+ }
+ }
+
+ // TestCase overrides --------------------------------------------
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ clientDispatcher = new PacketDispatcherImpl(null);
+ threadPool = Executors.newCachedThreadPool();
+ handler = new MinaHandler(clientDispatcher, threadPool, null, true);
+
+ handler_1 = new TestPacketHandler(23);
+ clientDispatcher.register(handler_1);
+ handler_2 = new TestPacketHandler(24) {
+ @Override
+ public void handle(Packet packet, PacketSender sender)
+ {
+ // slow down the 2nd handler
+ try
+ {
+ Thread.sleep(10);
+ } catch (InterruptedException e)
+ {
+ e.printStackTrace();
+ }
+ super.handle(packet, sender);
+ }
+ };
+ clientDispatcher.register(handler_2);
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ clientDispatcher.unregister(handler_1.getID());
+ clientDispatcher.unregister(handler_2.getID());
+ threadPool.shutdown();
+ handler_1 = null;
+ handler_2 = null;
+ clientDispatcher = null;
+ handler = null;
+ threadPool = null;
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaHandlerTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/mina/integration/test/MinaHandlerTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaHandlerTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaHandlerTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,114 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.integration.core.remoting.mina;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.remoting.PacketDispatcher;
+import org.jboss.messaging.core.remoting.impl.PacketDispatcherImpl;
+import org.jboss.messaging.core.remoting.impl.mina.MinaHandler;
+import org.jboss.messaging.core.remoting.impl.wireformat.TextPacket;
+import org.jboss.messaging.tests.unit.core.remoting.TestPacketHandler;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class MinaHandlerTest extends TestCase
+{
+
+ private MinaHandler handler;
+ private ExecutorService threadPool;
+ private TestPacketHandler packetHandler;
+ private PacketDispatcher clientDispatcher;
+
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ public void testReceiveNotAbstractPacket() throws Exception
+ {
+ try
+ {
+ handler.messageReceived(null, new Object());
+ fail();
+ } catch (IllegalArgumentException e)
+ {
+ }
+ }
+
+ public void testReceiveUnhandledAbstractPacket() throws Exception
+ {
+ TextPacket packet = new TextPacket("testReceiveUnhandledAbstractPacket");
+ packet.setExecutorID(packetHandler.getID());
+
+ handler.messageReceived(null, packet);
+
+ assertEquals(0, packetHandler.getPackets().size());
+ }
+
+ public void testReceiveHandledAbstractPacket() throws Exception
+ {
+ packetHandler.expectMessage(1);
+
+ TextPacket packet = new TextPacket("testReceiveHandledAbstractPacket");
+ packet.setTargetID(packetHandler.getID());
+ packet.setExecutorID(packetHandler.getID());
+
+ handler.messageReceived(null, packet);
+
+ assertTrue(packetHandler.await(500, MILLISECONDS));
+ assertEquals(1, packetHandler.getPackets().size());
+ assertEquals(packet.getText(), packetHandler.getPackets().get(0)
+ .getText());
+ }
+
+ // TestCase overrides --------------------------------------------
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ clientDispatcher = new PacketDispatcherImpl(null);
+ threadPool = Executors.newCachedThreadPool();
+ handler = new MinaHandler(clientDispatcher, threadPool, null, true);
+
+ packetHandler = new TestPacketHandler(23);
+ clientDispatcher.register(packetHandler);
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ clientDispatcher.unregister(packetHandler.getID());
+ threadPool.shutdown();
+ packetHandler = null;
+ clientDispatcher = null;
+ handler = null;
+ threadPool = null;
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaInspectorTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/mina/integration/test/MinaInspectorTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaInspectorTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaInspectorTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,108 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.integration.core.remoting.mina;
+
+import static org.apache.mina.filter.reqres.ResponseType.WHOLE;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.NULL;
+
+import java.util.UUID;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.remoting.impl.mina.MinaInspector;
+import org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class MinaInspectorTest extends TestCase
+{
+
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ private MinaInspector inspector;
+
+ public void testGetRequestIdForNull()
+ {
+ assertNull(inspector.getRequestId(null));
+ }
+
+ public void testGetRequestIdForNotAbstractPacket()
+ {
+ assertNull(inspector.getRequestId(new Object()));
+ }
+
+ public void testGetRequestIdForAbstractPacketWhichIsNotRequest()
+ {
+ PacketImpl packet = new PacketImpl(NULL);
+ packet.setTargetID(23);
+ assertFalse(packet.isRequest());
+ assertNull(inspector.getRequestId(packet));
+ }
+
+ public void testGetRequestIdForAbstractPacketWhichIsRequest()
+ {
+ PacketImpl packet = new PacketImpl(NULL);
+ packet.setTargetID(23);
+ packet.setCorrelationID(System.currentTimeMillis());
+ assertTrue(packet.isRequest());
+
+ Object requestID = inspector.getRequestId(packet);
+ assertNotNull(requestID);
+ assertEquals(packet.getCorrelationID(), requestID);
+ }
+
+ public void testGetResponseTypeForNull()
+ {
+ assertNull(inspector.getResponseType(null));
+ }
+
+ public void testGetResponseTypeForNotAbstractPacket()
+ {
+ assertNull(inspector.getResponseType(new Object()));
+ }
+
+ public void testGetResponseTypeForAbstractPacket()
+ {
+ PacketImpl packet = new PacketImpl(NULL);
+
+ assertEquals(WHOLE, inspector.getResponseType(packet));
+ }
+
+ // TestCase overrides --------------------------------------------
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ inspector = new MinaInspector();
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ inspector = null;
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaKeepAliveFactoryTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/mina/integration/test/MinaKeepAliveFactoryTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaKeepAliveFactoryTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaKeepAliveFactoryTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,99 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.integration.core.remoting.mina;
+
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.expectLastCall;
+import static org.easymock.EasyMock.isA;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
+import static org.jboss.messaging.tests.util.RandomUtil.randomLong;
+import junit.framework.TestCase;
+
+import org.apache.mina.common.IoSession;
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.remoting.KeepAliveFactory;
+import org.jboss.messaging.core.remoting.impl.mina.FailureNotifier;
+import org.jboss.messaging.core.remoting.impl.mina.MinaKeepAliveFactory;
+import org.jboss.messaging.core.remoting.impl.wireformat.Pong;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class MinaKeepAliveFactoryTest extends TestCase
+{
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ public void testResponseIsNotAPong()
+ {
+ IoSession session = createMock(IoSession.class);
+ KeepAliveFactory factory = createMock(KeepAliveFactory.class);
+ FailureNotifier notifier = createMock(FailureNotifier.class);
+ replay(session, factory, notifier);
+
+ MinaKeepAliveFactory minaFactory = new MinaKeepAliveFactory(factory, notifier);
+
+ assertFalse(minaFactory.isResponse(session, new Object()));
+
+ verify(session, factory, notifier);
+ }
+
+ public void testResponseIsAPongWithSessionNotFailed()
+ {
+ IoSession session = createMock(IoSession.class);
+ long sessionID = randomLong();
+ Pong pong = new Pong(sessionID, false);
+ KeepAliveFactory factory = createMock(KeepAliveFactory.class);
+ FailureNotifier notifier = createMock(FailureNotifier.class);
+ replay(session, factory, notifier);
+
+ MinaKeepAliveFactory minaFactory = new MinaKeepAliveFactory(factory, notifier);
+
+ assertTrue(minaFactory.isResponse(session, pong));
+
+ verify(session, factory, notifier);
+ }
+
+ public void testResponseIsAPongWithSessionFailed()
+ {
+ IoSession session = createMock(IoSession.class);
+ long sessionID = randomLong();
+ expect(session.getId()).andStubReturn(sessionID);
+ Pong pong = new Pong(sessionID, true);
+ KeepAliveFactory factory = createMock(KeepAliveFactory.class);
+ FailureNotifier notifier = createMock(FailureNotifier.class);
+ notifier.fireFailure(isA(MessagingException.class));
+ expectLastCall().once();
+ replay(session, factory, notifier);
+
+ MinaKeepAliveFactory minaFactory = new MinaKeepAliveFactory(factory, notifier);
+
+ assertTrue(minaFactory.isResponse(session, pong));
+
+ verify(session, factory, notifier);
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaRemotingBufferTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/mina/integration/test/MinaRemotingBufferTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaRemotingBufferTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaRemotingBufferTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,108 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.integration.core.remoting.mina;
+
+import static java.util.UUID.randomUUID;
+import junit.framework.TestCase;
+
+import org.apache.mina.common.IoBuffer;
+import org.jboss.messaging.core.remoting.impl.codec.RemotingBuffer;
+import org.jboss.messaging.core.remoting.impl.mina.BufferWrapper;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>.
+ *
+ * @version <tt>$Revision$</tt>
+ */
+public class MinaRemotingBufferTest extends TestCase
+{
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ private RemotingBuffer wrapper;
+ private IoBuffer buffer;
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ buffer = IoBuffer.allocate(256);
+ buffer.setAutoExpand(true);
+ wrapper = new BufferWrapper(buffer);
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ wrapper = null;
+ buffer = null;
+
+ }
+
+ public void testNullString() throws Exception
+ {
+ assertNull(putAndGetNullableString(null));
+ }
+
+ public void testEmptyString() throws Exception
+ {
+ String result = putAndGetNullableString("");
+
+ assertNotNull(result);
+ assertEquals("", result);
+ }
+
+ public void testNonEmptyString() throws Exception
+ {
+ String junk = randomUUID().toString();
+
+ String result = putAndGetNullableString(junk);
+
+ assertNotNull(result);
+ assertEquals(junk, result);
+ }
+
+ public void testPutTrueBoolean() throws Exception
+ {
+ wrapper.putBoolean(true);
+
+ buffer.flip();
+
+ assertTrue(wrapper.getBoolean());
+ }
+
+ public void testPutFalseBoolean() throws Exception
+ {
+ wrapper.putBoolean(false);
+
+ buffer.flip();
+
+ assertFalse(wrapper.getBoolean());
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ private String putAndGetNullableString(String nullableString) throws Exception
+ {
+ wrapper.putNullableString(nullableString);
+
+ buffer.flip();
+
+ return wrapper.getNullableString();
+ }
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaServiceTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/mina/integration/test/MinaServiceTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaServiceTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaServiceTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,84 @@
+package org.jboss.messaging.tests.integration.core.remoting.mina;
+
+import static org.jboss.messaging.core.remoting.TransportType.TCP;
+
+import java.io.IOException;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.remoting.NIOConnector;
+import org.jboss.messaging.core.remoting.NIOSession;
+import org.jboss.messaging.core.remoting.RemotingService;
+import org.jboss.messaging.core.remoting.TransportType;
+import org.jboss.messaging.tests.unit.core.remoting.impl.ConfigurationHelper;
+import org.jboss.messaging.core.remoting.impl.PacketDispatcherImpl;
+import org.jboss.messaging.core.remoting.impl.invm.INVMConnector;
+import org.jboss.messaging.core.remoting.impl.mina.MinaConnector;
+import org.jboss.messaging.core.remoting.impl.mina.MinaService;
+
+public class MinaServiceTest extends TestCase
+{
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------t------------------------
+
+ private RemotingService invmService;
+
+ public void testINVMConnector_OK() throws Exception
+ {
+ NIOConnector connector = new INVMConnector(1, new PacketDispatcherImpl(null), invmService.getDispatcher());
+ NIOSession session = connector.connect();
+
+ assertTrue(session.isConnected());
+ assertTrue(connector.disconnect());
+ assertFalse(session.isConnected());
+ }
+
+ public void testMinaConnector_Failure() throws Exception
+ {
+ NIOConnector connector = new MinaConnector(ConfigurationHelper.newConfiguration(
+ TCP, "localhost", 9000), new PacketDispatcherImpl(null));
+
+ try
+ {
+ connector.connect();
+ fail("MINA service started in invm: can not connect to it through TCP");
+ } catch (IOException e)
+ {
+
+ }
+ }
+
+ // TestCase overrides --------------------------------------------
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+
+ invmService = new MinaService(ConfigurationHelper.newConfiguration(TransportType.INVM, "localhost", -1));
+ invmService.start();
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ invmService.stop();
+
+ super.tearDown();
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaSessionTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/mina/integration/test/MinaSessionTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaSessionTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/MinaSessionTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,94 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.integration.core.remoting.mina;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static org.jboss.messaging.core.remoting.TransportType.TCP;
+
+import org.jboss.messaging.core.config.Configuration;
+import org.jboss.messaging.core.remoting.NIOConnector;
+import org.jboss.messaging.core.remoting.PacketDispatcher;
+import org.jboss.messaging.tests.unit.core.remoting.impl.ConfigurationHelper;
+import org.jboss.messaging.tests.unit.core.remoting.impl.SessionTestBase;
+import org.jboss.messaging.core.remoting.impl.mina.MinaConnector;
+import org.jboss.messaging.core.remoting.impl.mina.MinaService;
+import org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl;
+import org.jboss.messaging.core.remoting.impl.wireformat.TextPacket;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class MinaSessionTest extends SessionTestBase
+{
+
+ private MinaService service;
+
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ public void testWriteAndBlockWithTimeout() throws Exception
+ {
+ serverPacketHandler.setSleepTime(1000, MILLISECONDS);
+
+ PacketImpl packet = new TextPacket("testSendBlockingWithTimeout");
+ packet.setTargetID(serverPacketHandler.getID());
+
+ try
+ {
+ session.writeAndBlock(packet, 500, MILLISECONDS);
+ fail("a Throwable should be thrown");
+ } catch (Throwable t)
+ {
+ }
+ }
+
+ // ClientTestBase overrides --------------------------------------
+
+ @Override
+ protected NIOConnector createNIOConnector(PacketDispatcher dispatcher)
+ {
+ return new MinaConnector(createRemotingConfiguration(), dispatcher);
+ }
+
+ @Override
+ protected Configuration createRemotingConfiguration()
+ {
+ return ConfigurationHelper.newConfiguration(TCP, "localhost", TestSupport.PORT);
+ }
+
+ @Override
+ protected PacketDispatcher startServer() throws Exception
+ {
+ service = new MinaService(createRemotingConfiguration());
+ service.start();
+ return service.getDispatcher();
+ }
+
+ @Override
+ protected void stopServer()
+ {
+ service.stop();
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/ReversePacketHandler.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/mina/integration/test/ReversePacketHandler.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/ReversePacketHandler.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/ReversePacketHandler.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,106 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.integration.core.remoting.mina;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static junit.framework.Assert.fail;
+
+import java.util.concurrent.TimeUnit;
+
+import junit.framework.Assert;
+
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.remoting.Packet;
+import org.jboss.messaging.core.remoting.PacketSender;
+import org.jboss.messaging.core.remoting.impl.wireformat.TextPacket;
+import org.jboss.messaging.tests.unit.core.remoting.TestPacketHandler;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class ReversePacketHandler extends TestPacketHandler
+{
+ // Constants -----------------------------------------------------
+
+ private static final Logger log = Logger.getLogger(ReversePacketHandler.class);
+
+
+ // Attributes ----------------------------------------------------
+
+ private int sleepTime;
+ private TimeUnit timeUnit;
+ private PacketSender lastSender;
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ public ReversePacketHandler(final long id)
+ {
+ super(id);
+ }
+
+ // Public --------------------------------------------------------
+
+ public void setSleepTime(int sleepTime, TimeUnit timeUnit)
+ {
+ this.sleepTime = sleepTime;
+ this.timeUnit = timeUnit;
+ }
+
+ public PacketSender getLastSender()
+ {
+ return lastSender;
+ }
+
+ // TestPacketHandler overrides -----------------------------------
+
+ @Override
+ protected void doHandle(Packet packet, PacketSender sender)
+ {
+ Assert.assertTrue(packet instanceof TextPacket);
+
+ lastSender = sender;
+
+ if (sleepTime > 0)
+ {
+ try
+ {
+ Thread.sleep(MILLISECONDS.convert(sleepTime, timeUnit));
+ } catch (InterruptedException e)
+ {
+ fail();
+ }
+ }
+
+ TextPacket message = (TextPacket) packet;
+ if (message.isRequest())
+ {
+ TextPacket response = new TextPacket(TestSupport.reverse(message.getText()));
+ response.normalize(message);
+ try
+ {
+ sender.send(response);
+ }
+ catch (Exception e)
+ {
+ log.error("Failed to handle", e);
+ }
+ }
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/ServerKeepAliveTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/mina/integration/test/ServerKeepAliveTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/ServerKeepAliveTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/ServerKeepAliveTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,178 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.integration.core.remoting.mina;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.jboss.messaging.core.remoting.TransportType.TCP;
+
+import java.util.concurrent.CountDownLatch;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.client.FailureListener;
+import org.jboss.messaging.core.config.impl.ConfigurationImpl;
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.remoting.NIOSession;
+import org.jboss.messaging.core.remoting.RemotingException;
+import org.jboss.messaging.tests.unit.core.remoting.impl.ConfigurationHelper;
+import org.jboss.messaging.core.remoting.impl.PacketDispatcherImpl;
+import org.jboss.messaging.core.remoting.impl.mina.MinaConnector;
+import org.jboss.messaging.core.remoting.impl.mina.MinaService;
+import org.jboss.messaging.core.remoting.impl.mina.ServerKeepAliveFactory;
+import org.jboss.messaging.core.remoting.impl.wireformat.Ping;
+import org.jboss.messaging.core.remoting.impl.wireformat.Pong;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class ServerKeepAliveTest extends TestCase
+{
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ private MinaService service;
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ service.stop();
+ service = null;
+ }
+
+ public void testKeepAliveWithServerNotResponding() throws Exception
+ {
+ ServerKeepAliveFactory factory = new ServerKeepAliveFactory()
+ {
+ // server does not send ping
+ @Override
+ public Ping ping(long sessionID)
+ {
+ return null;
+ }
+
+ @Override
+ public Pong pong(long sessionID, Ping ping)
+ {
+ // no pong -> server is not responding
+ super.pong(sessionID, ping);
+ return null;
+ }
+ };
+
+ ConfigurationImpl config = ConfigurationHelper.newConfiguration(TCP,
+ "localhost", TestSupport.PORT);
+ config.setKeepAliveInterval(TestSupport.KEEP_ALIVE_INTERVAL);
+ config.setKeepAliveTimeout(TestSupport.KEEP_ALIVE_TIMEOUT);
+ service = new MinaService(config, factory);
+ service.start();
+
+ MinaConnector connector = new MinaConnector(service
+ .getConfiguration(), new PacketDispatcherImpl(null));
+ final long[] sessionIDNotResponding = new long[1];
+ final CountDownLatch latch = new CountDownLatch(1);
+
+ FailureListener listener = new FailureListener()
+ {
+ public void onFailure(MessagingException me)
+ {
+ assertTrue(me instanceof RemotingException);
+ RemotingException re = (RemotingException) me;
+ sessionIDNotResponding[0] = re.getSessionID();
+ latch.countDown();
+ }
+ };
+ connector.addFailureListener(listener);
+
+ NIOSession session = connector.connect();
+
+ boolean firedKeepAliveNotification = latch.await(TestSupport.KEEP_ALIVE_INTERVAL
+ + TestSupport.KEEP_ALIVE_TIMEOUT + 2, SECONDS);
+ assertTrue(firedKeepAliveNotification);
+ assertEquals(session.getID(), sessionIDNotResponding[0]);
+
+ connector.removeFailureListener(listener);
+ connector.disconnect();
+ }
+
+ public void testKeepAliveWithServerSessionFailed() throws Exception
+ {
+ ServerKeepAliveFactory factory = new ServerKeepAliveFactory()
+ {
+ // server does not send ping
+ @Override
+ public Ping ping(long sessionID)
+ {
+ return null;
+ }
+
+ @Override
+ public Pong pong(long sessionID, Ping ping)
+ {
+ // no pong -> server is not responding
+ super.pong(sessionID, ping);
+ return new Pong(sessionID, true);
+ }
+ };
+
+ ConfigurationImpl config = ConfigurationHelper.newConfiguration(TCP,
+ "localhost", TestSupport.PORT);
+ config.setKeepAliveInterval(TestSupport.KEEP_ALIVE_INTERVAL);
+ config.setKeepAliveTimeout(TestSupport.KEEP_ALIVE_TIMEOUT);
+ service = new MinaService(config, factory);
+ service.start();
+
+ MinaConnector connector = new MinaConnector(service
+ .getConfiguration(), new PacketDispatcherImpl(null));
+ final long[] sessionIDNotResponding = new long[1];
+ final CountDownLatch latch = new CountDownLatch(1);
+
+ FailureListener listener = new FailureListener()
+ {
+ public void onFailure(MessagingException me)
+ {
+ assertTrue(me instanceof RemotingException);
+ RemotingException re = (RemotingException) me;
+ sessionIDNotResponding[0] = re.getSessionID();
+ latch.countDown();
+ }
+ };
+ connector.addFailureListener(listener);
+
+ NIOSession session = connector.connect();
+
+ boolean firedKeepAliveNotification = latch.await(TestSupport.KEEP_ALIVE_INTERVAL
+ + TestSupport.KEEP_ALIVE_TIMEOUT + 2, SECONDS);
+ assertTrue(firedKeepAliveNotification);
+ assertEquals(session.getID(), sessionIDNotResponding[0]);
+
+ connector.removeFailureListener(listener);
+ connector.disconnect();
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
\ No newline at end of file
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/TestSupport.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/mina/integration/test/TestSupport.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/TestSupport.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/mina/TestSupport.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,55 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.integration.core.remoting.mina;
+
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>.
+ *
+ * @version <tt>$Revision$</tt>
+ */
+public abstract class TestSupport
+{
+ // Constants -----------------------------------------------------
+
+ public static final int MANY_MESSAGES = 500;
+
+ public static final int KEEP_ALIVE_INTERVAL = 2; // in seconds
+
+ public static final int KEEP_ALIVE_TIMEOUT = 1; // in seconds
+
+ public static final long REQRES_TIMEOUT = 2; // in seconds
+
+ public static final int PORT = 9090;
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ public static String reverse(String text)
+ {
+ // Reverse text
+ StringBuffer buf = new StringBuffer(text.length());
+ for (int i = text.length() - 1; i >= 0; i--)
+ {
+ buf.append(text.charAt(i));
+ }
+ return buf.toString();
+ }
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/ssl/CoreClientOverSSL.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/ssl/integration/CoreClientOverSSL.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/ssl/CoreClientOverSSL.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/ssl/CoreClientOverSSL.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,116 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.integration.core.remoting.ssl;
+
+import static org.jboss.messaging.core.remoting.TransportType.TCP;
+
+import java.util.Arrays;
+
+import org.jboss.messaging.core.client.ClientConnection;
+import org.jboss.messaging.core.client.ClientConnectionFactory;
+import org.jboss.messaging.core.client.ClientProducer;
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.client.impl.ClientConnectionFactoryImpl;
+import org.jboss.messaging.core.config.impl.ConfigurationImpl;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.message.impl.MessageImpl;
+import org.jboss.messaging.tests.unit.core.remoting.impl.ConfigurationHelper;
+import org.jboss.messaging.core.server.MessagingServer;
+import org.jboss.messaging.core.server.impl.MessagingServerImpl;
+import org.jboss.messaging.jms.client.JBossTextMessage;
+
+/**
+ * This client will open a connection, send a message to a queue over SSL and
+ * exit.
+ *
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ */
+public class CoreClientOverSSL
+{
+ // Constants -----------------------------------------------------
+
+ private static final Logger log = Logger.getLogger(CoreClientOverSSL.class);
+
+ // Static --------------------------------------------------------
+
+ public static void main(String[] args)
+ {
+ try
+ {
+ log.info("args = " + Arrays.asList(args));
+
+ if (args.length != 3)
+ {
+ log.fatal("unexpected number of args (should be 3)");
+ System.exit(1);
+ }
+
+ boolean sslEnabled = Boolean.parseBoolean(args[0]);
+ String keyStorePath = args[1];
+ String keyStorePassword = args[2];
+
+ ConfigurationImpl config = ConfigurationHelper.newConfiguration(TCP,
+ "localhost", CoreClientOverSSLTest.SSL_PORT);
+ config.setSSLEnabled(sslEnabled);
+ config.setKeyStorePath(keyStorePath);
+ config.setKeyStorePassword(keyStorePassword);
+
+ // FIXME there should be another way to get a meaningful Version on the
+ // client side...
+ MessagingServer server = new MessagingServerImpl();
+ ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0, config, server.getVersion());
+ ClientConnection conn = cf.createConnection(null, null);
+ ClientSession session = conn.createClientSession(false, true, true, -1, false, false);
+ ClientProducer producer = session.createProducer(CoreClientOverSSLTest.QUEUE);
+
+ MessageImpl message = new MessageImpl(JBossTextMessage.TYPE, false, 0,
+ System.currentTimeMillis(), (byte) 1);
+ message.setPayload(CoreClientOverSSLTest.MESSAGE_TEXT_FROM_CLIENT.getBytes());
+ producer.send(message);
+
+ conn.close();
+
+ System.exit(0);
+ } catch (Throwable t)
+ {
+ log.error(t.getMessage(), t);
+ System.exit(1);
+ }
+ }
+
+ // Attributes ----------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/ssl/CoreClientOverSSLTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/ssl/integration/CoreClientOverSSLTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/ssl/CoreClientOverSSLTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/core/remoting/ssl/CoreClientOverSSLTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,157 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.integration.core.remoting.ssl;
+
+import static java.lang.Boolean.FALSE;
+import static org.jboss.messaging.core.remoting.TransportType.TCP;
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.client.ClientConnection;
+import org.jboss.messaging.core.client.ClientConnectionFactory;
+import org.jboss.messaging.core.client.ClientConsumer;
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.client.impl.ClientConnectionFactoryImpl;
+import org.jboss.messaging.core.config.impl.ConfigurationImpl;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.tests.unit.core.remoting.impl.ConfigurationHelper;
+import org.jboss.messaging.tests.unit.core.util.SerializedClientSupport;
+import org.jboss.messaging.core.server.MessagingServer;
+import org.jboss.messaging.core.server.impl.MessagingServerImpl;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision: 3716 $</tt>
+ *
+ */
+public class CoreClientOverSSLTest extends TestCase
+{
+ // Constants -----------------------------------------------------
+
+ public static final String MESSAGE_TEXT_FROM_CLIENT = "CoreClientOverSSLTest from client";
+ public static final String QUEUE = "QueueOverSSL";
+ public static final int SSL_PORT = 5402;
+
+ // Static --------------------------------------------------------
+
+ private static final Logger log = Logger
+ .getLogger(CoreClientOverSSLTest.class);
+
+ // Attributes ----------------------------------------------------
+
+ private MessagingServer server;
+
+ private ClientConnection connection;
+
+ private ClientConsumer consumer;
+
+ // Constructors --------------------------------------------------
+
+ public CoreClientOverSSLTest(String name)
+ {
+ super(name);
+ }
+
+ // Public --------------------------------------------------------
+
+ public void testSSL() throws Exception
+ {
+ final Process p = SerializedClientSupport.spawnVM(CoreClientOverSSL.class
+ .getName(), Boolean.TRUE.toString(), "messaging.keystore",
+ "secureexample");
+
+ Message m = consumer.receive(10000);
+ assertNotNull(m);
+ assertEquals(MESSAGE_TEXT_FROM_CLIENT, new String(m.getPayload()));
+
+ log.info("waiting for the client VM to exit ...");
+ SerializedClientSupport.assertProcessExits(true, 0, p);
+ }
+
+ public void testSSLWithIncorrectKeyStorePassword() throws Exception
+ {
+ Process p = SerializedClientSupport.spawnVM(CoreClientOverSSL.class
+ .getName(), Boolean.TRUE.toString(), "messaging.keystore",
+ "incorrectKeyStorePassword");
+
+ Message m = consumer.receive(5000);
+ assertNull(m);
+
+ log.info("waiting for the client VM to exit ...");
+ SerializedClientSupport.assertProcessExits(false, 0, p);
+ }
+
+ public void testPlainConnectionToSSLEndpoint() throws Exception
+ {
+ Process p = SerializedClientSupport.spawnVM(CoreClientOverSSL.class
+ .getName(), FALSE.toString(), null, null);
+
+ Message m = consumer.receive(5000);
+ assertNull(m);
+
+ log.info("waiting for the client VM to exit ...");
+ SerializedClientSupport.assertProcessExits(false, 0, p);
+ }
+
+ // Package protected ---------------------------------------------
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ ConfigurationImpl config = ConfigurationHelper.newConfiguration(TCP,
+ "localhost", SSL_PORT);
+ config.setSSLEnabled(true);
+ config.setKeyStorePath("messaging.keystore");
+ config.setKeyStorePassword("secureexample");
+ config.setTrustStorePath("messaging.truststore");
+ config.setTrustStorePassword("secureexample");
+
+ server = new MessagingServerImpl(config);
+ server.start();
+
+ ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0, config, server.getVersion());
+ connection = cf.createConnection(null, null);
+ ClientSession session = connection.createClientSession(false, true, true, -1, false, false);
+ session.createQueue(QUEUE, QUEUE, null, false, false);
+ consumer = session.createConsumer(QUEUE, null, false, false, true);
+ connection.start();
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ consumer.close();
+ connection.close();
+
+ server.stop();
+
+ super.tearDown();
+ }
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/integration/jms/server/impl/JMSServerManagerimplTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/jms/server/impl/test/unit/JMSServerManagerimplTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/jms/server/impl/JMSServerManagerimplTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/jms/server/impl/JMSServerManagerimplTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,981 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.integration.jms.server.impl;
+
+import junit.framework.TestCase;
+import org.jboss.messaging.jms.server.JMSServerManager;
+import org.jboss.messaging.jms.server.ConnectionInfo;
+import org.jboss.messaging.jms.server.SubscriptionInfo;
+import org.jboss.messaging.jms.server.MessageStatistics;
+import org.jboss.messaging.jms.server.impl.JMSServerManagerImpl;
+import org.jboss.messaging.jms.client.JBossConnectionFactory;
+import org.jboss.messaging.core.server.MessagingServer;
+import org.jboss.messaging.core.server.impl.MessagingServerImpl;
+import org.jboss.messaging.core.management.impl.MessagingServerManagementImpl;
+import static org.jboss.messaging.core.remoting.TransportType.INVM;
+import org.jboss.messaging.core.security.JBMUpdateableSecurityManager;
+import org.jboss.messaging.core.config.impl.ConfigurationImpl;
+
+import javax.jms.*;
+import javax.naming.NameNotFoundException;
+import javax.naming.InitialContext;
+import java.util.Hashtable;
+import java.util.Set;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * JMSServerManagerImpl tests
+ * @author <a href="ataylor at redhat.com">Andy Taylor</a>
+ */
+public class JMSServerManagerimplTest extends TestCase
+{
+ private JMSServerManagerImpl jmsServerManager;
+ private InitialContext initialContext;
+ private MessagingServer messagingServer;
+
+ protected void setUp() throws Exception
+ {
+ jmsServerManager = new JMSServerManagerImpl();
+ MessagingServerManagementImpl messagingServerManagement = new MessagingServerManagementImpl();
+ ConfigurationImpl conf = new ConfigurationImpl();
+ conf.setInvmDisabled(false);
+ conf.setTransport(INVM);
+ messagingServer = new MessagingServerImpl(conf);
+ messagingServer.start();
+ jmsServerManager.setMessagingServerManagement(messagingServerManagement);
+ messagingServerManagement.setMessagingServer(messagingServer);
+ Hashtable env = new Hashtable();
+ env.put("java.naming.factory.initial",
+ "org.jboss.messaging.tests.util.InVMSingleInitialContextFactory");
+ initialContext = new InitialContext(env);
+ jmsServerManager.setInitialContext(initialContext);
+ }
+
+ protected void tearDown() throws Exception
+ {
+ //InVMInitialContextFactory.reset();
+ messagingServer.stop();
+ jmsServerManager = null;
+ messagingServer = null;
+ }
+
+ public void testIsStarted()
+ {
+ assertTrue(jmsServerManager.isStarted());
+ }
+
+ public void testCreateAndDestroyQueue() throws Exception
+ {
+ jmsServerManager.createQueue("anewtestqueue", "anewtestqueue");
+ Queue q = (Queue) initialContext.lookup("anewtestqueue");
+ assertNotNull(q);
+ jmsServerManager.destroyQueue("anewtestqueue");
+ try
+ {
+ initialContext.lookup("anewtestqueue");
+ fail("should throw eception");
+ }
+ catch (NameNotFoundException e)
+ {
+ //pass
+ }
+ jmsServerManager.createQueue("anewtestqueue", "/anewtestqueue");
+ q = (Queue) initialContext.lookup("/anewtestqueue");
+ assertNotNull(q);
+ jmsServerManager.destroyQueue("anewtestqueue");
+ try
+ {
+ initialContext.lookup("/anewtestqueue");
+ fail("should throw eception");
+ }
+ catch (NameNotFoundException e)
+ {
+ //pass
+ }
+
+ jmsServerManager.createQueue("anewtestqueue", "/queues/anewtestqueue");
+ initialContext.lookup("/queues/anewtestqueue");
+ assertNotNull(q);
+ jmsServerManager.destroyQueue("anewtestqueue");
+ try
+ {
+ initialContext.lookup("/queues/newtestqueue");
+ fail("should throw eception");
+ }
+ catch (NameNotFoundException e)
+ {
+ //pass
+ }
+
+ jmsServerManager.createQueue("anewtestqueue", "/queues/and/anewtestqueue");
+ q = (Queue) initialContext.lookup("/queues/and/anewtestqueue");
+ assertNotNull(q);
+ jmsServerManager.destroyQueue("anewtestqueue");
+ try
+ {
+ initialContext.lookup("/queues/and/anewtestqueue");
+ fail("should throw eception");
+ }
+ catch (NameNotFoundException e)
+ {
+ //pass
+ }
+ }
+
+ public void testCreateAndDestroyTopic() throws Exception
+ {
+ jmsServerManager.createTopic("anewtesttopic", "anewtesttopic");
+ Topic q = (Topic) initialContext.lookup("anewtesttopic");
+ assertNotNull(q);
+ jmsServerManager.destroyTopic("anewtesttopic");
+ try
+ {
+ q = (Topic) initialContext.lookup("anewtesttopic");
+ fail("should throw eception");
+ }
+ catch (NameNotFoundException e)
+ {
+ //pass
+ }
+ jmsServerManager.createTopic("anewtesttopic", "/anewtesttopic");
+ q = (Topic) initialContext.lookup("/anewtesttopic");
+ assertNotNull(q);
+ jmsServerManager.destroyTopic("anewtesttopic");
+ try
+ {
+ q = (Topic) initialContext.lookup("/anewtesttopic");
+ fail("should throw eception");
+ }
+ catch (NameNotFoundException e)
+ {
+ //pass
+ }
+
+ jmsServerManager.createTopic("anewtesttopic", "/topics/anewtesttopic");
+ q = (Topic) initialContext.lookup("/topics/anewtesttopic");
+ assertNotNull(q);
+ jmsServerManager.destroyTopic("anewtesttopic");
+ try
+ {
+ q = (Topic) initialContext.lookup("/topics/newtesttopic");
+ fail("should throw eception");
+ }
+ catch (NameNotFoundException e)
+ {
+ //pass
+ }
+
+ jmsServerManager.createTopic("anewtesttopic", "/topics/and/anewtesttopic");
+ q = (Topic) initialContext.lookup("/topics/and/anewtesttopic");
+ assertNotNull(q);
+ jmsServerManager.destroyTopic("anewtesttopic");
+ try
+ {
+ q = (Topic) initialContext.lookup("/topics/and/anewtesttopic");
+ fail("should throw eception");
+ }
+ catch (NameNotFoundException e)
+ {
+ //pass
+ }
+ }
+
+ public void testListAllQueues() throws Exception
+ {
+ ArrayList queuesAdded = new ArrayList();
+ for(int i = 0; i < 100; i++)
+ {
+ jmsServerManager.createQueue("aq" + i, "/aq"+ i);
+ queuesAdded.add("aq" + i);
+ }
+ Set<String> queueNames = jmsServerManager.listAllQueues();
+ for (Object o : queuesAdded)
+ {
+ assertTrue(queueNames.remove(o));
+ }
+ assertTrue(queueNames.isEmpty());
+ }
+
+ public void testListAllTopics() throws Exception
+ {
+ ArrayList topicsAdded = new ArrayList();
+ for(int i = 0; i < 100; i++)
+ {
+ jmsServerManager.createTopic("at" + i, "/at"+ i);
+ topicsAdded.add("at" + i);
+ }
+ Set<String> topicNames = jmsServerManager.listAllTopics();
+ for (Object o : topicsAdded)
+ {
+ assertTrue(topicNames.remove(o));
+ }
+ assertTrue(topicNames.isEmpty());
+ }
+
+ public void testCreateAndDestroyConnectionFactory() throws Exception
+ {
+ jmsServerManager.createConnectionFactory("newtestcf", "anid", 100, true, 1000, -1, 1000, -1, "newtestcf");
+ JBossConnectionFactory jbcf = (JBossConnectionFactory) initialContext.lookup("newtestcf");
+ assertNotNull(jbcf);
+ assertNotNull(jbcf.getDelegate());
+ jmsServerManager.destroyConnectionFactory("newtestcf");
+ try
+ {
+ initialContext.lookup("newtestcf");
+ fail("should throw exception");
+ }
+ catch (NameNotFoundException e)
+ {
+ //pass
+ }
+ ArrayList<String> bindings = new ArrayList<String>();
+ bindings.add("oranewtestcf");
+ bindings.add("newtestcf");
+ jmsServerManager.createConnectionFactory("newtestcf", "anid", 100, true, 1000, -1, 1000, -1, bindings);
+ jbcf = (JBossConnectionFactory) initialContext.lookup("newtestcf");
+ assertNotNull(jbcf);
+ assertNotNull(jbcf.getDelegate());
+ jbcf = (JBossConnectionFactory) initialContext.lookup("oranewtestcf");
+ assertNotNull(jbcf);
+ assertNotNull(jbcf.getDelegate());
+ jmsServerManager.destroyConnectionFactory("newtestcf");
+ try
+ {
+ initialContext.lookup("newtestcf");
+ fail("should throw exception");
+ }
+ catch (NameNotFoundException e)
+ {
+ //pass
+ }
+ try
+ {
+ initialContext.lookup("oranewtestcf");
+ fail("should throw exception");
+ }
+ catch (NameNotFoundException e)
+ {
+ //pass
+ }
+ }
+
+ public void testGetConnections() throws Exception
+ {
+ ArrayList<String> bindings = new ArrayList<String>();
+ bindings.add("cf");
+ jmsServerManager.createConnectionFactory("newtestcf", "anid", 100, true, 1000, -1, 1000, -1, bindings );
+ JBossConnectionFactory connectionFactory = (JBossConnectionFactory) initialContext.lookup("cf");
+
+ Connection conn = connectionFactory.createConnection("guest", "guest");
+ List<ConnectionInfo> connectionInfos = jmsServerManager.getConnections();
+ assertNotNull(connectionInfos);
+ assertEquals(1, connectionInfos.size());
+ ConnectionInfo connectionInfo = connectionInfos.get(0);
+ assertEquals("guest", connectionInfo.getUser());
+ assertEquals(ConnectionInfo.status.STOPPED, connectionInfo.getStatus());
+ conn.start();
+ // starting a connection is a remoting async operation
+ // wait a little before querying clients infos from the server
+ //sleepIfRemoting(250);
+ connectionInfos = jmsServerManager.getConnections();
+ assertNotNull(connectionInfos);
+ assertEquals(1, connectionInfos.size());
+ connectionInfo = connectionInfos.get(0);
+ assertEquals(ConnectionInfo.status.STARTED, connectionInfo.getStatus());
+ connectionInfo.getAddress();
+ connectionInfo.getTimeCreated();
+ connectionInfo.getAliveTime();
+ conn.close();
+ connectionInfos = jmsServerManager.getConnections();
+ assertNotNull(connectionInfos);
+ assertEquals(0, connectionInfos.size());
+ Connection conn2 = connectionFactory.createConnection("guest", "guest");
+ Connection conn3 = connectionFactory.createConnection("guest", "guest");
+ connectionInfos = jmsServerManager.getConnections();
+ assertNotNull(connectionInfos);
+ assertEquals(2, connectionInfos.size());
+ conn2.close();
+ connectionInfos = jmsServerManager.getConnections();
+ assertNotNull(connectionInfos);
+ assertEquals(1, connectionInfos.size());
+ conn3.close();
+ connectionInfos = jmsServerManager.getConnections();
+ assertNotNull(connectionInfos);
+ assertEquals(0, connectionInfos.size());
+ }
+
+ public void testGetConnectionsForUser() throws Exception
+ {
+ ArrayList<String> bindings = new ArrayList<String>();
+ bindings.add("cf");
+ jmsServerManager.createConnectionFactory("newtestcf", "anid", 100, true, 1000, -1, 1000, -1, bindings );
+ JBossConnectionFactory connectionFactory = (JBossConnectionFactory) initialContext.lookup("cf");
+
+ Connection conn = connectionFactory.createConnection("guest", "guest");
+ Connection conn2 = connectionFactory.createConnection();
+ Connection conn3 = connectionFactory.createConnection();
+ Connection conn4 = connectionFactory.createConnection("guest", "guest");
+ Connection conn5 = connectionFactory.createConnection("guest", "guest");
+
+ try
+ {
+ List<ConnectionInfo> connectionInfos = jmsServerManager.getConnectionsForUser("guest");
+ assertNotNull(connectionInfos);
+ assertEquals(connectionInfos.size(), 3);
+ for (ConnectionInfo connectionInfo : connectionInfos)
+ {
+ assertEquals(connectionInfo.getUser(), "guest");
+ }
+ }
+ finally
+ {
+ if (conn != null)
+ {
+ conn.close();
+ }
+ if (conn2 != null)
+ {
+ conn2.close();
+ }
+ if (conn3 != null)
+ {
+ conn3.close();
+ }
+ if (conn4 != null)
+ {
+ conn4.close();
+ }
+ if (conn5 != null)
+ {
+ conn5.close();
+ }
+ }
+
+ }
+
+ public void testDropConnectionForId() throws Exception
+ {
+ JBMUpdateableSecurityManager securityManager = (JBMUpdateableSecurityManager) messagingServer.getSecurityManager();
+ securityManager.addUser("john", "needle");
+ ArrayList<String> bindings = new ArrayList<String>();
+ bindings.add("cf");
+ jmsServerManager.createConnectionFactory("newtestcf", "anid", 100, true, 1000, -1, 1000, -1, bindings );
+ JBossConnectionFactory connectionFactory = (JBossConnectionFactory) initialContext.lookup("cf");
+
+ Connection conn = connectionFactory.createConnection("guest", "guest");
+ Connection conn2 = connectionFactory.createConnection();
+ Connection conn3 = connectionFactory.createConnection();
+ Connection conn4 = connectionFactory.createConnection("john", "needle");
+ Connection conn5 = connectionFactory.createConnection("guest", "guest");
+ String id = conn4.getClientID();
+ try
+ {
+
+ List<ConnectionInfo> connectionInfos = jmsServerManager.getConnectionsForUser("john");
+ assertEquals(connectionInfos.size(), 1);
+ jmsServerManager.dropConnection(connectionInfos.get(0).getId());
+ connectionInfos = jmsServerManager.getConnections();
+ assertNotNull(connectionInfos);
+ assertEquals(connectionInfos.size(), 4);
+ for (ConnectionInfo connectionInfo : connectionInfos)
+ {
+ assertNotSame(connectionInfo.getUser(), "john");
+ }
+ try
+ {
+ conn4.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ fail("Should throw exception");
+ }
+ catch (JMSException e)
+ {
+ //pass
+ }
+ }
+ finally
+ {
+ if (conn != null)
+ {
+ conn.close();
+ }
+ if (conn2 != null)
+ {
+ conn2.close();
+ }
+ if (conn3 != null)
+ {
+ conn3.close();
+ }
+ if (conn5 != null)
+ {
+ conn5.close();
+ }
+ }
+
+ }
+
+ public void testDropConnectionForUser() throws Exception
+ {
+ JBMUpdateableSecurityManager securityManager = (JBMUpdateableSecurityManager) messagingServer.getSecurityManager();
+ securityManager.addUser("john", "needle");
+ ArrayList<String> bindings = new ArrayList<String>();
+ bindings.add("cf");
+ jmsServerManager.createConnectionFactory("newtestcf", "anid", 100, true, 1000, -1, 1000, -1, bindings );
+ JBossConnectionFactory connectionFactory = (JBossConnectionFactory) initialContext.lookup("cf");
+
+ Connection conn = connectionFactory.createConnection("guest", "guest");
+ Connection conn2 = connectionFactory.createConnection();
+ Connection conn3 = connectionFactory.createConnection();
+ Connection conn4 = connectionFactory.createConnection("john", "needle");
+ Connection conn5 = connectionFactory.createConnection("guest", "guest");
+ String id = conn4.getClientID();
+ try
+ {
+ jmsServerManager.dropConnectionsForUser("guest");
+ List<ConnectionInfo> connectionInfos = jmsServerManager.getConnections();
+ assertNotNull(connectionInfos);
+ assertEquals(connectionInfos.size(), 3);
+ for (ConnectionInfo connectionInfo : connectionInfos)
+ {
+ assertNotSame(connectionInfo.getUser(), "guest");
+ }
+ try
+ {
+ conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ fail("Should throw exception");
+ }
+ catch (JMSException e)
+ {
+ //pass
+ }
+ try
+ {
+ conn5.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ fail("Should throw exception");
+ }
+ catch (JMSException e)
+ {
+ //pass
+ }
+ }
+ finally
+ {
+ if (conn2 != null)
+ {
+ conn2.close();
+ }
+ if (conn3 != null)
+ {
+ conn3.close();
+ }
+ if (conn4 != null)
+ {
+ conn4.close();
+ }
+ }
+
+ }
+
+ public void testListMessagesForQueue() throws Exception
+ {
+ ArrayList<String> bindings = new ArrayList<String>();
+ bindings.add("cf");
+ jmsServerManager.createConnectionFactory("newtestcf", "anid", 100, true, 1000, -1, 1000, -1, bindings );
+ JBossConnectionFactory connectionFactory = (JBossConnectionFactory) initialContext.lookup("cf");
+ jmsServerManager.createQueue("Queue1", "/queue1");
+ Queue queue1 = (Queue) initialContext.lookup("/queue1");
+ Connection conn = connectionFactory.createConnection("guest", "guest");
+ try
+ {
+ Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ MessageProducer producer = sess.createProducer(queue1);
+ producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
+ for (int i = 0; i < 10; i++)
+ {
+ TextMessage message = sess.createTextMessage();
+ message.setIntProperty("count", i);
+ producer.send(message);
+ }
+ producer.setDeliveryMode(DeliveryMode.PERSISTENT);
+ for (int i = 10; i < 20; i++)
+ {
+ TextMessage message = sess.createTextMessage();
+ message.setIntProperty("count", i);
+ producer.send(message);
+ }
+ List<Message> messageList = jmsServerManager.listMessagesForQueue("Queue1");
+ assertEquals(messageList.size(), 20);
+ for (int i = 0; i < messageList.size(); i++)
+ {
+ Message message = messageList.get(i);
+ assertEquals(message.getIntProperty("count"), i);
+ assertTrue(message instanceof TextMessage);
+ }
+ messageList = jmsServerManager.listMessagesForQueue("Queue1", JMSServerManager.ListType.NON_DURABLE);
+ assertEquals(messageList.size(), 10);
+ for (int i = 0; i < messageList.size(); i++)
+ {
+ Message message = messageList.get(i);
+ assertEquals(message.getIntProperty("count"), i);
+ assertTrue(message instanceof TextMessage);
+ assertTrue(message.getJMSDeliveryMode() == DeliveryMode.NON_PERSISTENT);
+ }
+ messageList = jmsServerManager.listMessagesForQueue("Queue1", JMSServerManager.ListType.DURABLE);
+ assertEquals(messageList.size(), 10);
+ for (int i = 10; i < messageList.size() + 10; i++)
+ {
+ Message message = messageList.get(i - 10);
+ assertEquals(message.getIntProperty("count"), i);
+ assertTrue(message instanceof TextMessage);
+ assertTrue(message.getJMSDeliveryMode() == DeliveryMode.PERSISTENT);
+ }
+ }
+ finally
+ {
+ if (conn != null)
+ {
+ conn.close();
+ }
+ }
+ }
+
+ // public void testRemoveMessageFromQueue() throws Exception
+// {
+// Connection conn = getConnectionFactory().createConnection("guest", "guest");
+// try
+// {
+// Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+// MessageProducer producer = sess.createProducer(queue1);
+// Message messageToDelete = null;
+// for (int i = 0; i < 10; i++)
+// {
+// TextMessage message = sess.createTextMessage();
+// message.setIntProperty("pos", i);
+// producer.send(message);
+// if (i == 5)
+// {
+// messageToDelete = message;
+// }
+// }
+// jmsServerManager.removeMessageFromQueue("Queue1", messageToDelete.getJMSMessageID());
+// sess = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
+// MessageConsumer consumer = sess.createConsumer(queue1);
+// conn.start();
+// int lastPos = -1;
+// for (int i = 0; i < 9; i++)
+// {
+// Message message = consumer.receive();
+// assertNotSame(messageToDelete.getJMSMessageID(), message.getJMSMessageID());
+// int pos = message.getIntProperty("pos");
+// assertTrue("returned in wrong order", pos > lastPos);
+// lastPos = pos;
+// }
+// }
+// finally
+// {
+// if (conn != null)
+// {
+// conn.close();
+// }
+// }
+// }
+
+// public void testRemoveMessageFromTopic() throws Exception
+// {
+// Connection conn = getConnectionFactory().createConnection("guest", "guest");
+// try
+// {
+// Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+// MessageProducer producer = sess.createProducer(topic1);
+// MessageConsumer consumer = sess.createConsumer(topic1);
+// MessageConsumer consumer2 = sess.createConsumer(topic1);
+// Message messageToDelete = null;
+// for (int i = 0; i < 10; i++)
+// {
+// TextMessage message = sess.createTextMessage();
+// producer.send(message);
+// if (i == 5)
+// {
+// messageToDelete = message;
+// }
+// }
+// jmsServerManager.removeMessageFromTopic("Topic1", messageToDelete.getJMSMessageID());
+// conn.start();
+// for (int i = 0; i < 9; i++)
+// {
+// Message message = consumer.receive();
+// assertNotSame(messageToDelete.getJMSMessageID(), message.getJMSMessageID());
+// message = consumer2.receive();
+// assertNotSame(messageToDelete.getJMSMessageID(), message.getJMSMessageID());
+// }
+// }
+// finally
+// {
+// if (conn != null)
+// {
+// conn.close();
+// }
+// }
+//
+// }
+
+// public void testRemoveAllMessagesFromQueue() throws Exception
+// {
+// Connection conn = getConnectionFactory().createConnection("guest", "guest");
+//
+// ServerManagement.getServer(0).createQueue("myQueue", null);
+//
+// Queue queue = (Queue)this.getInitialContext().lookup("/queue/myQueue");
+//
+// try
+// {
+// Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+// MessageProducer producer = sess.createProducer(queue);
+// for (int i = 0; i < 10; i++)
+// {
+// TextMessage message = sess.createTextMessage();
+// producer.send(message);
+// }
+// jmsServerManager.removeAllMessagesForQueue("myQueue");
+// sess = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
+// MessageConsumer consumer = sess.createConsumer(queue);
+// assertEquals("messages still exist", 0, jmsServerManager.getMessageCountForQueue("myQueue"));
+//
+// }
+// finally
+// {
+// if (conn != null)
+// {
+// conn.close();
+// }
+//
+// try
+// {
+// ServerManagement.getServer(0).destroyQueue("myQueue", null);
+// }
+// catch (Exception ignore)
+// {
+// }
+// }
+// }
+
+ public void testListMessagesForSubscription() throws Exception
+ {
+ ArrayList<String> bindings = new ArrayList<String>();
+ bindings.add("cf");
+ jmsServerManager.createConnectionFactory("newtestcf", null, 100, true, 1000, -1, 1000, -1, bindings );
+ JBossConnectionFactory connectionFactory = (JBossConnectionFactory) initialContext.lookup("cf");
+ jmsServerManager.createTopic("topic1", "/topic1");
+ Topic topic1 = (Topic) initialContext.lookup("/topic1");
+ Connection conn = connectionFactory.createConnection("guest", "guest");
+ try
+ {
+ String cid = "myclientid";
+ String id = "mysubid";
+ conn.setClientID(cid);
+ Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ TopicSubscriber subscriber = sess.createDurableSubscriber(topic1, id);
+ MessageProducer producer = sess.createProducer(topic1);
+
+ producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
+ for (int i = 0; i < 10; i++)
+ {
+ TextMessage message = sess.createTextMessage();
+ message.setIntProperty("count", i);
+ producer.send(message);
+ }
+ producer.setDeliveryMode(DeliveryMode.PERSISTENT);
+ for (int i = 10; i < 20; i++)
+ {
+ TextMessage message = sess.createTextMessage();
+ message.setIntProperty("count", i);
+ producer.send(message);
+ }
+
+ assertEquals(20, jmsServerManager.listMessagesForSubscription(cid + "." + id).size());
+ assertEquals(10, jmsServerManager.listMessagesForSubscription(cid + "." + id, JMSServerManager.ListType.DURABLE).size());
+ assertEquals(10, jmsServerManager.listMessagesForSubscription(cid + "." + id, JMSServerManager.ListType.NON_DURABLE).size());
+ subscriber.close();
+ sess.unsubscribe(id);
+ }
+ finally
+ {
+ if (conn != null)
+ {
+ conn.close();
+ }
+ }
+ }
+
+// public void testMoveMessage() throws Exception
+// {
+// Connection conn = getConnectionFactory().createConnection("guest", "guest");
+// try
+// {
+// Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+// MessageProducer producer = sess.createProducer(queue1);
+// Message messageToMove = null;
+// for (int i = 0; i < 10; i++)
+// {
+// TextMessage message = sess.createTextMessage();
+// producer.send(message);
+// if (i == 5)
+// {
+// messageToMove = message;
+// }
+// }
+// jmsServerManager.moveMessage("Queue1", "Queue2", messageToMove.getJMSMessageID());
+// MessageConsumer consumer = sess.createConsumer(queue1);
+// conn.start();
+// for (int i = 0; i < 9; i++)
+// {
+// Message message = consumer.receive();
+// assertNotSame(messageToMove.getJMSMessageID(), message.getJMSMessageID());
+// }
+// consumer.close();
+// consumer = sess.createConsumer(queue2);
+// Message message = consumer.receive();
+// assertEquals(messageToMove.getJMSMessageID(), message.getJMSMessageID());
+// }
+// finally
+// {
+// if (conn != null)
+// {
+// conn.close();
+// }
+// }
+//
+// }
+
+
+ public void testRemoveAllMessagesFromTopic() throws Exception
+ {
+ ArrayList<String> bindings = new ArrayList<String>();
+ bindings.add("cf");
+ jmsServerManager.createConnectionFactory("newtestcf", "anid", 100, true, 1000, -1, 1000, -1, bindings );
+ JBossConnectionFactory connectionFactory = (JBossConnectionFactory) initialContext.lookup("cf");
+ Connection conn = connectionFactory.createConnection("guest", "guest");
+ jmsServerManager.createTopic("topic1", "/topic1");
+ Topic topic1 = (Topic) initialContext.lookup("/topic1");
+ try
+ {
+ Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ MessageProducer producer = sess.createProducer(topic1);
+ MessageConsumer consumer = sess.createConsumer(topic1);
+ MessageConsumer consumer2 = sess.createConsumer(topic1);
+ Message messageToDelete = null;
+ for (int i = 0; i < 10; i++)
+ {
+ TextMessage message = sess.createTextMessage();
+ producer.send(message);
+ if (i == 5)
+ {
+ messageToDelete = message;
+ }
+ }
+ jmsServerManager.removeAllMessagesForTopic("Topic1");
+ List<SubscriptionInfo> subscriptionInfos = jmsServerManager.listSubscriptions("Topic1");
+ for (SubscriptionInfo subscriptionInfo : subscriptionInfos)
+ {
+ assertEquals(0, jmsServerManager.listMessagesForSubscription(subscriptionInfo.getId()).size());
+ }
+ }
+ finally
+ {
+ if (conn != null)
+ {
+ conn.close();
+ }
+ }
+
+ }
+
+// public void testChangeMessagePriority() throws Exception
+// {
+// Connection conn = getConnectionFactory().createConnection("guest", "guest");
+// try
+// {
+// Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+// MessageProducer producer = sess.createProducer(queue1);
+// producer.setPriority(9);
+// Message messageToMove = null;
+// for (int i = 0; i < 10; i++)
+// {
+// TextMessage message = sess.createTextMessage();
+//
+// producer.send(message);
+// if (i == 5)
+// {
+// messageToMove = message;
+// }
+// }
+// jmsServerManager.changeMessagePriority("Queue1", messageToMove.getJMSMessageID(), 8);
+// MessageConsumer consumer = sess.createConsumer(queue1);
+// conn.start();
+// for (int i = 0; i < 9; i++)
+// {
+// Message message = consumer.receive();
+// assertNotSame(messageToMove.getJMSMessageID(), message.getJMSMessageID());
+// System.out.println("message.getJMSPriority() = " + message.getJMSPriority());
+// assertEquals(9, message.getJMSPriority());
+// }
+// Message message = consumer.receive();
+// assertEquals(8, message.getJMSPriority());
+// assertEquals(messageToMove.getJMSMessageID(), message.getJMSMessageID());
+//
+// consumer.close();
+//
+// }
+// finally
+// {
+// if (conn != null)
+// {
+// conn.close();
+// }
+// }
+//
+// }
+
+
+ public void testExpireMessage() throws Exception
+ {
+ ArrayList<String> bindings = new ArrayList<String>();
+ bindings.add("cf");
+ jmsServerManager.createConnectionFactory("newtestcf", "anid", 100, true, 1000, -1, 1000, -1, bindings );
+ JBossConnectionFactory connectionFactory = (JBossConnectionFactory) initialContext.lookup("cf");
+ Connection conn = connectionFactory.createConnection("guest", "guest");
+ jmsServerManager.createQueue("QueueWithOwnDLQAndExpiryQueue", "/queue/QueueWithOwnDLQAndExpiryQueue");
+ jmsServerManager.createQueue("PrivateExpiryQueue", "/queue/PrivateExpiryQueue");
+
+ try
+ {
+ Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ Queue q = (Queue) initialContext.lookup("/queue/QueueWithOwnDLQAndExpiryQueue");
+ MessageProducer producer = sess.createProducer(q);
+ Message messageToMove = null;
+ for (int i = 0; i < 10; i++)
+ {
+ TextMessage message = sess.createTextMessage();
+ producer.send(message);
+ if (i == 5)
+ {
+ messageToMove = message;
+ }
+ }
+ jmsServerManager.expireMessage("QueueWithOwnDLQAndExpiryQueue", messageToMove.getJMSMessageID());
+ MessageConsumer consumer = sess.createConsumer(q);
+ conn.start();
+ for (int i = 0; i < 9; i++)
+ {
+ Message message = consumer.receive();
+ assertNotSame(messageToMove.getJMSMessageID(), message.getJMSMessageID());
+ }
+ consumer.close();
+ Queue expQueue = (Queue) initialContext.lookup("/queue/PrivateExpiryQueue");
+ consumer = sess.createConsumer(expQueue);
+ Message message = consumer.receive();
+ assertEquals(messageToMove.getJMSMessageID(), message.getJMSMessageID());
+ }
+ finally
+ {
+ if (conn != null)
+ {
+ conn.close();
+ }
+ }
+
+ }
+
+ public void testMessageStatistics() throws Exception
+ {
+ ArrayList<String> bindings = new ArrayList<String>();
+ bindings.add("cf");
+ jmsServerManager.createConnectionFactory("newtestcf", "anid", 100, true, 1000, -1, 1000, -1, bindings );
+ JBossConnectionFactory connectionFactory = (JBossConnectionFactory) initialContext.lookup("cf");
+ Connection conn = connectionFactory.createConnection("guest", "guest");
+ try
+ {
+ jmsServerManager.createQueue("CountQueue", "/queue/CountQueue");
+ Queue queue1 = (Queue) initialContext.lookup("/queue/CountQueue");
+ Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ MessageProducer producer = sess.createProducer(queue1);
+
+ TextMessage message = sess.createTextMessage();
+ for(int i = 0; i < 100; i++)
+ {
+ producer.send(message);
+ }
+ jmsServerManager.startGatheringStatisticsForQueue("CountQueue");
+ for(int i = 0; i < 100; i++)
+ {
+ producer.send(message);
+ }
+ List<MessageStatistics> messageStatistics = jmsServerManager.getStatistics();
+ assertTrue(messageStatistics != null && messageStatistics.size() ==1);
+ assertEquals(messageStatistics.get(0).getCount(), 100);
+ assertEquals(messageStatistics.get(0).getTotalMessageCount(), 200);
+ assertEquals(messageStatistics.get(0).getCurrentMessageCount(), 200);
+ MessageConsumer consumer = sess.createConsumer(queue1);
+ conn.start();
+ for(int i = 0; i < 50; i++)
+ {
+ consumer.receive();
+ }
+ messageStatistics = jmsServerManager.getStatistics();
+ assertEquals(messageStatistics.get(0).getCount(), 100);
+ assertEquals(messageStatistics.get(0).getTotalMessageCount(), 200);
+ assertEquals(messageStatistics.get(0).getCurrentMessageCount(), 150);
+ consumer.close();
+ for(int i = 0; i < 50; i++)
+ {
+ producer.send(message);
+ }
+ messageStatistics = jmsServerManager.getStatistics();
+ assertEquals(messageStatistics.get(0).getCount(), 150);
+ assertEquals(messageStatistics.get(0).getTotalMessageCount(), 250);
+ assertEquals(messageStatistics.get(0).getCurrentMessageCount(), 200);
+
+ consumer = sess.createConsumer(queue1);
+ conn.start();
+ for(int i = 0; i < 200; i++)
+ {
+ consumer.receive();
+ }
+ messageStatistics = jmsServerManager.getStatistics();
+ assertEquals(messageStatistics.get(0).getCount(), 150);
+ assertEquals(messageStatistics.get(0).getTotalMessageCount(), 250);
+ assertEquals(messageStatistics.get(0).getCurrentMessageCount(), 0);
+ consumer.close();
+ jmsServerManager.stopGatheringStatisticsForQueue("CountQueue");
+ messageStatistics = jmsServerManager.getStatistics();
+ assertTrue(messageStatistics != null && messageStatistics.size() == 0);
+ }
+ finally
+ {
+ if (conn != null)
+ {
+ conn.close();
+ }
+ }
+
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/stress/core/remoting/mina/PacketStressTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/mina/stress/PacketStressTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/stress/core/remoting/mina/PacketStressTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/stress/core/remoting/mina/PacketStressTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,166 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.stress.core.remoting.mina;
+
+import static org.jboss.messaging.core.remoting.TransportType.TCP;
+import static org.jboss.messaging.tests.integration.core.remoting.mina.TestSupport.PORT;
+
+import java.util.Random;
+import java.util.concurrent.CountDownLatch;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.config.Configuration;
+import org.jboss.messaging.core.remoting.NIOConnector;
+import org.jboss.messaging.core.remoting.NIOSession;
+import org.jboss.messaging.core.remoting.Packet;
+import org.jboss.messaging.core.remoting.PacketHandler;
+import org.jboss.messaging.core.remoting.PacketSender;
+import org.jboss.messaging.tests.unit.core.remoting.impl.ConfigurationHelper;
+import org.jboss.messaging.core.remoting.impl.PacketDispatcherImpl;
+import org.jboss.messaging.core.remoting.impl.mina.MinaConnector;
+import org.jboss.messaging.core.remoting.impl.mina.MinaService;
+import org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl;
+import org.jboss.messaging.core.remoting.impl.wireformat.BytesPacket;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class PacketStressTest extends TestCase
+{
+
+ // Constants -----------------------------------------------------
+
+ private static final int MANY_MESSAGES = 100000;
+ private static final int PAYLOAD = 10000; // in bytes
+
+ // Attributes ----------------------------------------------------
+
+ private MinaService service;
+ private NIOConnector connector;
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ Configuration config = ConfigurationHelper.newConfiguration(TCP, "localhost", PORT);
+ service = new MinaService(config);
+ service.start();
+ connector = new MinaConnector(config, new PacketDispatcherImpl(null));
+
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ connector.disconnect();
+ service.stop();
+
+ connector = null;
+ service = null;
+ }
+
+ public void testManyPackets() throws Exception
+ {
+ int spinner = MANY_MESSAGES / 100;
+ System.out.println("number of messages: " + MANY_MESSAGES);
+ System.out.println("message payload: " + MANY_MESSAGES + " bytes");
+ System.out.println("# => " + spinner + " messages sent (1% of total messages)");
+ System.out.println(". => " + spinner + " messages received (1% of total messages)");
+ System.out.println();
+
+
+ final long handlerID = 12346;
+ CountDownLatch latch = new CountDownLatch(1);
+
+ service.getDispatcher().register(new ServerHandler(handlerID, latch, spinner));
+ NIOSession session = connector.connect();
+
+ byte[] payloadBytes = generatePayload(PAYLOAD);
+ PacketImpl packet = new BytesPacket(payloadBytes);
+ packet.setTargetID(handlerID);
+
+ long start = System.currentTimeMillis();
+ for (int i = 0; i < MANY_MESSAGES; i++)
+ {
+ session.write(packet);
+ if (i % spinner == 0)
+ System.out.print('#');
+ }
+
+ long durationForSending = System.currentTimeMillis() - start;
+ latch.await();
+ long durationForReceiving = System.currentTimeMillis() - start;
+
+ System.out.println();
+ System.out.println(MANY_MESSAGES + " messages of " + PAYLOAD + "B sent one-way in " + durationForSending + "ms");
+ System.out.println(MANY_MESSAGES + " messages of " + PAYLOAD + "B received on the server in " + durationForReceiving + "ms");
+ System.out.println("==============");
+
+ // in MB/s
+ double sendingThroughput = (MANY_MESSAGES * PAYLOAD) / (durationForSending * 1000);
+ double receivingThroughput = (MANY_MESSAGES * PAYLOAD) / (durationForReceiving * 1000);
+
+ System.out.format("sending throughput: %.1f MB/s\n", sendingThroughput);
+ System.out.format("receiving throughput: %.1f MB/s\n", receivingThroughput);
+ System.out.println("==============");
+ }
+
+ private byte[] generatePayload(int payload)
+ {
+ Random rand = new Random(System.currentTimeMillis());
+ byte[] bytes = new byte[payload];
+ rand.nextBytes(bytes);
+ return bytes;
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ private final class ServerHandler implements PacketHandler
+ {
+ private final long handlerID;
+ private CountDownLatch latch;
+ private int messagesReceived;
+ private int spinner;
+
+ private ServerHandler(long handlerID, CountDownLatch latch, int spinner)
+ {
+ this.handlerID = handlerID;
+ this.latch = latch;
+ this.spinner = spinner;
+ messagesReceived = 0;
+ }
+
+ public long getID()
+ {
+ return handlerID;
+ }
+
+ public void handle(Packet packet, PacketSender sender)
+ {
+ messagesReceived++;
+ if (messagesReceived % spinner == 0)
+ System.out.print('.');
+ if (messagesReceived == MANY_MESSAGES)
+ {
+ latch.countDown();
+ }
+ }
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/config/impl/ConfigurationTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/config/impl/test/unit/ConfigurationTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/config/impl/ConfigurationTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/config/impl/ConfigurationTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,178 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.config.impl;
+
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.config.impl.FileConfiguration;
+import org.jboss.messaging.core.remoting.TransportType;
+
+/**
+ * @author <a href="ataylor at redhat.com">Andy Taylor</a>
+ */
+public class ConfigurationTest extends TestCase
+{
+ private FileConfiguration configuration;
+
+ protected void setUp() throws Exception
+ {
+ configuration = new FileConfiguration();
+ configuration.setConfigurationUrl("ConfigurationTest-config.xml");
+ configuration.start();
+ }
+
+ protected void tearDown() throws Exception
+ {
+ configuration = null;
+ }
+
+ public void testSetServerPeerId() throws Exception
+ {
+ assertEquals("failed to set ServerPeerId", 10, configuration.getMessagingServerID());
+ }
+
+ public void testSetSecurityDomain() throws Exception
+ {
+ assertEquals("failed to set security domain", "java:/jaas/messagingtest", configuration.getSecurityDomain());
+ }
+
+ public void testSetMessageCounterSamplePeriod() throws Exception
+ {
+ assertEquals("failed to set Message Counter sample period", 50000, configuration.getMessageCounterSamplePeriod());
+ }
+
+ public void testSetDefaultMessageCounterHistory() throws Exception
+ {
+ assertEquals("failed to set default message counter history", new Integer(21), configuration.getDefaultMessageCounterHistoryDayLimit());
+ }
+
+ public void testSetStrictTck() throws Exception
+ {
+ assertEquals("failed to set strict tck", Boolean.TRUE, configuration.isStrictTck());
+ }
+
+ public void testSetClustered() throws Exception
+ {
+ assertEquals("failed to set clustered", Boolean.TRUE, configuration.isClustered());
+ }
+
+ public void testSetTransport() throws Exception
+ {
+ assertEquals(TransportType.TCP, configuration.getTransport());
+ }
+
+ public void testRemotingHost() throws Exception
+ {
+ assertEquals("localhost", configuration.getHost());
+ }
+
+ public void testSetRemotingPort() throws Exception
+ {
+ assertEquals(10000, configuration.getPort());
+
+ }
+
+ public void testSetRemotingTimeout() throws Exception
+ {
+ assertEquals(100, configuration.getTimeout());
+ }
+
+ public void testRemotingTcpNodelay() throws Exception
+ {
+ assertEquals(true, configuration.isTcpNoDelay());
+ }
+
+ public void testRemotingTcpReceiveBufferSize() throws Exception
+ {
+ assertEquals(8192, configuration.getTcpReceiveBufferSize());
+ }
+
+ public void testRemotingTcpSendBufferSize() throws Exception
+ {
+ assertEquals(1024, configuration.getTcpSendBufferSize());
+ }
+
+ public void testRemotingEnableSSL() throws Exception
+ {
+ assertEquals(true, configuration.isSSLEnabled());
+ }
+
+ public void testRemotingSSLKeyStorePath() throws Exception
+ {
+ assertEquals("messaging.keystore", configuration.getKeyStorePath());
+ }
+
+ public void testRemotingSSLKeyStorePassword() throws Exception
+ {
+ assertEquals("secureexample keystore", configuration.getKeyStorePassword());
+ }
+
+ public void testRemotingSSLTrustStorePath() throws Exception
+ {
+ assertEquals("messaging.truststore", configuration.getTrustStorePath());
+ }
+
+ public void testRemotingSSLTrustStorePassword() throws Exception
+ {
+ assertEquals("secureexample truststore", configuration.getTrustStorePassword());
+ }
+
+ public void testSetInterceptorsList() throws Exception
+ {
+ assertEquals("Didn't get the correct number of elements on interceptors", 2, configuration.getDefaultInterceptors().size());
+ assertEquals("org.jboss.tst", configuration.getDefaultInterceptors().get(0));
+ assertEquals("org.jboss.tst2", configuration.getDefaultInterceptors().get(1));
+ }
+
+ //config is supposed to be immutable??
+// public void testPropertyChangeListener() throws Exception
+// {
+// MyListener listener = new MyListener();
+// configuration.addPropertyChangeListener(listener);
+// listener.setCalled(false);
+// configuration.setMessageCounterSamplePeriod(1000000);
+// assertTrue("property change listener not fired", listener.isCalled());
+// }
+
+ class MyListener implements PropertyChangeListener
+ {
+ boolean called = false;
+
+ public boolean isCalled()
+ {
+ return called;
+ }
+
+ public void setCalled(boolean called)
+ {
+ this.called = called;
+ }
+
+ public void propertyChange(PropertyChangeEvent evt)
+ {
+ called = true;
+ }
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/DeployerTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/deployers/impl/test/unit/DeployerTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/DeployerTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/DeployerTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,244 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.deployers.impl;
+
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.deployers.Deployer;
+import org.jboss.messaging.core.deployers.impl.XmlDeployer;
+import org.jboss.messaging.util.XMLUtil;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.HashMap;
+
+/**
+ * tests the abstract deployer class
+ * @author <a href="ataylor at redhat.com">Andy Taylor</a>
+ */
+public class DeployerTest extends TestCase
+{
+ private String conf1 = "<deployment>\n" +
+ " <test name=\"test1\">content1</test>\n" +
+ " <test name=\"test2\">content2</test>\n" +
+ " <test name=\"test3\">content3</test>\n" +
+ " <test name=\"test4\">content4</test>\n" +
+ "</deployment>";
+
+ private String conf2 = "<deployment>\n" +
+ " <test name=\"test1\">content1</test>\n" +
+ " <test name=\"test2\">contenthaschanged2</test>\n" +
+ " <test name=\"test3\">contenthaschanged3</test>\n" +
+ " <test name=\"test4\">content4</test>\n" +
+ "</deployment>";
+
+ private String conf3 = "<deployment>\n" +
+ " <test name=\"test1\">content1</test>\n" +
+ " <test name=\"test2\">contenthaschanged2</test>\n" +
+ "</deployment>";
+
+ private String conf4 = "<deployment>\n" +
+ " <test name=\"test1\">content1</test>\n" +
+ " <test name=\"test2\">content2</test>\n" +
+ " <test name=\"test3\">content3</test>\n" +
+ " <test name=\"test4\">content4</test>\n" +
+ " <test name=\"test5\">content5</test>\n" +
+ " <test name=\"test6\">content6</test>\n" +
+ "</deployment>";
+
+ private URL url;
+
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+ url = new URL("http://thisdoesntmatter");
+ }
+
+ public void testDeploy() throws Exception
+ {
+ Element e = XMLUtil.stringToElement(conf1);
+ TestDeployer testDeployer = new TestDeployer();
+ testDeployer.setElement(e);
+ testDeployer.deploy(url);
+ assertEquals(testDeployer.getDeployments(), 4);
+ assertNotNull(testDeployer.getNodes().get("test1"));
+ assertNotNull(testDeployer.getNodes().get("test2"));
+ assertNotNull(testDeployer.getNodes().get("test3"));
+ assertNotNull(testDeployer.getNodes().get("test4"));
+ assertEquals(testDeployer.getNodes().get("test1").getTextContent(), "content1");
+ assertEquals(testDeployer.getNodes().get("test2").getTextContent(), "content2");
+ assertEquals(testDeployer.getNodes().get("test3").getTextContent(), "content3");
+ assertEquals(testDeployer.getNodes().get("test4").getTextContent(), "content4");
+ }
+
+ public void testRedeploy() throws Exception
+ {
+ Element e = XMLUtil.stringToElement(conf1);
+ TestDeployer testDeployer = new TestDeployer();
+ testDeployer.setElement(e);
+ testDeployer.deploy(url);
+ e = XMLUtil.stringToElement(conf2);
+ testDeployer.setElement(e);
+ testDeployer.redeploy(url);
+ assertEquals(testDeployer.getDeployments(), 4);
+ assertNotNull(testDeployer.getNodes().get("test1"));
+ assertNotNull(testDeployer.getNodes().get("test2"));
+ assertNotNull(testDeployer.getNodes().get("test3"));
+ assertNotNull(testDeployer.getNodes().get("test4"));
+ assertEquals(testDeployer.getNodes().get("test1").getTextContent(), "content1");
+ assertEquals(testDeployer.getNodes().get("test2").getTextContent(), "contenthaschanged2");
+ assertEquals(testDeployer.getNodes().get("test3").getTextContent(), "contenthaschanged3");
+ assertEquals(testDeployer.getNodes().get("test4").getTextContent(), "content4");
+ }
+
+ public void testRedeployRemovingNodes() throws Exception
+ {
+ Element e = XMLUtil.stringToElement(conf1);
+ TestDeployer testDeployer = new TestDeployer();
+ testDeployer.setElement(e);
+ testDeployer.deploy(url);
+ e = XMLUtil.stringToElement(conf3);
+ testDeployer.setElement(e);
+ testDeployer.redeploy(url);
+ assertEquals(testDeployer.getDeployments(), 2);
+ assertNotNull(testDeployer.getNodes().get("test1"));
+ assertNotNull(testDeployer.getNodes().get("test2"));
+ assertNull(testDeployer.getNodes().get("test3"));
+ assertNull(testDeployer.getNodes().get("test4"));
+ assertEquals(testDeployer.getNodes().get("test1").getTextContent(), "content1");
+ assertEquals(testDeployer.getNodes().get("test2").getTextContent(), "contenthaschanged2");
+ }
+
+ public void testRedeployAddingNodes() throws Exception
+ {
+ Element e = XMLUtil.stringToElement(conf1);
+ TestDeployer testDeployer = new TestDeployer();
+ testDeployer.setElement(e);
+ testDeployer.deploy(url);
+ e = XMLUtil.stringToElement(conf4);
+ testDeployer.setElement(e);
+ testDeployer.redeploy(url);
+ assertEquals(testDeployer.getDeployments(), 6);
+ assertNotNull(testDeployer.getNodes().get("test1"));
+ assertNotNull(testDeployer.getNodes().get("test2"));
+ assertNotNull(testDeployer.getNodes().get("test3"));
+ assertNotNull(testDeployer.getNodes().get("test4"));
+ assertNotNull(testDeployer.getNodes().get("test5"));
+ assertNotNull(testDeployer.getNodes().get("test6"));
+ assertEquals(testDeployer.getNodes().get("test1").getTextContent(), "content1");
+ assertEquals(testDeployer.getNodes().get("test2").getTextContent(), "content2");
+ assertEquals(testDeployer.getNodes().get("test3").getTextContent(), "content3");
+ assertEquals(testDeployer.getNodes().get("test4").getTextContent(), "content4");
+ assertEquals(testDeployer.getNodes().get("test5").getTextContent(), "content5");
+ assertEquals(testDeployer.getNodes().get("test6").getTextContent(), "content6");
+ }
+
+ public void testUndeploy() throws Exception
+ {
+ Element e = XMLUtil.stringToElement(conf1);
+ TestDeployer testDeployer = new TestDeployer();
+ testDeployer.setElement(e);
+ testDeployer.deploy(url);
+ testDeployer.undeploy(url);
+ assertEquals(testDeployer.getDeployments(), 0);
+ assertNull(testDeployer.getNodes().get("test1"));
+ assertNull(testDeployer.getNodes().get("test2"));
+ assertNull(testDeployer.getNodes().get("test3"));
+ assertNull(testDeployer.getNodes().get("test4"));
+ }
+ class TestDeployer extends XmlDeployer
+ {
+ private String elementname = "test";
+ Element element = null;
+ private int deployments = 0;
+ ArrayList<String> contents = new ArrayList<String>();
+ HashMap<String, Node> nodes = new HashMap<String, Node>();
+
+ public HashMap<String, Node> getNodes()
+ {
+ return nodes;
+ }
+
+ public ArrayList<String> getContents()
+ {
+ return contents;
+ }
+
+ public int getDeployments()
+ {
+ return deployments;
+ }
+
+ public String getElementname()
+ {
+ return elementname;
+ }
+
+ public void setElementname(String elementname)
+ {
+ this.elementname = elementname;
+ }
+
+ public Element getElement()
+ {
+ return element;
+ }
+
+ public void setElement(Element element)
+ {
+ this.element = element;
+ }
+
+ public String[] getElementTagName()
+ {
+ return new String[]{elementname};
+ }
+
+
+ public String getConfigFileName()
+ {
+ return "test";
+ }
+
+ public void deploy(Node node) throws Exception
+ {
+ deployments++;
+ contents.add(node.getTextContent());
+ nodes.put(node.getAttributes().getNamedItem(NAME_ATTR).getNodeValue(), node);
+ }
+
+ public void undeploy(Node node) throws Exception
+ {
+ deployments--;
+ nodes.remove(node.getAttributes().getNamedItem(NAME_ATTR).getNodeValue());
+ }
+
+ protected Element getRootElement(URL url)
+ {
+ return element;
+ }
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/QueueSettingsDeployerTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/deployers/impl/test/unit/QueueSettingsDeployerTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/QueueSettingsDeployerTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/QueueSettingsDeployerTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,137 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.deployers.impl;
+
+import junit.framework.TestCase;
+
+import org.easymock.EasyMock;
+import org.easymock.IArgumentMatcher;
+import org.jboss.messaging.core.deployers.impl.QueueSettingsDeployer;
+import org.jboss.messaging.core.postoffice.PostOffice;
+import org.jboss.messaging.core.postoffice.impl.BindingImpl;
+import org.jboss.messaging.core.server.Queue;
+import org.jboss.messaging.core.settings.HierarchicalRepository;
+import org.jboss.messaging.core.settings.impl.QueueSettings;
+import org.jboss.messaging.util.XMLUtil;
+
+/**
+ * @author <a href="ataylor at redhat.com">Andy Taylor</a>
+ */
+public class QueueSettingsDeployerTest extends TestCase
+{
+ private String conf = "<queue-settings match=\"queues.*\">\n" +
+ " <clustered>false</clustered>\n" +
+ " <dlq>DLQtest</dlq>\n" +
+ " <expiry-queue>ExpiryQueueTest</expiry-queue>\n" +
+ " <redelivery-delay>100</redelivery-delay>\n" +
+ " <max-size>-100</max-size>\n" +
+ " <distribution-policy-class>org.jboss.messaging.core.impl.RoundRobinDistributionPolicy</distribution-policy-class>\n" +
+ " <message-counter-history-day-limit>1000</message-counter-history-day-limit>\n" +
+ " </queue-settings>";
+
+ private QueueSettingsDeployer queueSettingsDeployer;
+
+ private HierarchicalRepository<QueueSettings> repository;
+ private PostOffice postOffice;
+
+ protected void setUp() throws Exception
+ {
+ postOffice = EasyMock.createMock(PostOffice.class);
+
+ repository = EasyMock.createStrictMock(HierarchicalRepository.class);
+
+ queueSettingsDeployer = new QueueSettingsDeployer(postOffice, repository);
+ }
+
+ public void testDeploy() throws Exception
+ {
+ QueueSettings queueSettings = new QueueSettings();
+ queueSettings.setClustered(false);
+ queueSettings.setRedeliveryDelay((long) 100);
+ queueSettings.setMaxSize(-100);
+ queueSettings.setDistributionPolicyClass("org.jboss.messaging.core.impl.RoundRobinDistributionPolicy");
+ queueSettings.setMessageCounterHistoryDayLimit(1000);
+ Queue mockDLQ = EasyMock.createMock(Queue.class);
+ queueSettings.setDLQ(mockDLQ);
+ EasyMock.expect(postOffice.getBinding("DLQtest")).andReturn(new BindingImpl(0, "DLQtest", mockDLQ));
+ EasyMock.expect(postOffice.getBinding("DLQtest")).andReturn(new BindingImpl(0, "DLQtest", mockDLQ));
+ Queue mockQ = EasyMock.createMock(Queue.class);
+ queueSettings.setExpiryQueue(mockQ);
+ EasyMock.expect(postOffice.getBinding("ExpiryQueueTest")).andReturn(new BindingImpl(0, "ExpiryQueueTest", mockQ));
+ EasyMock.expect(postOffice.getBinding("ExpiryQueueTest")).andReturn(new BindingImpl(0, "ExpiryQueueTest", mockQ));
+
+ EasyMock.replay(postOffice);
+
+ repository.addMatch(EasyMock.eq("queues.*"), settings(queueSettings));
+
+ EasyMock.replay(repository);
+ EasyMock.reportMatcher(new QueueSettingsMatcher(queueSettings));
+ queueSettingsDeployer.deploy(XMLUtil.stringToElement(conf));
+ }
+
+ public void testUndeploy()
+ {
+ repository.removeMatch(conf);
+ EasyMock.replay(repository);
+
+ }
+
+ public static QueueSettings settings(QueueSettings queueSettings)
+ {
+ EasyMock.reportMatcher(new QueueSettingsMatcher(queueSettings));
+ return queueSettings;
+ }
+
+ static class QueueSettingsMatcher implements IArgumentMatcher
+ {
+ QueueSettings queueSettings;
+
+ public QueueSettingsMatcher(QueueSettings queueSettings)
+ {
+ this.queueSettings = queueSettings;
+ }
+
+ public boolean matches(Object o)
+ {
+ if (this == o) return true;
+
+ QueueSettings that = (QueueSettings) o;
+
+ if (!queueSettings.getDLQ().equals(that.getDLQ())) return false;
+ if (!queueSettings.getExpiryQueue().equals(that.getExpiryQueue())) return false;
+ if (!queueSettings.isClustered().equals(that.isClustered())) return false;
+ if (!queueSettings.getDistributionPolicyClass().equals(that.getDistributionPolicyClass())) return false;
+ if (!queueSettings.getMaxDeliveryAttempts().equals(that.getMaxDeliveryAttempts())) return false;
+ if (!queueSettings.getMaxSize().equals(that.getMaxSize())) return false;
+ if (!queueSettings.getMessageCounterHistoryDayLimit().equals(that.getMessageCounterHistoryDayLimit()))
+ return false;
+ if (!queueSettings.getRedeliveryDelay().equals(that.getRedeliveryDelay())) return false;
+
+ return true;
+ }
+
+ public void appendTo(StringBuffer stringBuffer)
+ {
+ stringBuffer.append("Invalid Queue Settings created");
+ }
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/SecurityDeployerTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/deployers/impl/test/unit/SecurityDeployerTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/SecurityDeployerTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/SecurityDeployerTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,107 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.deployers.impl;
+
+import junit.framework.TestCase;
+import org.easymock.EasyMock;
+import org.jboss.messaging.core.deployers.impl.SecurityDeployer;
+import org.jboss.messaging.core.security.Role;
+import org.jboss.messaging.core.settings.HierarchicalRepository;
+import org.jboss.messaging.util.XMLUtil;
+import org.w3c.dom.Element;
+
+import java.util.HashSet;
+
+/**
+ * @author <a href="ataylor at redhat.com">Andy Taylor</a>
+ */
+public class SecurityDeployerTest extends TestCase
+{
+ private SecurityDeployer deployer;
+ private String conf =
+ " <security match=\"topics.testTopic\">\n" +
+ " <permission type=\"create\" roles=\"durpublisher\"/>\n" +
+ " <permission type=\"read\" roles=\"guest,publisher,durpublisher\"/>\n" +
+ " <permission type=\"write\" roles=\"guest,publisher,durpublisher\"/>\n" +
+ " </security>";
+
+ private String conf2 =
+ " <security match=\"queues.testQueue\">\n" +
+ " <permission type=\"create\" roles=\"durpublisher\"/>\n" +
+ " <permission type=\"read\" roles=\"guest,publisher,durpublisher\"/>\n" +
+ " <permission type=\"write\" roles=\"guest,publisher,durpublisher\"/>\n" +
+ " </security>";
+
+ private String noRoles =
+ " <securityfoo match=\"queues.testQueue\">\n" +
+ " </securityfoo>";
+ private HierarchicalRepository<HashSet<Role>> repository;
+
+ protected void setUp() throws Exception
+ {
+ repository = EasyMock.createStrictMock(HierarchicalRepository.class);
+ deployer = new SecurityDeployer(EasyMock.createStrictMock(HierarchicalRepository.class));
+ }
+
+ public void testSingle() throws Exception
+ {
+
+
+ Element e = XMLUtil.stringToElement(conf);
+ Role role = new Role("durpublisher", true, true, true);
+ Role role2 = new Role("guest", true, true, false);
+ Role role3 = new Role("publisher", true, true, false);
+ HashSet<Role> roles = new HashSet<Role>();
+ roles.add(role);
+ roles.add(role2);
+ roles.add(role3);
+ repository.addMatch("topics.testTopic", roles);
+ EasyMock.replay(repository);
+ deployer.deploy(e);
+
+ }
+
+ public void testMultiple() throws Exception
+ {
+ Role role = new Role("durpublisher", true, true, true);
+ Role role2 = new Role("guest", true, true, false);
+ Role role3 = new Role("publisher", true, true, false);
+ HashSet<Role> roles = new HashSet<Role>();
+ roles.add(role);
+ roles.add(role2);
+ roles.add(role3);
+ repository.addMatch("topics.testTopic", roles);
+ repository.addMatch("queues.testQueue", roles);
+ EasyMock.replay(repository);
+ deployer.deploy(XMLUtil.stringToElement(conf));
+ deployer.deploy(XMLUtil.stringToElement(conf2));
+
+ }
+ public void testNoRolesAdded() throws Exception
+ {
+ HashSet<Role> roles = new HashSet<Role>();
+ repository.addMatch("queues.testQueue", roles);
+ EasyMock.replay(repository);
+ deployer.deploy(XMLUtil.stringToElement(noRoles));
+
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/SecurityManagerDeployerTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/deployers/impl/test/unit/SecurityManagerDeployerTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/SecurityManagerDeployerTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/deployers/impl/SecurityManagerDeployerTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,141 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.deployers.impl;
+
+import junit.framework.TestCase;
+import org.jboss.messaging.core.deployers.impl.SecurityManagerDeployer;
+import org.jboss.messaging.core.security.impl.JBMSecurityManagerImpl;
+import org.jboss.messaging.core.security.JBMUpdateableSecurityManager;
+import org.jboss.messaging.util.XMLUtil;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Node;
+import org.easymock.EasyMock;
+
+/**
+ * tests SecurityManagerDeployer
+ * @author <a href="ataylor at redhat.com">Andy Taylor</a>
+ */
+public class SecurityManagerDeployerTest extends TestCase
+{
+ SecurityManagerDeployer deployer;
+ String simpleSecurityXml = "<deployment>\n" +
+ "</deployment>";
+
+ String singleUserXml = "<deployment>\n" +
+ " <user name=\"guest\" password=\"guest\">\n" +
+ " <role name=\"guest\"/>\n" +
+ " </user>\n" +
+ "</deployment>";
+
+ String multipleUserXml = "<deployment>\n" +
+ " <user name=\"guest\" password=\"guest\">\n" +
+ " <role name=\"guest\"/>\n" +
+ " <role name=\"foo\"/>\n" +
+ " </user>\n" +
+ " <user name=\"anotherguest\" password=\"anotherguest\">\n" +
+ " <role name=\"anotherguest\"/>\n" +
+ " <role name=\"foo\"/>\n" +
+ " <role name=\"bar\"/>\n" +
+ " </user>\n" +
+ "</deployment>";
+
+ protected void setUp() throws Exception
+ {
+ deployer = new SecurityManagerDeployer();
+ }
+
+ protected void tearDown() throws Exception
+ {
+ deployer = null;
+ }
+
+ private void deploy(String xml) throws Exception
+ {
+ NodeList children = XMLUtil.stringToElement(xml).getChildNodes();
+ for (int i = 0; i < children.getLength(); i++)
+ {
+ Node node = children.item(i);
+ if(node.getNodeName().equals("user"))
+ {
+ deployer.deploy(node);
+ }
+ }
+ }
+
+ private void undeploy(String xml) throws Exception
+ {
+ NodeList children = XMLUtil.stringToElement(xml).getChildNodes();
+ for (int i = 0; i < children.getLength(); i++)
+ {
+ Node node = children.item(i);
+ if(node.getNodeName().equals("user"))
+ {
+ deployer.undeploy(node);
+ }
+ }
+ }
+
+ public void testSimpleDefaultSecurity() throws Exception
+ {
+ JBMUpdateableSecurityManager securityManager = EasyMock.createStrictMock(JBMUpdateableSecurityManager.class);
+ deployer.setJbmSecurityManager(securityManager);
+ EasyMock.replay(securityManager);
+ deploy(simpleSecurityXml);
+ }
+
+ public void testSingleUserDeploySecurity() throws Exception
+ {
+ JBMUpdateableSecurityManager securityManager = EasyMock.createStrictMock(JBMUpdateableSecurityManager.class);
+ deployer.setJbmSecurityManager(securityManager);
+ securityManager.addUser("guest", "guest");
+ securityManager.addRole("guest", "guest");
+ EasyMock.replay(securityManager);
+ deploy(singleUserXml);
+ }
+
+ public void testMultipleUserDeploySecurity() throws Exception
+ {
+ JBMUpdateableSecurityManager securityManager = EasyMock.createStrictMock(JBMUpdateableSecurityManager.class);
+ deployer.setJbmSecurityManager(securityManager);
+ securityManager.addUser("guest", "guest");
+ securityManager.addRole("guest", "guest");
+ securityManager.addRole("guest", "foo");
+ securityManager.addUser("anotherguest", "anotherguest");
+ securityManager.addRole("anotherguest", "anotherguest");
+ securityManager.addRole("anotherguest", "foo");
+ securityManager.addRole("anotherguest", "bar");
+
+ EasyMock.replay(securityManager);
+ deploy(multipleUserXml);
+ }
+
+ public void testUndeploy() throws Exception
+ {
+ JBMUpdateableSecurityManager securityManager = EasyMock.createStrictMock(JBMUpdateableSecurityManager.class);
+ deployer.setJbmSecurityManager(securityManager);
+ securityManager.removeUser("guest");
+ securityManager.removeUser("anotherguest");
+
+ EasyMock.replay(securityManager);
+ undeploy(multipleUserXml);
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/filter/impl/FilterParserTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/filter/impl/test/unit/FilterParserTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/filter/impl/FilterParserTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/filter/impl/FilterParserTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,332 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.filter.impl;
+
+import java.io.ByteArrayInputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.jboss.messaging.core.filter.impl.Identifier;
+import org.jboss.messaging.core.filter.impl.Operator;
+import org.jboss.messaging.core.filter.impl.FilterParser;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.tests.util.UnitTestCase;
+
+/**
+ Tests of the JavaCC LL(1) parser for the JBoss Messaging filters
+
+ @author Scott.Stark at jboss.org
+ @author d_jencks at users.sourceforge.net
+ @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+
+ @version $Revision: 3465 $
+
+ * (david jencks) Used constructor of SelectorParser taking a stream
+ * to avoid reInit npe in all tests. Changed to JBossTestCase and logging.
+ */
+public class FilterParserTest extends UnitTestCase
+{
+ private static final Logger log = Logger.getLogger(FilterParserTest.class);
+
+ private Map<String, Identifier> identifierMap;
+
+ private FilterParser parser;
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+
+ identifierMap = new HashMap<String, Identifier>();
+
+ parser = new FilterParser(new ByteArrayInputStream(new byte[0]));
+ }
+
+ public void testSimpleUnary() throws Exception
+ {
+ // Neg Long
+ log.trace("parse(-12345 = -1 * 12345)");
+ Operator result = (Operator) parser.parse("-12345 = -1 * 12345", identifierMap);
+ log.trace("result -> "+result);
+ Boolean b = (Boolean) result.apply();
+ assertTrue("is true", b.booleanValue());
+
+ // Neg Double
+ log.trace("parse(-1 * 12345.67 = -12345.67)");
+ result = (Operator) parser.parse("-1 * 12345.67 = -12345.67", identifierMap);
+ log.trace("result -> "+result);
+ b = (Boolean) result.apply();
+ assertTrue("is true", b.booleanValue());
+
+ log.trace("parse(-(1 * 12345.67) = -12345.67)");
+ result = (Operator) parser.parse("-(1 * 12345.67) = -12345.67", identifierMap);
+ log.trace("result -> "+result);
+ b = (Boolean) result.apply();
+ assertTrue("is true", b.booleanValue());
+ }
+
+ public void testPrecedenceNAssoc() throws Exception
+ {
+ log.trace("parse(4 + 2 * 3 / 2 = 7)");
+ Operator result = (Operator) parser.parse("4 + 2 * 3 / 2 = 7", identifierMap);
+ log.trace("result -> "+result);
+ Boolean b = (Boolean) result.apply();
+ assertTrue("is true", b.booleanValue());
+
+ log.trace("parse(4 + ((2 * 3) / 2) = 7)");
+ result = (Operator) parser.parse("4 + ((2 * 3) / 2) = 7", identifierMap);
+ log.trace("result -> "+result);
+ b = (Boolean) result.apply();
+ assertTrue("is true", b.booleanValue());
+
+ log.trace("parse(4 * -2 / -1 - 4 = 4)");
+ result = (Operator) parser.parse("4 * -2 / -1 - 4 = 4", identifierMap);
+ log.trace("result -> "+result);
+ b = (Boolean) result.apply();
+ assertTrue("is true", b.booleanValue());
+
+ log.trace("parse(4 * ((-2 / -1) - 4) = -8)");
+ result = (Operator) parser.parse("4 * ((-2 / -1) - 4) = -8", identifierMap);
+ log.trace("result -> "+result);
+ b = (Boolean) result.apply();
+ assertTrue("is true", b.booleanValue());
+ }
+
+ public void testIds() throws Exception
+ {
+ log.trace("parse(a + b * c / d = e)");
+ Operator result = (Operator) parser.parse("a + b * c / d = e", identifierMap);
+ // 4 + 2 * 3 / 2 = 7
+ Identifier a = identifierMap.get("a");
+ a.setValue(new Long(4));
+ Identifier b = identifierMap.get("b");
+ b.setValue(new Long(2));
+ Identifier c = identifierMap.get("c");
+ c.setValue(new Long(3));
+ Identifier d = identifierMap.get("d");
+ d.setValue(new Long(2));
+ Identifier e = identifierMap.get("e");
+ e.setValue(new Long(7));
+ log.trace("result -> "+result);
+ Boolean bool = (Boolean) result.apply();
+ assertTrue("is true", bool.booleanValue());
+
+ }
+
+ public void testTrueINOperator() throws Exception
+ {
+ log.trace("parse(Status IN ('new', 'cleared', 'acknowledged'))");
+ Operator result = (Operator) parser.parse("Status IN ('new', 'cleared', 'acknowledged')", identifierMap);
+ Identifier a = identifierMap.get("Status");
+ a.setValue("new");
+ log.trace("result -> "+result);
+ Boolean bool = (Boolean) result.apply();
+ assertTrue("is true", bool.booleanValue());
+ }
+ public void testFalseINOperator() throws Exception
+ {
+ log.trace("parse(Status IN ('new', 'cleared', 'acknowledged'))");
+ Operator result = (Operator) parser.parse("Status IN ('new', 'cleared', 'acknowledged')", identifierMap);
+ Identifier a = identifierMap.get("Status");
+ a.setValue("none");
+ log.trace("result -> "+result);
+ Boolean bool = (Boolean) result.apply();
+ assertTrue("is false", !bool.booleanValue());
+ }
+
+ public void testTrueOROperator() throws Exception
+ {
+ log.trace("parse((Status = 'new') OR (Status = 'cleared') OR (Status = 'acknowledged'))");
+ Operator result = (Operator) parser.parse("(Status = 'new') OR (Status = 'cleared') OR (Status= 'acknowledged')", identifierMap);
+ Identifier a = identifierMap.get("Status");
+ a.setValue("new");
+ log.trace("result -> "+result);
+ Boolean bool = (Boolean) result.apply();
+ assertTrue("is true", bool.booleanValue());
+ }
+ public void testFalseOROperator() throws Exception
+ {
+ log.trace("parse((Status = 'new') OR (Status = 'cleared') OR (Status = 'acknowledged'))");
+ Operator result = (Operator) parser.parse("(Status = 'new') OR (Status = 'cleared') OR (Status = 'acknowledged')", identifierMap);
+ Identifier a = identifierMap.get("Status");
+ a.setValue("none");
+ log.trace("result -> "+result);
+ Boolean bool = (Boolean) result.apply();
+ assertTrue("is false", !bool.booleanValue());
+ }
+
+ public void testInvalidSelector() throws Exception
+ {
+ log.trace("parse(definitely not a message selector!)");
+ try
+ {
+ Object result = parser.parse("definitely not a message selector!", identifierMap);
+ log.trace("result -> "+result);
+ fail("Should throw an Exception.\n");
+ }
+ catch (Exception e)
+ {
+ log.trace("testInvalidSelector failed as expected", e);
+ }
+ }
+
+ /**
+ * Test diffent syntax for approximate numeric literal (+6.2, -95.7, 7.)
+ */
+ public void testApproximateNumericLiteral1()
+ {
+ try
+ {
+ log.trace("parse(average = +6.2)");
+ Object result = parser.parse("average = +6.2", identifierMap);
+ log.trace("result -> "+result);
+ } catch (Exception e)
+ {
+ fail(""+e);
+ }
+ }
+
+ public void testApproximateNumericLiteral2()
+ {
+ try
+ {
+ log.trace("parse(average = -95.7)");
+ Object result = parser.parse("average = -95.7", identifierMap);
+ log.trace("result -> "+result);
+ } catch (Exception e)
+ {
+ fail(""+e);
+ }
+ }
+ public void testApproximateNumericLiteral3()
+ {
+ try
+ {
+ log.trace("parse(average = 7.)");
+ Object result = parser.parse("average = 7.", identifierMap);
+ log.trace("result -> "+result);
+ } catch (Exception e)
+ {
+ fail(""+e);
+ }
+ }
+
+ public void testGTExact()
+ {
+ try
+ {
+ log.trace("parse(weight > 2500)");
+ Operator result = (Operator)parser.parse("weight > 2500", identifierMap);
+ (identifierMap.get("weight")).setValue(new Integer(3000));
+ log.trace("result -> "+result);
+ Boolean bool = (Boolean) result.apply();
+ assertTrue("is true", bool.booleanValue());
+ } catch (Exception e)
+ {
+ log.trace("failed", e);
+ fail(""+e);
+ }
+ }
+
+ public void testGTFloat()
+ {
+ try
+ {
+ log.trace("parse(weight > 2500)");
+ Operator result = (Operator)parser.parse("weight > 2500", identifierMap);
+ (identifierMap.get("weight")).setValue(new Float(3000));
+ log.trace("result -> "+result);
+ Boolean bool = (Boolean) result.apply();
+ assertTrue("is true", bool.booleanValue());
+ } catch (Exception e)
+ {
+ log.trace("failed", e);
+ fail(""+e);
+ }
+ }
+
+ public void testLTDouble()
+ {
+ try
+ {
+ log.trace("parse(weight < 1.5)");
+ Operator result = (Operator)parser.parse("weight < 1.5", identifierMap);
+ (identifierMap.get("weight")).setValue(new Double(1.2));
+ log.trace("result -> "+result);
+ Boolean bool = (Boolean) result.apply();
+ assertTrue("is true", bool.booleanValue());
+ } catch (Exception e)
+ {
+ log.trace("failed", e);
+ fail(""+e);
+ }
+ }
+
+ public void testAndCombination()
+ {
+ try
+ {
+ log.trace("parse(JMSType = 'car' AND color = 'blue' AND weight > 2500)");
+ Operator result = (Operator)parser.parse("JMSType = 'car' AND color = 'blue' AND weight > 2500", identifierMap);
+ (identifierMap.get("JMSType")).setValue("car");
+ (identifierMap.get("color")).setValue("blue");
+ (identifierMap.get("weight")).setValue("3000");
+
+ log.trace("result -> "+result);
+ Boolean bool = (Boolean) result.apply();
+ assertTrue("is false", !bool.booleanValue());
+ } catch (Exception e)
+ {
+ log.trace("failed", e);
+ fail(""+e);
+ }
+ }
+
+ public void testINANDCombination()
+ {
+ try
+ {
+ log.trace("parse(Cateogry IN ('category1') AND Rating >= 2");
+ Operator result = (Operator)parser.parse("Cateogry IN ('category1') AND Rating >= 2", identifierMap);
+ (identifierMap.get("Cateogry")).setValue("category1");
+ (identifierMap.get("Rating")).setValue(new Integer(3));
+ log.trace("result -> "+result);
+ Boolean bool = (Boolean) result.apply();
+ assertTrue("is true", bool.booleanValue());
+ } catch (Exception e)
+ {
+ log.trace("failed", e);
+ fail(""+e);
+ }
+ }
+
+ /** This testcase does not use the JBossServer so override
+ the testServerFound to be a noop
+ */
+ public void testServerFound()
+ {
+ }
+
+ public static void main(java.lang.String[] args)
+ {
+ junit.textui.TestRunner.run(FilterParserTest.class);
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/filter/impl/FilterTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/filter/impl/test/unit/FilterTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/filter/impl/FilterTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/filter/impl/FilterTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,615 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.filter.impl;
+
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.filter.Filter;
+import org.jboss.messaging.core.filter.impl.FilterImpl;
+import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.core.message.impl.MessageImpl;
+import junit.framework.TestCase;
+
+/**
+ * Tests the compliance with the JBoss Messaging Filter syntax.
+ *
+ * <p>Needs a lot of work...
+ *
+ * @author <a href="mailto:jason at planet57.com">Jason Dillon</a>
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * @version $Revision: 3514 $
+ */
+public class FilterTest extends TestCase
+{
+ private Filter filter;
+
+ private Message message;
+
+ public FilterTest(String name)
+ {
+ super(name);
+ }
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+
+ message = new MessageImpl();
+ }
+
+ public void testInvalidString() throws Exception
+ {
+ testInvalidFilter("invalid");
+
+ testInvalidFilter("color = 'red");
+
+ testInvalidFilter("3");
+
+ testInvalidFilter(null);
+ }
+
+ public void testJBMDurable() throws Exception
+ {
+ filter = new FilterImpl("JBMDurable='DURABLE'");
+
+ Message message = new MessageImpl();
+ message.setDurable(true);
+
+ assertTrue(filter.match(message));
+
+ message.setDurable(false);
+
+ assertFalse(filter.match(message));
+
+ filter = new FilterImpl("JBMDurable='NON_DURABLE'");
+
+ message = new MessageImpl();
+ message.setDurable(true);
+
+ assertFalse(filter.match(message));
+
+ message.setDurable(false);
+
+ assertTrue(filter.match(message));
+
+ }
+
+ public void testJBMPriority() throws Exception
+ {
+ filter = new FilterImpl("JBMPriority=3");
+
+ Message message = new MessageImpl();
+
+ for (int i = 0; i < 10; i++)
+ {
+ message.setPriority((byte)i);
+
+ if (i == 3)
+ {
+ assertTrue(filter.match(message));
+ }
+ else
+ {
+ assertFalse(filter.match(message));
+ }
+ }
+ }
+
+ public void testJBMMessageID() throws Exception
+ {
+ filter = new FilterImpl("JBMMessageID=11223344");
+
+ Message message = new MessageImpl();
+
+ message.setMessageID(78676);
+
+ assertFalse(filter.match(message));
+
+ message.setMessageID(11223344);
+
+ assertTrue(filter.match(message));
+ }
+
+ public void testJBMTimestamp() throws Exception
+ {
+ filter = new FilterImpl("JBMTimestamp=12345678");
+
+ Message message = new MessageImpl();
+
+ message.setTimestamp(87654321);
+
+ assertFalse(filter.match(message));
+
+ message.setTimestamp(12345678);
+
+ assertTrue(filter.match(message));
+ }
+
+ public void testBooleanTrue() throws Exception
+ {
+ filter = new FilterImpl("MyBoolean=true");
+
+ testBoolean("MyBoolean", true);
+ }
+
+ public void testBooleanFalse() throws Exception
+ {
+ filter = new FilterImpl("MyBoolean=false");
+ testBoolean("MyBoolean", false);
+ }
+
+ private void testBoolean(String name, boolean flag) throws Exception
+ {
+ message.putHeader(name, flag);
+ assertTrue(filter.match(message));
+
+ message.putHeader(name, !flag);
+ assertTrue(!filter.match(message));
+ }
+
+ public void testStringEquals() throws Exception
+ {
+ // First, simple test of string equality and inequality
+ filter = new FilterImpl("MyString='astring'");
+
+ message.putHeader("MyString", "astring");
+ assertTrue(filter.match(message));
+
+ message.putHeader("MyString", "NOTastring");
+ assertTrue(!filter.match(message));
+
+ // test empty string
+ filter = new FilterImpl("MyString=''");
+
+ message.putHeader("MyString", "");
+ assertTrue("test 1", filter.match(message));
+
+ message.putHeader("MyString", "NOTastring");
+ assertTrue("test 2", !filter.match(message));
+
+ // test literal apostrophes (which are escaped using two apostrophes
+ // in selectors)
+ filter = new FilterImpl("MyString='test JBoss''s filter'");
+
+ // note: apostrophes are not escaped in string properties
+ message.putHeader("MyString", "test JBoss's filter");
+ // this test fails -- bug 530120
+ //assertTrue("test 3", filter.match(message));
+
+ message.putHeader("MyString", "NOTastring");
+ assertTrue("test 4", !filter.match(message));
+
+ }
+
+ public void testStringLike() throws Exception
+ {
+ // test LIKE operator with no wildcards
+ filter = new FilterImpl("MyString LIKE 'astring'");
+
+ // test where LIKE operand matches
+ message.putHeader("MyString", "astring");
+ assertTrue(filter.match(message));
+
+ // test one character string
+ filter = new FilterImpl("MyString LIKE 'a'");
+ message.putHeader("MyString","a");
+ assertTrue(filter.match(message));
+
+ // test empty string
+ filter = new FilterImpl("MyString LIKE ''");
+ message.putHeader("MyString", "");
+ assertTrue(filter.match(message));
+
+ // tests where operand does not match
+ filter = new FilterImpl("MyString LIKE 'astring'");
+
+ // test with extra characters at beginning
+ message.putHeader("MyString", "NOTastring");
+ assertTrue(!filter.match(message));
+
+ // test with extra characters at end
+ message.putHeader("MyString", "astringNOT");
+ assertTrue(!filter.match(message));
+
+ // test with extra characters in the middle
+ message.putHeader("MyString", "astNOTring");
+ assertTrue(!filter.match(message));
+
+ // test where operand is entirely different
+ message.putHeader("MyString", "totally different");
+ assertTrue(!filter.match(message));
+
+ // test case sensitivity
+ message.putHeader("MyString", "ASTRING");
+ assertTrue(!filter.match(message));
+
+ // test empty string
+ message.putHeader("MyString", "");
+ assertTrue(!filter.match(message));
+
+
+ // test lower-case 'like' operator?
+ }
+
+ public void testStringLikeUnderbarWildcard() throws Exception
+ {
+ // test LIKE operator with the _ wildcard, which
+ // matches any single character
+
+ // first, some tests with the wildcard by itself
+ filter = new FilterImpl("MyString LIKE '_'");
+
+ // test match against single character
+ message.putHeader("MyString", "a");
+ assertTrue(filter.match(message));
+
+ // test match failure against multiple characters
+ message.putHeader("MyString", "aaaaa");
+ assertTrue(!filter.match(message));
+
+ // test match failure against the empty string
+ message.putHeader("MyString", "");
+ assertTrue(!filter.match(message));
+
+
+ // next, tests with wildcard at the beginning of the string
+ filter = new FilterImpl("MyString LIKE '_bcdf'");
+
+ // test match at beginning of string
+ message.putHeader("MyString", "abcdf");
+ assertTrue(filter.match(message));
+
+ // match failure in first character after wildcard
+ message.putHeader("MyString", "aXcdf");
+ assertTrue(!filter.match(message));
+
+ // match failure in middle character
+ message.putHeader("MyString", "abXdf");
+ assertTrue(!filter.match(message));
+
+ // match failure in last character
+ message.putHeader("MyString", "abcdX");
+ assertTrue(!filter.match(message));
+
+ // match failure with empty string
+ message.putHeader("MyString", "");
+ assertTrue(!filter.match(message));
+
+ // match failure due to extra characters at beginning
+ message.putHeader("MyString", "XXXabcdf");
+ assertTrue(!filter.match(message));
+
+ // match failure due to extra characters at the end
+ message.putHeader("MyString", "abcdfXXX");
+ assertTrue(!filter.match(message));
+
+ // test that the _ wildcard does not match the 'empty' character
+ message.putHeader("MyString", "bcdf");
+ assertTrue(!filter.match(message));
+
+ // next, tests with wildcard at the end of the string
+ filter = new FilterImpl("MyString LIKE 'abcd_'");
+
+ // test match at end of string
+ message.putHeader("MyString", "abcdf");
+ assertTrue(filter.match(message));
+
+ // match failure in first character before wildcard
+ message.putHeader("MyString", "abcXf");
+ assertTrue(!filter.match(message));
+
+ // match failure in middle character
+ message.putHeader("MyString", "abXdf");
+ assertTrue(!filter.match(message));
+
+ // match failure in first character
+ message.putHeader("MyString", "Xbcdf");
+ assertTrue(!filter.match(message));
+
+ // match failure with empty string
+ message.putHeader("MyString", "");
+ assertTrue(!filter.match(message));
+
+ // match failure due to extra characters at beginning
+ message.putHeader("MyString", "XXXabcdf");
+ assertTrue(!filter.match(message));
+
+ // match failure due to extra characters at the end
+ message.putHeader("MyString", "abcdfXXX");
+ assertTrue(!filter.match(message));
+
+ // test that the _ wildcard does not match the 'empty' character
+ message.putHeader("MyString", "abcd");
+ assertTrue(!filter.match(message));
+
+ // test match in middle of string
+
+ // next, tests with wildcard in the middle of the string
+ filter = new FilterImpl("MyString LIKE 'ab_df'");
+
+ // test match in the middle of string
+ message.putHeader("MyString", "abcdf");
+ assertTrue(filter.match(message));
+
+ // match failure in first character before wildcard
+ message.putHeader("MyString", "aXcdf");
+ assertTrue(!filter.match(message));
+
+ // match failure in first character after wildcard
+ message.putHeader("MyString", "abcXf");
+ assertTrue(!filter.match(message));
+
+ // match failure in last character
+ message.putHeader("MyString", "abcdX");
+ assertTrue(!filter.match(message));
+
+ // match failure with empty string
+ message.putHeader("MyString", "");
+ assertTrue(!filter.match(message));
+
+ // match failure due to extra characters at beginning
+ message.putHeader("MyString", "XXXabcdf");
+ assertTrue(!filter.match(message));
+
+ // match failure due to extra characters at the end
+ message.putHeader("MyString", "abcdfXXX");
+ assertTrue(!filter.match(message));
+
+ // test that the _ wildcard does not match the 'empty' character
+ message.putHeader("MyString", "abdf");
+ assertTrue(!filter.match(message));
+
+ // test match failures
+ }
+
+ public void testStringLikePercentWildcard() throws Exception
+ {
+ // test LIKE operator with the % wildcard, which
+ // matches any sequence of characters
+ // note many of the tests are similar to those for _
+
+
+ // first, some tests with the wildcard by itself
+ filter = new FilterImpl("MyString LIKE '%'");
+
+ // test match against single character
+ message.putHeader("MyString", "a");
+ assertTrue(filter.match(message));
+
+ // test match against multiple characters
+ message.putHeader("MyString", "aaaaa");
+ assertTrue(filter.match(message));
+
+ message.putHeader("MyString", "abcdf");
+ assertTrue(filter.match(message));
+
+ // test match against the empty string
+ message.putHeader("MyString", "");
+ assertTrue(filter.match(message));
+
+
+ // next, tests with wildcard at the beginning of the string
+ filter = new FilterImpl("MyString LIKE '%bcdf'");
+
+ // test match with single character at beginning of string
+ message.putHeader("MyString", "Xbcdf");
+ assertTrue(filter.match(message));
+
+ // match with multiple characters at beginning
+ message.putHeader("MyString", "XXbcdf");
+ assertTrue(filter.match(message));
+
+ // match failure in middle character
+ message.putHeader("MyString", "abXdf");
+ assertTrue(!filter.match(message));
+
+ // match failure in last character
+ message.putHeader("MyString", "abcdX");
+ assertTrue(!filter.match(message));
+
+ // match failure with empty string
+ message.putHeader("MyString", "");
+ assertTrue(!filter.match(message));
+
+ // match failure due to extra characters at the end
+ message.putHeader("MyString", "abcdfXXX");
+ assertTrue(!filter.match(message));
+
+ // test that the % wildcard matches the empty string
+ message.putHeader("MyString", "bcdf");
+ assertTrue(filter.match(message));
+
+ // next, tests with wildcard at the end of the string
+ filter = new FilterImpl("MyString LIKE 'abcd%'");
+
+ // test match of single character at end of string
+ message.putHeader("MyString", "abcdf");
+ assertTrue(filter.match(message));
+
+ // test match of multiple characters at end of string
+ message.putHeader("MyString", "abcdfgh");
+ assertTrue(filter.match(message));
+
+ // match failure in first character before wildcard
+ message.putHeader("MyString", "abcXf");
+ assertTrue(!filter.match(message));
+
+ // match failure in middle character
+ message.putHeader("MyString", "abXdf");
+ assertTrue(!filter.match(message));
+
+ // match failure in first character
+ message.putHeader("MyString", "Xbcdf");
+ assertTrue(!filter.match(message));
+
+ // match failure with empty string
+ message.putHeader("MyString", "");
+ assertTrue(!filter.match(message));
+
+ // match failure due to extra characters at beginning
+ message.putHeader("MyString", "XXXabcdf");
+ assertTrue(!filter.match(message));
+
+ // test that the % wildcard matches the empty string
+ message.putHeader("MyString", "abcd");
+ assertTrue(filter.match(message));
+
+ // next, tests with wildcard in the middle of the string
+ filter = new FilterImpl("MyString LIKE 'ab%df'");
+
+ // test match with single character in the middle of string
+ message.putHeader("MyString", "abXdf");
+ assertTrue(filter.match(message));
+
+ // test match with multiple characters in the middle of string
+ message.putHeader("MyString", "abXXXdf");
+ assertTrue(filter.match(message));
+
+ // match failure in first character before wildcard
+ message.putHeader("MyString", "aXcdf");
+ assertTrue(!filter.match(message));
+
+ // match failure in first character after wildcard
+ message.putHeader("MyString", "abcXf");
+ assertTrue(!filter.match(message));
+
+ // match failure in last character
+ message.putHeader("MyString", "abcdX");
+ assertTrue(!filter.match(message));
+
+ // match failure with empty string
+ message.putHeader("MyString", "");
+ assertTrue(!filter.match(message));
+
+ // match failure due to extra characters at beginning
+ message.putHeader("MyString", "XXXabcdf");
+ assertTrue(!filter.match(message));
+
+ // match failure due to extra characters at the end
+ message.putHeader("MyString", "abcdfXXX");
+ assertTrue(!filter.match(message));
+
+ // test that the % wildcard matches the empty string
+ message.putHeader("MyString", "abdf");
+ assertTrue(filter.match(message));
+
+ }
+
+ public void testStringLikePunctuation() throws Exception
+ {
+ // test proper handling of some punctuation characters.
+ // non-trivial since the underlying implementation might
+ // (and in fact currently does) use a general-purpose
+ // RE library, which has a different notion of which
+ // characters are wildcards
+
+ // the particular tests here are motivated by the
+ // wildcards of the current underlying RE engine,
+ // GNU regexp.
+
+ filter = new FilterImpl("MyString LIKE 'a^$b'");
+ message.putHeader("MyString", "a^$b");
+ assertTrue(filter.match(message));
+
+ // this one has a double backslash since backslash
+ // is interpreted specially by Java
+ filter = new FilterImpl("MyString LIKE 'a\\dc'");
+ message.putHeader("MyString", "a\\dc");
+ assertTrue(filter.match(message));
+
+ filter = new FilterImpl("MyString LIKE 'a.c'");
+ message.putHeader("MyString", "abc");
+ assertTrue(!filter.match(message));
+
+ filter = new FilterImpl("MyString LIKE '[abc]'");
+ message.putHeader("MyString", "[abc]");
+ assertTrue(filter.match(message));
+
+ filter = new FilterImpl("MyString LIKE '[^abc]'");
+ message.putHeader("MyString", "[^abc]");
+ assertTrue(filter.match(message));
+
+ filter = new FilterImpl("MyString LIKE '[a-c]'");
+ message.putHeader("MyString", "[a-c]");
+ assertTrue(filter.match(message));
+
+ filter = new FilterImpl("MyString LIKE '[:alpha]'");
+ message.putHeader("MyString", "[:alpha]");
+ assertTrue(filter.match(message));
+
+ filter = new FilterImpl("MyString LIKE '(abc)'");
+ message.putHeader("MyString", "(abc)");
+ assertTrue(filter.match(message));
+
+ filter = new FilterImpl("MyString LIKE 'a|bc'");
+ message.putHeader("MyString", "a|bc");
+ assertTrue(filter.match(message));
+
+ filter = new FilterImpl("MyString LIKE '(abc)?'");
+ message.putHeader("MyString", "(abc)?");
+ assertTrue(filter.match(message));
+
+ filter = new FilterImpl("MyString LIKE '(abc)*'");
+ message.putHeader("MyString", "(abc)*");
+ assertTrue(filter.match(message));
+
+ filter = new FilterImpl("MyString LIKE '(abc)+'");
+ message.putHeader("MyString", "(abc)+");
+ assertTrue(filter.match(message));
+
+ filter = new FilterImpl("MyString LIKE '(abc){3}'");
+ message.putHeader("MyString", "(abc){3}");
+ assertTrue(filter.match(message));
+
+ filter = new FilterImpl("MyString LIKE '(abc){3,5}'");
+ message.putHeader("MyString", "(abc){3,5}");
+ assertTrue(filter.match(message));
+
+ filter = new FilterImpl("MyString LIKE '(abc){3,}'");
+ message.putHeader("MyString", "(abc){3,}");
+ assertTrue(filter.match(message));
+
+ filter = new FilterImpl("MyString LIKE '(?=abc)'");
+ message.putHeader("MyString", "(?=abc)");
+ assertTrue(filter.match(message));
+
+ filter = new FilterImpl("MyString LIKE '(?!abc)'");
+ message.putHeader("MyString", "(?!abc)");
+ assertTrue(filter.match(message));
+ }
+
+ // Private -----------------------------------------------------------------------------------
+
+ private void testInvalidFilter(String filterString) throws Exception
+ {
+ try
+ {
+ filter = new FilterImpl(filterString);
+
+ fail("Should throw exception");
+ }
+ catch (MessagingException e)
+ {
+ assertEquals(MessagingException.INVALID_FILTER_EXPRESSION, e.getCode());
+ }
+ }
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/FakeJournalImplTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/journal/impl/test/unit/FakeJournalImplTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/FakeJournalImplTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/FakeJournalImplTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,40 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.journal.impl;
+
+import org.jboss.messaging.core.journal.SequentialFileFactory;
+import org.jboss.messaging.tests.unit.core.journal.impl.fakes.FakeSequentialFileFactory;
+
+/**
+ *
+ * A FakeJournalImplTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class FakeJournalImplTest extends JournalImplTestUnit
+{
+ protected SequentialFileFactory getFileFactory() throws Exception
+ {
+ return new FakeSequentialFileFactory();
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/FakeSequentialFileFactoryTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/journal/impl/test/unit/FakeSequentialFileFactoryTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/FakeSequentialFileFactoryTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/FakeSequentialFileFactoryTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,46 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.journal.impl;
+
+import org.jboss.messaging.core.journal.SequentialFileFactory;
+import org.jboss.messaging.tests.unit.core.journal.impl.fakes.FakeSequentialFileFactory;
+
+/**
+ *
+ * A FakeSequentialFileFactoryTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class FakeSequentialFileFactoryTest extends SequentialFileFactoryTestBase
+{
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+ }
+
+ protected SequentialFileFactory createFactory()
+ {
+ return new FakeSequentialFileFactory();
+ }
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/JournalImplTestBase.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/journal/impl/test/unit/JournalImplTestBase.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/JournalImplTestBase.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/JournalImplTestBase.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,415 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.journal.impl;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
+
+import org.jboss.messaging.core.journal.PreparedTransactionInfo;
+import org.jboss.messaging.core.journal.RecordInfo;
+import org.jboss.messaging.core.journal.SequentialFileFactory;
+import org.jboss.messaging.core.journal.TestableJournal;
+import org.jboss.messaging.core.journal.impl.JournalImpl;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.tests.util.RandomUtil;
+import org.jboss.messaging.tests.util.UnitTestCase;
+
+/**
+ *
+ * A JournalImplTestBase
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public abstract class JournalImplTestBase extends UnitTestCase
+{
+ private static final Logger log = Logger.getLogger(JournalImplTestBase.class);
+
+ protected List<RecordInfo> records = new LinkedList<RecordInfo>();
+
+ protected TestableJournal journal;
+
+ protected int recordLength = 1024;
+
+ protected Map<Long, TransactionHolder> transactions = new LinkedHashMap<Long, TransactionHolder>();
+
+ protected int minFiles;
+
+ protected int fileSize;
+
+ protected boolean sync;
+
+ protected String filePrefix = "jbm";
+
+ protected String fileExtension = "jbm";
+
+ protected SequentialFileFactory fileFactory;
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+
+ resetFileFactory();
+
+ transactions.clear();
+
+ records.clear();
+ }
+
+ protected void tearDown() throws Exception
+ {
+ super.tearDown();
+
+ if (journal != null)
+ {
+ try
+ {
+ journal.stop();
+ }
+ catch (Exception ignore)
+ {
+ }
+ }
+
+ fileFactory = null;
+
+ journal = null;;
+ }
+
+ protected void resetFileFactory() throws Exception
+ {
+ fileFactory = getFileFactory();
+ }
+
+ protected abstract SequentialFileFactory getFileFactory() throws Exception;
+
+ // Private ---------------------------------------------------------------------------------
+
+ protected void setup(int minFreeFiles, int fileSize, boolean sync)
+ {
+ this.minFiles = minFreeFiles;
+ this.fileSize = fileSize;
+ this.sync = sync;
+ }
+
+ public void createJournal() throws Exception
+ {
+ journal =
+ new JournalImpl(fileSize, minFiles, sync, fileFactory, 1000, filePrefix, fileExtension);
+ }
+
+ protected void startJournal() throws Exception
+ {
+ journal.start();
+ }
+
+ protected void stopJournal() throws Exception
+ {
+ //We do a reclaim in here
+ journal.checkAndReclaimFiles();
+
+ journal.stop();
+ }
+
+ protected void loadAndCheck() throws Exception
+ {
+ List<RecordInfo> committedRecords = new ArrayList<RecordInfo>();
+
+ List<PreparedTransactionInfo> preparedTransactions = new ArrayList<PreparedTransactionInfo>();
+
+ journal.load(committedRecords, preparedTransactions);
+
+ checkRecordsEquivalent(records, committedRecords);
+
+ //check prepared transactions
+
+ List<PreparedTransactionInfo> prepared = new ArrayList<PreparedTransactionInfo>();
+
+ for (Map.Entry<Long, TransactionHolder> entry : transactions.entrySet())
+ {
+ if (entry.getValue().prepared)
+ {
+ PreparedTransactionInfo info = new PreparedTransactionInfo(entry.getKey());
+
+ info.records.addAll(entry.getValue().records);
+
+ info.recordsToDelete.addAll(entry.getValue().deletes);
+
+ prepared.add(info);
+ }
+ }
+
+ checkTransactionsEquivalent(prepared, preparedTransactions);
+ }
+
+ protected void load() throws Exception
+ {
+ journal.load(null, null);
+ }
+
+ protected void add(long... arguments) throws Exception
+ {
+ for (int i = 0; i < arguments.length; i++)
+ {
+ byte[] record = generateRecord(recordLength);
+
+ journal.appendAddRecord(arguments[i], record);
+
+ records.add(new RecordInfo(arguments[i], record, false));
+ }
+ }
+
+ protected void update(long... arguments) throws Exception
+ {
+ for (int i = 0; i < arguments.length; i++)
+ {
+ byte[] updateRecord = generateRecord(recordLength);
+
+ journal.appendUpdateRecord(arguments[i], updateRecord);
+
+ records.add(new RecordInfo(arguments[i], updateRecord, true));
+ }
+ }
+
+ protected void delete(long... arguments) throws Exception
+ {
+ for (int i = 0; i < arguments.length; i++)
+ {
+ journal.appendDeleteRecord(arguments[i]);
+
+ removeRecordsForID(arguments[i]);
+ }
+ }
+
+ protected void addTx(long txID, long... arguments) throws Exception
+ {
+ TransactionHolder tx = getTransaction(txID);
+
+ for (int i = 0; i < arguments.length; i++)
+ {
+ byte[] record = generateRecord(recordLength);
+
+ journal.appendAddRecordTransactional(txID, arguments[i], record);
+
+ tx.records.add(new RecordInfo(arguments[i], record, false));
+
+ }
+ }
+
+ protected void updateTx(long txID, long... arguments) throws Exception
+ {
+ TransactionHolder tx = getTransaction(txID);
+
+ for (int i = 0; i < arguments.length; i++)
+ {
+ byte[] updateRecord = generateRecord(recordLength);
+
+ journal.appendUpdateRecordTransactional(txID, arguments[i], updateRecord);
+
+ tx.records.add(new RecordInfo(arguments[i], updateRecord, true));
+ }
+ }
+
+ protected void deleteTx(long txID, long... arguments) throws Exception
+ {
+ TransactionHolder tx = getTransaction(txID);
+
+ for (int i = 0; i < arguments.length; i++)
+ {
+ journal.appendDeleteRecordTransactional(txID, arguments[i]);
+
+ tx.deletes.add(arguments[i]);
+ }
+
+ }
+
+ protected void prepare(long txID) throws Exception
+ {
+ TransactionHolder tx = transactions.get(txID);
+
+ if (tx == null)
+ {
+ throw new IllegalStateException("Cannot find tx " + txID);
+ }
+
+ if (tx.prepared)
+ {
+ throw new IllegalStateException("Transaction is already prepared");
+ }
+
+ journal.appendPrepareRecord(txID);
+
+ tx.prepared = true;
+ }
+
+ protected void commit(long txID) throws Exception
+ {
+ TransactionHolder tx = transactions.get(txID);
+
+ if (tx == null)
+ {
+ throw new IllegalStateException("Cannot find tx " + txID);
+ }
+
+ journal.appendCommitRecord(txID);
+
+ this.commitTx(txID);
+ }
+
+ protected void rollback(long txID) throws Exception
+ {
+ TransactionHolder tx = transactions.remove(txID);
+
+ if (tx == null)
+ {
+ throw new IllegalStateException("Cannot find tx " + txID);
+ }
+
+ journal.appendRollbackRecord(txID);
+ }
+
+ private void commitTx(long txID)
+ {
+ TransactionHolder tx = transactions.remove(txID);
+
+ if (tx == null)
+ {
+ throw new IllegalStateException("Cannot find tx " + txID);
+ }
+
+ records.addAll(tx.records);
+
+ for (Long l: tx.deletes)
+ {
+ removeRecordsForID(l);
+ }
+ }
+
+ protected void removeRecordsForID(long id)
+ {
+ for (ListIterator<RecordInfo> iter = records.listIterator(); iter.hasNext();)
+ {
+ RecordInfo info = iter.next();
+
+ if (info.id == id)
+ {
+ iter.remove();
+ }
+ }
+ }
+
+ protected TransactionHolder getTransaction(long txID)
+ {
+ TransactionHolder tx = transactions.get(txID);
+
+ if (tx == null)
+ {
+ tx = new TransactionHolder();
+
+ transactions.put(txID, tx);
+ }
+
+ return tx;
+ }
+
+ protected void checkTransactionsEquivalent(List<PreparedTransactionInfo> expected, List<PreparedTransactionInfo> actual)
+ {
+ assertEquals("Lists not same length", expected.size(), actual.size());
+
+ Iterator<PreparedTransactionInfo> iterExpected = expected.iterator();
+
+ Iterator<PreparedTransactionInfo> iterActual = actual.iterator();
+
+ while (iterExpected.hasNext())
+ {
+ PreparedTransactionInfo rexpected = iterExpected.next();
+
+ PreparedTransactionInfo ractual = iterActual.next();
+
+ assertEquals("ids not same", rexpected.id, ractual.id);
+
+ checkRecordsEquivalent(rexpected.records, ractual.records);
+
+ assertEquals("deletes size not same", rexpected.recordsToDelete.size(), ractual.recordsToDelete.size());
+
+ Iterator<Long> iterDeletesExpected = rexpected.recordsToDelete.iterator();
+
+ Iterator<Long> iterDeletesActual = ractual.recordsToDelete.iterator();
+
+ while (iterDeletesExpected.hasNext())
+ {
+ long lexpected = iterDeletesExpected.next();
+
+ long lactual = iterDeletesActual.next();
+
+ assertEquals("Delete ids not same", lexpected, lactual);
+ }
+ }
+ }
+
+ protected void checkRecordsEquivalent(List<RecordInfo> expected, List<RecordInfo> actual)
+ {
+ assertEquals("Lists not same length", expected.size(), actual.size());
+
+ Iterator<RecordInfo> iterExpected = expected.iterator();
+
+ Iterator<RecordInfo> iterActual = actual.iterator();
+
+ while (iterExpected.hasNext())
+ {
+ RecordInfo rexpected = iterExpected.next();
+
+ RecordInfo ractual = iterActual.next();
+
+ assertEquals("ids not same", rexpected.id, ractual.id);
+
+ assertEquals("type not same", rexpected.isUpdate, ractual.isUpdate);
+
+ assertByteArraysEquivalent(rexpected.data, ractual.data);
+ }
+ }
+
+ protected byte[] generateRecord(int length)
+ {
+ byte[] record = new byte[length];
+ for (int i = 0; i < length; i++)
+ {
+ record[i] = RandomUtil.randomByte();
+ }
+ return record;
+ }
+
+ class TransactionHolder
+ {
+ List<RecordInfo> records = new ArrayList<RecordInfo>();
+
+ List<Long> deletes = new ArrayList<Long>();
+
+ boolean prepared;
+ }
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/JournalImplTestUnit.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/journal/impl/test/unit/JournalImplTestUnit.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/JournalImplTestUnit.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/JournalImplTestUnit.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,2418 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.journal.impl;
+
+import java.util.List;
+
+import org.jboss.messaging.core.journal.RecordInfo;
+import org.jboss.messaging.core.journal.impl.JournalImpl;
+import org.jboss.messaging.core.logging.Logger;
+
+/**
+ *
+ * A JournalImplTestBase
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public abstract class JournalImplTestUnit extends JournalImplTestBase
+{
+ private static final Logger log = Logger.getLogger(JournalImplTestUnit.class);
+
+ // General tests
+ // =============
+
+ public void testState() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ try
+ {
+ load();
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+ try
+ {
+ stopJournal();
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+ startJournal();
+ try
+ {
+ startJournal();
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+ stopJournal();
+ startJournal();
+ load();
+ try
+ {
+ load();
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+ try
+ {
+ startJournal();
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+ stopJournal();
+ }
+
+ public void testParams() throws Exception
+ {
+ try
+ {
+ new JournalImpl(JournalImpl.MIN_FILE_SIZE - 1, 10, true, fileFactory, 5000, filePrefix, fileExtension);
+
+ fail("Should throw exception");
+ }
+ catch (IllegalArgumentException e)
+ {
+ //Ok
+ }
+
+ try
+ {
+ new JournalImpl(10 * 1024, 1, true, fileFactory, 5000, filePrefix, fileExtension);
+
+ fail("Should throw exception");
+ }
+ catch (IllegalArgumentException e)
+ {
+ //Ok
+ }
+
+ try
+ {
+ new JournalImpl(10 * 1024, 10, true, null, 5000, filePrefix, fileExtension);
+
+ fail("Should throw exception");
+ }
+ catch (NullPointerException e)
+ {
+ //Ok
+ }
+
+ try
+ {
+ new JournalImpl(10 * 1024, 10, true, fileFactory, JournalImpl.MIN_TASK_PERIOD - 1, filePrefix, fileExtension);
+
+ fail("Should throw exception");
+ }
+ catch (IllegalArgumentException e)
+ {
+ //Ok
+ }
+
+ try
+ {
+ new JournalImpl(10 * 1024, 10, true, fileFactory, 5000, null, fileExtension);
+
+ fail("Should throw exception");
+ }
+ catch (NullPointerException e)
+ {
+ //Ok
+ }
+
+ try
+ {
+ new JournalImpl(10 * 1024, 10, true, fileFactory, 5000, filePrefix, null);
+
+ fail("Should throw exception");
+ }
+ catch (NullPointerException e)
+ {
+ //Ok
+ }
+
+ }
+
+ public void testFilesImmediatelyAfterload() throws Exception
+ {
+ try
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files.size());
+
+ for (String file: files)
+ {
+ assertTrue(file.startsWith(filePrefix));
+ }
+
+ stopJournal();
+
+ resetFileFactory();
+
+ setup(20, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ files = fileFactory.listFiles(fileExtension);
+
+ assertEquals(20, files.size());
+
+ for (String file: files)
+ {
+ assertTrue(file.startsWith(filePrefix));
+ }
+
+ stopJournal();
+
+ fileExtension = "tim";
+
+ resetFileFactory();
+
+ setup(17, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ files = fileFactory.listFiles(fileExtension);
+
+ assertEquals(17, files.size());
+
+ for (String file: files)
+ {
+ assertTrue(file.startsWith(filePrefix));
+ }
+
+ stopJournal();
+
+ filePrefix = "echidna";
+
+ resetFileFactory();
+
+ setup(11, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ files = fileFactory.listFiles(fileExtension);
+
+ assertEquals(11, files.size());
+
+ for (String file: files)
+ {
+ assertTrue(file.startsWith(filePrefix));
+ }
+
+ stopJournal();
+ }
+ finally
+ {
+ filePrefix = "jbm";
+
+ fileExtension = "jbm";
+ }
+ }
+
+ public void testCreateFilesOnLoad() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files1.size());
+
+ stopJournal();
+
+ //Now restart with different number of minFiles - should create 10 more
+
+ setup(20, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files2 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(20, files2.size());
+
+ for (String file: files1)
+ {
+ assertTrue(files2.contains(file));
+ }
+
+ stopJournal();
+ }
+
+ public void testReduceFreeFiles() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files1.size());
+
+ stopJournal();
+
+ setup(5, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files2 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files2.size());
+
+ for (String file: files1)
+ {
+ assertTrue(files2.contains(file));
+ }
+
+ stopJournal();
+ }
+
+ public void testCheckCreateMoreFiles() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ //Fill all the files
+
+ for (int i = 0; i < 90; i++)
+ {
+ add(i);
+ }
+
+ assertEquals(9, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(90, journal.getIDMapSize());
+
+ List<String> files2 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files2.size());
+
+ for (String file: files1)
+ {
+ assertTrue(files2.contains(file));
+ }
+
+ //Now add some more
+
+ for (int i = 90; i < 95; i++)
+ {
+ add(i);
+ }
+
+ assertEquals(10, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(95, journal.getIDMapSize());
+
+ List<String> files3 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(11, files3.size());
+
+ for (String file: files1)
+ {
+ assertTrue(files3.contains(file));
+ }
+
+ //And a load more
+
+ for (int i = 95; i < 200; i++)
+ {
+ add(i);
+ }
+
+ assertEquals(22, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(200, journal.getIDMapSize());
+
+ List<String> files4 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(23, files4.size());
+
+ for (String file: files1)
+ {
+ assertTrue(files4.contains(file));
+ }
+
+ stopJournal();
+ }
+
+ public void testReclaim() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ for (int i = 0; i < 100; i++)
+ {
+ add(i);
+ }
+
+ assertEquals(11, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(100, journal.getIDMapSize());
+
+ List<String> files4 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(12, files4.size());
+
+ for (String file: files1)
+ {
+ assertTrue(files4.contains(file));
+ }
+
+ //Now delete half of them
+
+ for (int i = 0; i < 50; i++)
+ {
+ delete(i);
+ }
+
+ assertEquals(11, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(50, journal.getIDMapSize());
+
+ //Make sure the deletes aren't in the current file
+
+ for (int i = 100; i < 110; i++)
+ {
+ add(i);
+ }
+
+ assertEquals(12, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(60, journal.getIDMapSize());
+
+ journal.checkAndReclaimFiles();
+
+ //Several of them should be reclaimed - and others deleted - the total number of files should not drop below
+ //10
+
+ assertEquals(7, journal.getDataFilesCount());
+ assertEquals(2, journal.getFreeFilesCount());
+ assertEquals(60, journal.getIDMapSize());
+
+ List<String> files5 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files5.size());
+
+ //Now delete the rest
+
+ for (int i = 50; i < 110; i++)
+ {
+ delete(i);
+ }
+
+ //And fill the current file
+
+ for (int i = 110; i < 120; i++)
+ {
+ add(i);
+ delete(i);
+ }
+
+ journal.checkAndReclaimFiles();
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ List<String> files6 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files6.size());
+
+ stopJournal();
+ }
+
+ public void testReclaimAddUpdateDeleteDifferentFiles1() throws Exception
+ {
+ setup(2, 1046, true); //Make sure there is one record per file
+ createJournal();
+ startJournal();
+ load();
+
+ add(1);
+ update(1);
+ delete(1);
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files1.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ journal.checkAndReclaimFiles();
+
+ List<String> files2 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files2.size());
+
+ //1 gets deleted and 1 gets reclaimed
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(1, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ stopJournal();
+ }
+
+ public void testReclaimAddUpdateDeleteDifferentFiles2() throws Exception
+ {
+ setup(2, 1046, true); //Make sure there is one record per file
+ createJournal();
+ startJournal();
+ load();
+
+ add(1);
+ update(1);
+ add(2);
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files1.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+
+ journal.checkAndReclaimFiles();
+
+ List<String> files2 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files2.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+
+
+ stopJournal();
+ }
+
+ public void testReclaimTransactionalAddCommit() throws Exception
+ {
+ testReclaimTransactionalAdd(true);
+ }
+
+ public void testReclaimTransactionalAddRollback() throws Exception
+ {
+ testReclaimTransactionalAdd(false);
+ }
+
+ //TODO commit and rollback, also transactional deletes
+
+ private void testReclaimTransactionalAdd(boolean commit) throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ for (int i = 0; i < 100; i++)
+ {
+ addTx(1, i);
+ }
+
+ assertEquals(11, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ List<String> files2 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(12, files2.size());
+
+ for (String file: files1)
+ {
+ assertTrue(files2.contains(file));
+ }
+
+ journal.checkAndReclaimFiles();
+
+ //Make sure nothing reclaimed
+
+ assertEquals(11, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ List<String> files3 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(12, files3.size());
+
+ for (String file: files1)
+ {
+ assertTrue(files3.contains(file));
+ }
+
+ //Add a load more updates
+
+ for (int i = 100; i < 200; i++)
+ {
+ updateTx(1, i);
+ }
+
+ assertEquals(22, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ List<String> files4 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(23, files4.size());
+
+ for (String file: files1)
+ {
+ assertTrue(files4.contains(file));
+ }
+
+ journal.checkAndReclaimFiles();
+
+ //Make sure nothing reclaimed
+
+ assertEquals(22, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ List<String> files5 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(23, files5.size());
+
+ for (String file: files1)
+ {
+ assertTrue(files5.contains(file));
+ }
+
+ //Now delete them
+
+ for (int i = 0; i < 200; i++)
+ {
+ deleteTx(1, i);
+ }
+
+ assertEquals(22, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ List<String> files7 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(23, files7.size());
+
+ for (String file: files1)
+ {
+ assertTrue(files7.contains(file));
+ }
+
+ journal.checkAndReclaimFiles();
+
+ assertEquals(22, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ List<String> files8 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(23, files8.size());
+
+ for (String file: files1)
+ {
+ assertTrue(files8.contains(file));
+ }
+
+ //Commit
+
+ if (commit)
+ {
+ commit(1);
+ }
+ else
+ {
+ rollback(1);
+ }
+
+ //Add more records to make sure we get to the next file
+
+ for (int i = 200; i < 210; i++)
+ {
+ add(i);
+ }
+
+ assertEquals(23, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(10, journal.getIDMapSize());
+
+ List<String> files9 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(24, files9.size());
+
+ for (String file: files1)
+ {
+ assertTrue(files9.contains(file));
+ }
+
+ journal.checkAndReclaimFiles();
+
+ //Most Should now be reclaimed - leaving 10 left in total
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(8, journal.getFreeFilesCount());
+ assertEquals(10, journal.getIDMapSize());
+
+ List<String> files10 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files10.size());
+ }
+
+ public void testReclaimTransactionalSimple() throws Exception
+ {
+ setup(2, 1054, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(1, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ addTx(1, 1); // in file 0
+
+ deleteTx(1, 1); // in file 1
+
+ List<String> files2 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files2.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ //Make sure we move on to the next file
+
+ add(2); // in file 2
+
+ List<String> files3 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files3.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ commit(1); // in file 3
+
+ List<String> files4 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(4, files4.size());
+
+ assertEquals(3, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ //Make sure we move on to the next file
+
+ add(3); // in file 4
+
+ List<String> files5 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(5, files5.size());
+
+ assertEquals(4, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+
+ journal.checkAndReclaimFiles();
+
+ List<String> files6 = fileFactory.listFiles(fileExtension);
+
+ //Three should get deleted (files 0, 1, 3)
+
+ assertEquals(2, files6.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+
+ //Now restart
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+
+ assertEquals(2, files6.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+ }
+
+ public void testAddDeleteCommitTXIDMap1() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ addTx(1, 1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ deleteTx(1, 1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ commit(1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+ }
+
+ public void testAddCommitTXIDMap1() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ addTx(1, 1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ commit(1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+ }
+
+ public void testAddDeleteCommitTXIDMap2() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ add(1, 1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ deleteTx(1, 1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ commit(1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+ }
+
+
+ public void testAddDeleteRollbackTXIDMap1() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ addTx(1, 1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ deleteTx(1, 1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ rollback(1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+ }
+
+ public void testAddRollbackTXIDMap1() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ addTx(1, 1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ rollback(1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+ }
+
+ public void testAddDeleteRollbackTXIDMap2() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ add(1, 1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ deleteTx(1, 1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ rollback(1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+ }
+
+ public void testAddDeleteIDMap() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(10, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ add(1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ delete(1);
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(9, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ }
+
+ public void testCommitRecordsInFileReclaim() throws Exception
+ {
+ setup(2, 1054, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(1, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ addTx(1, 1);
+
+ List<String> files2 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files2.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(1, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ //Make sure we move on to the next file
+
+ commit(1);
+
+ List<String> files3 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files3.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ add(2);
+
+ //Move on to another file
+
+ List<String> files4 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files4.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+
+ journal.checkAndReclaimFiles();
+
+ //Nothing should be reclaimed
+
+ List<String> files5 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files5.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+ }
+
+
+ // file 1: add 1 tx,
+ // file 2: commit 1, add 2, delete 2
+ // file 3: add 3
+
+ public void testCommitRecordsInFileNoReclaim() throws Exception
+ {
+ setup(2, 1300, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(1, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ addTx(1, 1); // in file 0
+
+ //Make sure we move on to the next file
+
+ add(2); // in file 1
+
+ List<String> files2 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files2.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ commit(1); // in file 1
+
+ List<String> files3 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files3.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+
+ delete(2); // in file 1
+
+ List<String> files4 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files4.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ //Move on to another file
+
+ add(3); // in file 2
+
+ List<String> files5 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files5.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+
+ journal.checkAndReclaimFiles();
+
+ List<String> files6 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files6.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+
+ //Restart
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+
+ List<String> files7 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files7.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+ }
+
+ public void testRollbackRecordsInFileNoReclaim() throws Exception
+ {
+ setup(2, 1300, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(1, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ addTx(1, 1); // in file 0
+
+ //Make sure we move on to the next file
+
+ add(2); // in file 1
+
+ List<String> files2 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files2.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ rollback(1); // in file 1
+
+ List<String> files3 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files3.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ delete(2); // in file 1
+
+ List<String> files4 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files4.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ //Move on to another file
+
+ add(3); // in file 2 (current file)
+
+ List<String> files5 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files5.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ journal.checkAndReclaimFiles();
+
+ List<String> files6 = fileFactory.listFiles(fileExtension);
+
+ // files 0 and 1 should be deleted
+
+ assertEquals(2, files6.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(1, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ //Restart
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+
+ List<String> files7 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files7.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(1, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+ }
+
+ public void testPrepareNoReclaim() throws Exception
+ {
+ setup(2, 1300, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(1, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ addTx(1, 1); // in file 0
+
+ //Make sure we move on to the next file
+
+ add(2); // in file 1
+
+ List<String> files2 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files2.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ prepare(1); // in file 1
+
+ List<String> files3 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files3.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ delete(2); // in file 1
+
+ List<String> files4 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files4.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ //Move on to another file
+
+ add(3); // in file 2
+
+ List<String> files5 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files5.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ journal.checkAndReclaimFiles();
+
+ List<String> files6 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files6.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ add(4); // in file 3
+
+ List<String> files7 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(4, files7.size());
+
+ assertEquals(3, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+
+ commit(1); // in file 4
+
+ List<String> files8 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(4, files8.size());
+
+ assertEquals(3, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(3, journal.getIDMapSize());
+
+ //Restart
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+
+ }
+
+ public void testPrepareReclaim() throws Exception
+ {
+ setup(2, 1300, true);
+ createJournal();
+ startJournal();
+ load();
+
+ List<String> files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(1, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ addTx(1, 1); // in file 0
+
+ files1 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files1.size());
+
+ assertEquals(0, journal.getDataFilesCount());
+ assertEquals(1, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ //Make sure we move on to the next file
+
+ add(2); // in file 1
+
+ List<String> files2 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files2.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ prepare(1); // in file 1
+
+ List<String> files3 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files3.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ delete(2); // in file 1
+
+ List<String> files4 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(2, files4.size());
+
+ assertEquals(1, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(0, journal.getIDMapSize());
+
+ //Move on to another file
+
+ add(3); // in file 2
+
+ journal.checkAndReclaimFiles();
+
+ List<String> files5 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files5.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ journal.checkAndReclaimFiles();
+
+ List<String> files6 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files6.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(1, journal.getIDMapSize());
+
+ add(4); // in file 3
+
+ List<String> files7 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(4, files7.size());
+
+ assertEquals(3, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+
+ commit(1); // in file 3
+
+ List<String> files8 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(4, files8.size());
+
+ assertEquals(3, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(3, journal.getIDMapSize());
+
+ delete(1); // in file 3
+
+ List<String> files9 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(4, files9.size());
+
+ assertEquals(3, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+
+ journal.checkAndReclaimFiles();
+
+ List<String> files10 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(4, files10.size());
+
+ assertEquals(3, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+
+ add(5); // in file 4
+
+ List<String> files11 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(5, files11.size());
+
+ assertEquals(4, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(3, journal.getIDMapSize());
+
+ journal.checkAndReclaimFiles();
+
+ List<String> files12 = fileFactory.listFiles(fileExtension);
+
+ //File 0, and File 1 should be deleted
+
+ assertEquals(3, files12.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(3, journal.getIDMapSize());
+
+
+ //Restart
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+
+ delete(4);
+
+ List<String> files13 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files13.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(2, journal.getIDMapSize());
+
+ add(6);
+
+ List<String> files14 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(4, files14.size());
+
+ assertEquals(3, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(3, journal.getIDMapSize());
+
+ journal.checkAndReclaimFiles();
+
+ //file 3 should now be deleted
+
+ List<String> files15 = fileFactory.listFiles(fileExtension);
+
+ assertEquals(3, files15.size());
+
+ assertEquals(2, journal.getDataFilesCount());
+ assertEquals(0, journal.getFreeFilesCount());
+ assertEquals(3, journal.getIDMapSize());
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ // Non transactional tests
+ // =======================
+
+ public void testSimpleAdd() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testMultipleAdd() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1,2,3,4,5,6,7,8,9,10);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testMultipleAddNonContiguous() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1,3,5,7,10,13,56,100,102,200,201,202,203);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testSimpleAddUpdate() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1);
+ update(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testMultipleAddUpdate() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1,2,3,4,5,6,7,8,9,10);
+ update(1,2,4,7,9,10);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testMultipleAddUpdateAll() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1,2,3,4,5,6,7,8,9,10);
+ update(1,2,3,4,5,6,7,8,9,10);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testMultipleAddUpdateNonContiguous() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1,3,5,7,10,13,56,100,102,200,201,202,203);
+ add(3,7,10,13,56,100,200,202,203);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testMultipleAddUpdateAllNonContiguous() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1,3,5,7,10,13,56,100,102,200,201,202,203);
+ update(1,3,5,7,10,13,56,100,102,200,201,202,203);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testSimpleAddUpdateDelete() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1);
+ update(1);
+ delete(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testMultipleAddUpdateDelete() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1,2,3,4,5,6,7,8,9,10);
+ update(1,2,4,7,9,10);
+ delete(1,4,7,9,10);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testMultipleAddUpdateDeleteAll() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1,2,3,4,5,6,7,8,9,10);
+ update(1,2,3,4,5,6,7,8,9,10);
+ update(1,2,3,4,5,6,7,8,9,10);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testMultipleAddUpdateDeleteNonContiguous() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1,3,5,7,10,13,56,100,102,200,201,202,203);
+ add(3,7,10,13,56,100,200,202,203);
+ delete(3,10,56,100,200,203);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testMultipleAddUpdateDeleteAllNonContiguous() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1,3,5,7,10,13,56,100,102,200,201,202,203);
+ update(1,3,5,7,10,13,56,100,102,200,201,202,203);
+ delete(1,3,5,7,10,13,56,100,102,200,201,202,203);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testMultipleAddUpdateDeleteDifferentOrder() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1,3,5,7,10,13,56,100,102,200,201,202,203);
+ update(203, 202, 201, 200, 102, 100, 1, 3, 5, 7, 10, 13, 56);
+ delete(56, 13, 10, 7, 5, 3, 1, 203, 202, 201, 200, 102, 100);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testMultipleAddUpdateDeleteDifferentRecordLengths() throws Exception
+ {
+ setup(10, 2048, true);
+ createJournal();
+ startJournal();
+ load();
+
+ for (int i = 0; i < 1000; i++)
+ {
+ byte[] record = generateRecord(10 + (int)(1500 * Math.random()));
+
+ journal.appendAddRecord(i, record);
+
+ records.add(new RecordInfo(i, record, false));
+ }
+
+ for (int i = 0; i < 1000; i++)
+ {
+ byte[] record = generateRecord(10 + (int)(1024 * Math.random()));
+
+ journal.appendUpdateRecord(i, record);
+
+ records.add(new RecordInfo(i, record, true));
+ }
+
+ for (int i = 0; i < 1000; i++)
+ {
+ journal.appendDeleteRecord(i);
+
+ removeRecordsForID(i);
+ }
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ stopJournal();
+ }
+
+
+ public void testAddUpdateDeleteRestartAndContinue() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1, 2, 3);
+ update(1, 2);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ add(4, 5, 6);
+ update(5);
+ delete(3);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ add(7, 8);
+ delete(1, 2);
+ delete(4, 5, 6);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testAddUpdateDeleteTransactionalRestartAndContinue() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1, 2, 3);
+ updateTx(1, 1, 2);
+ commit(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ addTx(2, 4, 5, 6);
+ update(2, 2);
+ delete(2, 3);
+ commit(2);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ addTx(3, 7, 8);
+ deleteTx(3, 1);
+ deleteTx(3, 4, 5, 6);
+ commit(3);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testFillFileExactly() throws Exception
+ {
+ this.recordLength = 500;
+
+ int numRecords = 2;
+
+ //The real appended record size in the journal file = SIZE_BYTE + SIZE_LONG + SIZE_INT + recordLength + SIZE_BYTE
+
+ int realLength = 1 + 8 + 4 + this.recordLength + 1;
+
+ int fileSize = numRecords * realLength + 8; //8 for timestamp
+
+ setup(10, fileSize, true);
+
+ createJournal();
+ startJournal();
+ load();
+
+ add(1, 2);
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+
+ add(3, 4);
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+
+ add(4, 5, 6, 7, 8, 9, 10);
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ // Transactional tests
+ // ===================
+
+ public void testSimpleTransaction() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ addTx(1, 1);
+ updateTx(1, 1);
+ deleteTx(1, 1);
+ commit(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testTransactionDontDeleteAll() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ addTx(1, 1, 2, 3);
+ updateTx(1, 1, 2);
+ deleteTx(1, 1);
+ commit(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testTransactionDeleteAll() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ addTx(1, 1, 2, 3);
+ updateTx(1, 1, 2);
+ deleteTx(1, 1, 2, 3);
+ commit(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testTransactionUpdateFromBeforeTx() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1, 2, 3);
+ addTx(1, 4, 5, 6);
+ updateTx(1, 1, 5);
+ commit(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testTransactionDeleteFromBeforeTx() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1, 2, 3);
+ addTx(1, 4, 5, 6);
+ deleteTx(1, 1, 2, 3, 4, 5, 6);
+ commit(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testTransactionChangesNotVisibleOutsideTX() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1, 2, 3);
+ addTx(1, 4, 5, 6);
+ updateTx(1, 1, 2, 4, 5);
+ deleteTx(1, 1, 2, 3, 4, 5, 6);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testMultipleTransactionsDifferentIDs() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ addTx(1, 1, 2, 3, 4, 5, 6);
+ updateTx(1, 1, 3, 5);
+ deleteTx(1, 1, 2, 3, 4, 5, 6);
+ commit(1);
+
+ addTx(2, 11, 12, 13, 14, 15, 16);
+ updateTx(2, 11, 13, 15);
+ deleteTx(2, 11, 12, 13, 14, 15, 16);
+ commit(2);
+
+ addTx(3, 21, 22, 23, 24, 25, 26);
+ updateTx(3, 21, 23, 25);
+ deleteTx(3, 21, 22, 23, 24, 25, 26);
+ commit(3);
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testMultipleInterleavedTransactionsDifferentIDs() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ addTx(1, 1, 2, 3, 4, 5, 6);
+ addTx(3, 21, 22, 23, 24, 25, 26);
+ updateTx(1, 1, 3, 5);
+ addTx(2, 11, 12, 13, 14, 15, 16);
+ deleteTx(1, 1, 2, 3, 4, 5, 6);
+ updateTx(2, 11, 13, 15);
+ updateTx(3, 21, 23, 25);
+ deleteTx(2, 11, 12, 13, 14, 15, 16);
+ deleteTx(3, 21, 22, 23, 24, 25, 26);
+
+ commit(1);
+ commit(2);
+ commit(3);
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testMultipleInterleavedTransactionsSameIDs() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ add(1, 2, 3, 4, 5, 6, 7, 8);
+ addTx(1, 9, 10, 11, 12);
+ addTx(2, 13, 14, 15, 16, 17);
+ addTx(3, 18, 19, 20, 21, 22);
+ updateTx(1, 1, 2, 3);
+ updateTx(2, 4, 5, 6);
+ commit(2);
+ updateTx(3, 7, 8);
+ deleteTx(1, 1, 2);
+ commit(1);
+ deleteTx(3, 7, 8);
+ commit(3);
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testTransactionMixed() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1,3,5,7,10,13,56,100,102,200,201,202,203);
+ addTx(1, 675, 676, 677, 700, 703);
+ update(1,3,5,7,10,13,56,100,102,200,201,202,203);
+ updateTx(1, 677, 700);
+ delete(1,3,5,7,10,13,56,100,102,200,201,202,203);
+ deleteTx(1, 703, 675);
+ commit(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testTransactionAddDeleteDifferentOrder() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ addTx(1, 1, 2, 3, 4, 5, 6, 7, 8, 9);
+ deleteTx(1, 9, 8, 5, 3, 7, 6, 2, 1, 4);
+ commit(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testAddOutsideTXThenUpdateInsideTX() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1, 2, 3);
+ updateTx(1, 1, 2, 3);
+ commit(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testAddOutsideTXThenDeleteInsideTX() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1, 2, 3);
+ deleteTx(1, 1, 2, 3);
+ commit(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testRollback() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1, 2, 3);
+ deleteTx(1, 1, 2, 3);
+ rollback(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testRollbackMultiple() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1, 2, 3);
+ deleteTx(1, 1, 2, 3);
+ addTx(2, 4, 5, 6);
+ rollback(1);
+ rollback(2);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testIsolation1() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ addTx(1, 1, 2, 3);
+ deleteTx(1, 1, 2, 3);
+ commit(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testIsolation2() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ addTx(1, 1, 2, 3);
+ try
+ {
+ update(1);
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //Ok
+ }
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testIsolation3() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ addTx(1, 1, 2, 3);
+ try
+ {
+ delete(1);
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //Ok
+ }
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+
+ // XA tests
+ // ========
+
+ public void testXASimpleNotPrepared() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ addTx(1, 1, 2, 3, 4, 5, 6, 7, 8, 9);
+ updateTx(1, 1, 2, 3, 4, 7, 8);
+ deleteTx(1, 1, 2, 3, 4, 5);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testXASimplePrepared() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ addTx(1, 1, 2, 3, 4, 5, 6, 7, 8, 9);
+ updateTx(1, 1, 2, 3, 4, 7, 8);
+ deleteTx(1, 1, 2, 3, 4, 5);
+ prepare(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testXASimpleCommit() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ addTx(1, 1, 2, 3, 4, 5, 6, 7, 8, 9);
+ updateTx(1, 1, 2,3, 4, 7, 8);
+ deleteTx(1, 1, 2, 3, 4, 5);
+ prepare(1);
+ commit(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testXASimpleRollback() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ addTx(1, 1, 2, 3, 4, 5, 6, 7, 8, 9);
+ updateTx(1, 1, 2,3, 4, 7, 8);
+ deleteTx(1, 1, 2, 3, 4, 5);
+ prepare(1);
+ rollback(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testXAChangesNotVisibleNotPrepared() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1, 2, 3, 4, 5, 6);
+ addTx(1, 7, 8, 9, 10);
+ updateTx(1, 1, 2, 3, 7, 8, 9);
+ deleteTx(1, 1, 2, 3, 4, 5);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testXAChangesNotVisiblePrepared() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1, 2, 3, 4, 5, 6);
+ addTx(1, 7, 8, 9, 10);
+ updateTx(1, 1, 2, 3, 7, 8, 9);
+ deleteTx(1, 1, 2, 3, 4, 5);
+ prepare(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testXAChangesNotVisibleRollback() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1, 2, 3, 4, 5, 6);
+ addTx(1, 7, 8, 9, 10);
+ updateTx(1, 1, 2, 3, 7, 8, 9);
+ deleteTx(1, 1, 2, 3, 4, 5);
+ prepare(1);
+ rollback(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testXAChangesisibleCommit() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1, 2, 3, 4, 5, 6);
+ addTx(1, 7, 8, 9, 10);
+ updateTx(1, 1, 2, 3, 7, 8, 9);
+ deleteTx(1, 1, 2, 3, 4, 5);
+ prepare(1);
+ commit(1);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+ }
+
+ public void testXAMultiple() throws Exception
+ {
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+ addTx(1, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
+ addTx(2, 21, 22, 23, 24, 25, 26, 27);
+ updateTx(1, 1, 3, 6, 11, 14, 17);
+ addTx(3, 28, 29, 30, 31, 32, 33, 34, 35);
+ updateTx(3, 7, 8, 9, 10);
+ deleteTx(2, 4, 5, 6, 23, 25, 27);
+ prepare(2);
+ deleteTx(1, 1, 2, 11, 14, 15);
+ prepare(1);
+ deleteTx(3, 28, 31, 32, 9);
+ prepare(3);
+
+ commit(1);
+ rollback(2);
+ commit(3);
+ }
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/NIOSequentialFileFactoryTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/journal/impl/test/unit/NIOSequentialFileFactoryTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/NIOSequentialFileFactoryTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/NIOSequentialFileFactoryTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,56 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.journal.impl;
+
+import java.io.File;
+
+import org.jboss.messaging.core.journal.SequentialFileFactory;
+import org.jboss.messaging.core.journal.impl.NIOSequentialFileFactory;
+
+/**
+ *
+ * A NIOSequentialFileFactoryTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class NIOSequentialFileFactoryTest extends SequentialFileFactoryTestBase
+{
+ protected String journalDir = System.getProperty("user.home") + "/journal-test";
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+
+ File file = new File(journalDir);
+
+ deleteDirectory(file);
+
+ file.mkdir();
+ }
+
+ protected SequentialFileFactory createFactory()
+ {
+ return new NIOSequentialFileFactory(journalDir);
+ }
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/RealJournalImplTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/journal/impl/test/unit/RealJournalImplTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/RealJournalImplTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/RealJournalImplTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,56 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.journal.impl;
+
+import java.io.File;
+
+import org.jboss.messaging.core.journal.SequentialFileFactory;
+import org.jboss.messaging.core.journal.impl.NIOSequentialFileFactory;
+import org.jboss.messaging.core.logging.Logger;
+
+/**
+ *
+ * A RealJournalImplTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class RealJournalImplTest extends JournalImplTestUnit
+{
+ private static final Logger log = Logger.getLogger(RealJournalImplTest.class);
+
+ protected String journalDir = System.getProperty("user.home") + "/journal-test";
+
+ protected SequentialFileFactory getFileFactory() throws Exception
+ {
+ File file = new File(journalDir);
+
+ log.info("deleting directory " + journalDir);
+
+ deleteDirectory(file);
+
+ file.mkdir();
+
+ return new NIOSequentialFileFactory(journalDir);
+ }
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/ReclaimerTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/journal/impl/test/unit/ReclaimerTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/ReclaimerTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/ReclaimerTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,872 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.journal.impl;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import org.jboss.messaging.core.journal.SequentialFile;
+import org.jboss.messaging.core.journal.impl.JournalFile;
+import org.jboss.messaging.core.journal.impl.Reclaimer;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.tests.util.UnitTestCase;
+
+/**
+ *
+ * A ReclaimerTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class ReclaimerTest extends UnitTestCase
+{
+ private static final Logger log = Logger.getLogger(ReclaimerTest.class);
+
+ private JournalFile[] files;
+
+ private Reclaimer reclaimer;
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+
+ reclaimer = new Reclaimer();
+ }
+
+ public void testOneFilePosNegAll() throws Exception
+ {
+ setup(1);
+
+ setupPosNeg(0, 10, 10);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ }
+
+ public void testOneFilePosNegNotAll() throws Exception
+ {
+ setup(1);
+
+ setupPosNeg(0, 10, 7);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ }
+
+ public void testOneFilePosOnly() throws Exception
+ {
+ setup(1);
+
+ setupPosNeg(0, 10);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ }
+
+ public void testOneFileNegOnly() throws Exception
+ {
+ setup(1);
+
+ setupPosNeg(0, 0, 10);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ }
+
+
+ public void testTwoFilesPosNegAllDifferentFiles() throws Exception
+ {
+ setup(2);
+
+ setupPosNeg(0, 10);
+ setupPosNeg(1, 0, 10);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCanDelete(1);
+
+ }
+
+ public void testTwoFilesPosNegAllSameFiles() throws Exception
+ {
+ setup(2);
+
+ setupPosNeg(0, 10, 10);
+ setupPosNeg(1, 10, 0, 10);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCanDelete(1);
+
+ }
+
+ public void testTwoFilesPosNegMixedFiles() throws Exception
+ {
+ setup(2);
+
+ setupPosNeg(0, 10, 7);
+ setupPosNeg(1, 10, 3, 10);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCanDelete(1);
+ }
+
+ public void testTwoFilesPosNegAllFirstFile() throws Exception
+ {
+ setup(2);
+
+ setupPosNeg(0, 10, 10);
+ setupPosNeg(1, 10);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCantDelete(1);
+ }
+
+ public void testTwoFilesPosNegAllSecondFile() throws Exception
+ {
+ setup(2);
+
+ setupPosNeg(0, 10);
+ setupPosNeg(1, 10, 0, 10);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCanDelete(1);
+ }
+
+ public void testTwoFilesPosOnly() throws Exception
+ {
+ setup(2);
+
+ setupPosNeg(0, 10);
+ setupPosNeg(1, 10);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCantDelete(1);
+ }
+
+ public void testTwoFilesxyz() throws Exception
+ {
+ setup(2);
+
+ setupPosNeg(0, 10);
+ setupPosNeg(1, 10, 10);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCantDelete(1);
+ }
+
+ //Can-can-can
+
+ public void testThreeFiles1() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 10, 0, 0);
+ setupPosNeg(1, 10, 0, 10, 0);
+ setupPosNeg(2, 10, 0, 0, 10);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCanDelete(1);
+ assertCanDelete(2);
+ }
+
+ public void testThreeFiles2() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 7, 0, 0);
+ setupPosNeg(1, 10, 3, 5, 0);
+ setupPosNeg(2, 10, 0, 5, 10);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCanDelete(1);
+ assertCanDelete(2);
+ }
+
+ public void testThreeFiles3() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 1, 0, 0);
+ setupPosNeg(1, 10, 6, 5, 0);
+ setupPosNeg(2, 10, 3, 5, 10);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCanDelete(1);
+ assertCanDelete(2);
+ }
+
+ public void testThreeFiles3_1() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 1, 0, 0);
+ setupPosNeg(1, 10, 6, 5, 0);
+ setupPosNeg(2, 0, 3, 5, 0);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCanDelete(1);
+ assertCanDelete(2);
+ }
+
+ public void testThreeFiles3_2() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 1, 0, 0);
+ setupPosNeg(1, 0, 6, 0, 0);
+ setupPosNeg(2, 0, 3, 0, 0);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCanDelete(1);
+ assertCanDelete(2);
+ }
+
+
+
+
+ //Cant-can-can
+
+
+ public void testThreeFiles4() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 3, 0, 0);
+ setupPosNeg(1, 10, 0, 5, 0);
+ setupPosNeg(2, 10, 0, 5, 10);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCanDelete(1);
+ assertCanDelete(2);
+ }
+
+ public void testThreeFiles5() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 3, 0, 0);
+ setupPosNeg(1, 10, 0, 5, 0);
+ setupPosNeg(2, 0, 0, 5, 0);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCanDelete(1);
+ assertCanDelete(2);
+ }
+
+ public void testThreeFiles6() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 0, 0, 0);
+ setupPosNeg(1, 10, 0, 5, 0);
+ setupPosNeg(2, 0, 0, 5, 10);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCanDelete(1);
+ assertCanDelete(2);
+ }
+
+ public void testThreeFiles7() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 0, 0, 0);
+ setupPosNeg(1, 10, 0, 5, 0);
+ setupPosNeg(2, 0, 0, 5, 0);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCanDelete(1);
+ assertCanDelete(2);
+ }
+
+
+ //Cant can cant
+
+ public void testThreeFiles8() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 3, 0, 0);
+ setupPosNeg(1, 10, 0, 10, 0);
+ setupPosNeg(2, 10, 0, 0, 2);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCanDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles9() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 3, 0, 0);
+ setupPosNeg(1, 10, 0, 10, 0);
+ setupPosNeg(2, 10, 1, 0, 2);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCanDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles10() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 3, 0, 0);
+ setupPosNeg(1, 10, 0, 10, 0);
+ setupPosNeg(2, 10, 1, 0, 0);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCanDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles11() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 0, 0, 0);
+ setupPosNeg(1, 10, 0, 10, 0);
+ setupPosNeg(2, 10, 0, 0, 0);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCanDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles12() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 0, 0, 0);
+ setupPosNeg(1, 10, 0, 10, 0);
+ setupPosNeg(2, 0, 3, 0, 0);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCanDelete(1);
+ assertCantDelete(2);
+ }
+
+ //Cant-cant-cant
+
+ public void testThreeFiles13() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 3, 0, 0);
+ setupPosNeg(1, 10, 2, 3, 0);
+ setupPosNeg(2, 10, 1, 5, 7);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCantDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles14() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 3, 0, 0);
+ setupPosNeg(1, 0, 2, 0, 0);
+ setupPosNeg(2, 10, 1, 0, 7);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCantDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles15() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 3, 0, 0);
+ setupPosNeg(1, 10, 2, 3, 0);
+ setupPosNeg(2, 0, 1, 5, 0);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCantDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles16() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 3, 0, 0);
+ setupPosNeg(1, 0, 2, 0, 0);
+ setupPosNeg(2, 0, 1, 0, 0);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCantDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles17() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 3, 0, 0);
+ setupPosNeg(1, 10, 0, 3, 0);
+ setupPosNeg(2, 10, 1, 5, 7);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCantDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles18() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 3, 0, 0);
+ setupPosNeg(1, 10, 0, 3, 0);
+ setupPosNeg(2, 10, 1, 0, 7);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCantDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles19() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 3, 0, 0);
+ setupPosNeg(1, 10, 0, 3, 0);
+ setupPosNeg(2, 10, 1, 0, 0);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCantDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles20() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 3, 0, 0);
+ setupPosNeg(1, 10, 0, 0, 0);
+ setupPosNeg(2, 10, 1, 0, 0);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCantDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles21() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 0, 0, 0);
+ setupPosNeg(1, 10, 0, 0, 0);
+ setupPosNeg(2, 10, 0, 0, 0);
+
+ reclaimer.scan(files);
+
+ assertCantDelete(0);
+ assertCantDelete(1);
+ assertCantDelete(2);
+ }
+
+ // Can-can-cant
+
+ public void testThreeFiles22() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 10, 0, 0);
+ setupPosNeg(1, 10, 0, 10, 0);
+ setupPosNeg(2, 10, 0, 0, 0);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCanDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles23() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 10, 0, 0);
+ setupPosNeg(1, 10, 0, 10, 0);
+ setupPosNeg(2, 10, 3, 0, 0);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCanDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles24() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 7, 0, 0);
+ setupPosNeg(1, 10, 3, 10, 0);
+ setupPosNeg(2, 10, 3, 0, 0);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCanDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles25() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 7, 0, 0);
+ setupPosNeg(1, 0, 3, 10, 0);
+ setupPosNeg(2, 10, 3, 0, 0);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCanDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles26() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 7, 0, 0);
+ setupPosNeg(1, 0, 3, 10, 0);
+ setupPosNeg(2, 10, 0, 0, 0);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCanDelete(1);
+ assertCantDelete(2);
+ }
+
+
+ //Can-cant-cant
+
+ public void testThreeFiles27() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 10, 0, 0);
+ setupPosNeg(1, 10, 0, 0, 0);
+ setupPosNeg(2, 10, 0, 0, 0);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCantDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles28() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 10, 0, 0);
+ setupPosNeg(1, 10, 0, 3, 0);
+ setupPosNeg(2, 10, 0, 0, 5);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCantDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles29() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 10, 0, 0);
+ setupPosNeg(1, 10, 0, 3, 0);
+ setupPosNeg(2, 10, 0, 6, 5);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCantDelete(1);
+ assertCantDelete(2);
+ }
+
+ public void testThreeFiles30() throws Exception
+ {
+ setup(3);
+
+ setupPosNeg(0, 10, 10, 0, 0);
+ setupPosNeg(1, 10, 0, 3, 0);
+ setupPosNeg(2, 0, 0, 6, 0);
+
+ reclaimer.scan(files);
+
+ assertCanDelete(0);
+ assertCantDelete(1);
+ assertCantDelete(2);
+ }
+
+
+ // Private ------------------------------------------------------------------------
+
+ private void setup(int numFiles)
+ {
+ files = new JournalFile[numFiles];
+
+ for (int i = 0; i < numFiles; i++)
+ {
+ files[i] = new MockJournalFile();
+ }
+ }
+
+ private void setupPosNeg(int fileNumber, int pos, int... neg)
+ {
+ JournalFile file = files[fileNumber];
+
+ for (int i = 0; i < pos; i++)
+ {
+ file.incPosCount();
+ }
+
+ for (int i = 0; i < neg.length; i++)
+ {
+ JournalFile reclaimable2 = files[i];
+
+ for (int j = 0; j < neg[i]; j++)
+ {
+ file.incNegCount(reclaimable2);
+ }
+ }
+ }
+
+ private void assertCanDelete(int... fileNumber)
+ {
+ for (int num: fileNumber)
+ {
+ assertTrue(files[num].isCanReclaim());
+ }
+ }
+
+ private void assertCantDelete(int... fileNumber)
+ {
+ for (int num: fileNumber)
+ {
+ assertFalse(files[num].isCanReclaim());
+ }
+ }
+
+ class MockJournalFile implements JournalFile
+ {
+ private Set<Long> transactionIDs = new HashSet<Long>();
+
+ private Set<Long> transactionTerminationIDs = new HashSet<Long>();
+
+ private Set<Long> transactionPrepareIDs = new HashSet<Long>();
+
+ private Map<JournalFile, Integer> negCounts = new HashMap<JournalFile, Integer>();
+
+ private int posCount;
+
+ private boolean canDelete;
+
+ public void extendOffset(int delta)
+ {
+ }
+
+ public SequentialFile getFile()
+ {
+ return null;
+ }
+
+ public int getOffset()
+ {
+ return 0;
+ }
+
+ public long getOrderingID()
+ {
+ return 0;
+ }
+
+ public void setOffset(int offset)
+ {
+ }
+
+ public int getNegCount(final JournalFile file)
+ {
+ Integer count = negCounts.get(file);
+
+ if (count != null)
+ {
+ return count.intValue();
+ }
+ else
+ {
+ return 0;
+ }
+ }
+
+ public void incNegCount(final JournalFile file)
+ {
+ Integer count = negCounts.get(file);
+
+ int c = count == null ? 1 : count.intValue() + 1;
+
+ negCounts.put(file, c);
+ }
+
+ public int getPosCount()
+ {
+ return posCount;
+ }
+
+ public void incPosCount()
+ {
+ this.posCount++;
+ }
+
+ public void decPosCount()
+ {
+ this.posCount--;
+ }
+
+ public boolean isCanReclaim()
+ {
+ return canDelete;
+ }
+
+ public void setCanReclaim(boolean canDelete)
+ {
+ this.canDelete = canDelete;
+ }
+
+ public void addTransactionID(long id)
+ {
+ transactionIDs.add(id);
+ }
+
+ public void addTransactionPrepareID(long id)
+ {
+ transactionPrepareIDs.add(id);
+ }
+
+ public void addTransactionTerminationID(long id)
+ {
+ transactionTerminationIDs.add(id);
+ }
+
+ public boolean containsTransactionID(long id)
+ {
+ return transactionIDs.contains(id);
+ }
+
+ public boolean containsTransactionPrepareID(long id)
+ {
+ return transactionPrepareIDs.contains(id);
+ }
+
+ public boolean containsTransactionTerminationID(long id)
+ {
+ return transactionTerminationIDs.contains(id);
+ }
+
+ public Set<Long> getTranactionTerminationIDs()
+ {
+ return transactionTerminationIDs;
+ }
+
+ public Set<Long> getTransactionPrepareIDs()
+ {
+ return transactionPrepareIDs;
+ }
+
+ public Set<Long> getTransactionsIDs()
+ {
+ return transactionIDs;
+ }
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/SequentialFileFactoryTestBase.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/journal/impl/test/unit/SequentialFileFactoryTestBase.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/SequentialFileFactoryTestBase.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/SequentialFileFactoryTestBase.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,326 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.journal.impl;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import org.jboss.messaging.core.journal.SequentialFile;
+import org.jboss.messaging.core.journal.SequentialFileFactory;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.tests.util.UnitTestCase;
+
+/**
+ *
+ * A SequentialFileFactoryTestBase
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public abstract class SequentialFileFactoryTestBase extends UnitTestCase
+{
+ private static final Logger log = Logger.getLogger(SequentialFileFactoryTestBase.class);
+
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+
+ factory = createFactory();
+ }
+
+ protected abstract SequentialFileFactory createFactory();
+
+ private SequentialFileFactory factory;
+
+ public void testCreateAndListFiles() throws Exception
+ {
+ List<String> expectedFiles = new ArrayList<String>();
+
+ final int numFiles = 10;
+
+ for (int i = 0; i < numFiles; i++)
+ {
+ String fileName = UUID.randomUUID().toString() + ".jbm";
+
+ expectedFiles.add(fileName);
+
+ SequentialFile sf = factory.createSequentialFile(fileName, false);
+
+ sf.open();
+
+ assertEquals(fileName, sf.getFileName());
+ }
+
+ //Create a couple with a different extension - they shouldn't be picked up
+
+ SequentialFile sf1 = factory.createSequentialFile("different.file", false);
+ sf1.open();
+
+ SequentialFile sf2 = factory.createSequentialFile("different.cheese", false);
+ sf2.open();
+
+ List<String> fileNames = factory.listFiles("jbm");
+
+ assertEquals(expectedFiles.size(), fileNames.size());
+
+ for (String fileName: expectedFiles)
+ {
+ assertTrue(fileNames.contains(fileName));
+ }
+
+ fileNames = factory.listFiles("file");
+
+ assertEquals(1, fileNames.size());
+
+ assertTrue(fileNames.contains("different.file"));
+
+ fileNames = factory.listFiles("cheese");
+
+ assertEquals(1, fileNames.size());
+
+ assertTrue(fileNames.contains("different.cheese"));
+ }
+
+
+ public void testFill() throws Exception
+ {
+ SequentialFile sf = factory.createSequentialFile("fill.jbm", true);
+
+ sf.open();
+
+ checkFill(sf, 0, 100, (byte)'X');
+
+ checkFill(sf, 13, 300, (byte)'Y');
+
+ checkFill(sf, 0, 1, (byte)'Z');
+
+ checkFill(sf, 100, 1, (byte)'A');
+
+ checkFill(sf, 1000, 10000, (byte)'B');
+ }
+
+ public void testDelete() throws Exception
+ {
+ SequentialFile sf = factory.createSequentialFile("delete-me.jbm", true);
+
+ sf.open();
+
+ SequentialFile sf2 = factory.createSequentialFile("delete-me2.jbm", true);
+
+ sf2.open();
+
+ List<String> fileNames = factory.listFiles("jbm");
+
+ assertEquals(2, fileNames.size());
+
+ assertTrue(fileNames.contains("delete-me.jbm"));
+
+ assertTrue(fileNames.contains("delete-me2.jbm"));
+
+ sf.delete();
+
+ fileNames = factory.listFiles("jbm");
+
+ assertEquals(1, fileNames.size());
+
+ assertTrue(fileNames.contains("delete-me2.jbm"));
+
+ }
+
+ public void testWriteandRead() throws Exception
+ {
+ SequentialFile sf = factory.createSequentialFile("write.jbm", true);
+
+ sf.open();
+
+ String s1 = "aardvark";
+ byte[] bytes1 = s1.getBytes("UTF-8");
+ ByteBuffer bb1 = ByteBuffer.wrap(bytes1);
+
+ String s2 = "hippopotamus";
+ byte[] bytes2 = s2.getBytes("UTF-8");
+ ByteBuffer bb2 = ByteBuffer.wrap(bytes2);
+
+ String s3 = "echidna";
+ byte[] bytes3 = s3.getBytes("UTF-8");
+ ByteBuffer bb3 = ByteBuffer.wrap(bytes3);
+
+ int bytesWritten = sf.write(bb1, true);
+
+ assertEquals(bytes1.length, bytesWritten);
+
+ bytesWritten = sf.write(bb2, true);
+
+ assertEquals(bytes2.length, bytesWritten);
+
+ bytesWritten = sf.write(bb3, true);
+
+ assertEquals(bytes3.length, bytesWritten);
+
+ sf.position(0);
+
+ byte[] rbytes1 = new byte[bytes1.length];
+
+ byte[] rbytes2 = new byte[bytes2.length];
+
+ byte[] rbytes3 = new byte[bytes3.length];
+
+ ByteBuffer rb1 = ByteBuffer.wrap(rbytes1);
+ ByteBuffer rb2 = ByteBuffer.wrap(rbytes2);
+ ByteBuffer rb3 = ByteBuffer.wrap(rbytes3);
+
+ int bytesRead = sf.read(rb1);
+ assertEquals(rbytes1.length, bytesRead);
+ assertByteArraysEquivalent(bytes1, rbytes1);
+
+ bytesRead = sf.read(rb2);
+ assertEquals(rbytes2.length, bytesRead);
+ assertByteArraysEquivalent(bytes2, rbytes2);
+
+ bytesRead = sf.read(rb3);
+ assertEquals(rbytes3.length, bytesRead);
+ assertByteArraysEquivalent(bytes3, rbytes3);
+ }
+
+ public void testPosition() throws Exception
+ {
+ SequentialFile sf = factory.createSequentialFile("position.jbm", true);
+
+ sf.open();
+
+ String s1 = "orange";
+ byte[] bytes1 = s1.getBytes("UTF-8");
+ ByteBuffer bb1 = ByteBuffer.wrap(bytes1);
+
+ String s2 = "grapefruit";
+ byte[] bytes2 = s2.getBytes("UTF-8");
+ ByteBuffer bb2 = ByteBuffer.wrap(bytes2);
+
+ String s3 = "lemon";
+ byte[] bytes3 = s3.getBytes("UTF-8");
+ ByteBuffer bb3 = ByteBuffer.wrap(bytes3);
+
+ int bytesWritten = sf.write(bb1, true);
+
+ assertEquals(bytes1.length, bytesWritten);
+
+ bytesWritten = sf.write(bb2, true);
+
+ assertEquals(bytes2.length, bytesWritten);
+
+ bytesWritten = sf.write(bb3, true);
+
+ assertEquals(bytes3.length, bytesWritten);
+
+ byte[] rbytes1 = new byte[bytes1.length];
+
+ byte[] rbytes2 = new byte[bytes2.length];
+
+ byte[] rbytes3 = new byte[bytes3.length];
+
+ ByteBuffer rb1 = ByteBuffer.wrap(rbytes1);
+ ByteBuffer rb2 = ByteBuffer.wrap(rbytes2);
+ ByteBuffer rb3 = ByteBuffer.wrap(rbytes3);
+
+ sf.position(bytes1.length + bytes2.length);
+
+ int bytesRead = sf.read(rb3);
+ assertEquals(rbytes3.length, bytesRead);
+ assertByteArraysEquivalent(bytes3, rbytes3);
+
+ sf.position(bytes1.length);
+
+ bytesRead = sf.read(rb2);
+ assertEquals(rbytes2.length, bytesRead);
+ assertByteArraysEquivalent(bytes2, rbytes2);
+
+ sf.position(0);
+
+ bytesRead = sf.read(rb1);
+ assertEquals(rbytes1.length, bytesRead);
+ assertByteArraysEquivalent(bytes1, rbytes1);
+ }
+
+ public void testOpenClose() throws Exception
+ {
+ SequentialFile sf = factory.createSequentialFile("openclose.jbm", true);
+
+ sf.open();
+
+ String s1 = "cheesecake";
+ byte[] bytes1 = s1.getBytes("UTF-8");
+ ByteBuffer bb1 = ByteBuffer.wrap(bytes1);
+
+ int bytesWritten = sf.write(bb1, true);
+
+ assertEquals(bytes1.length, bytesWritten);
+
+ sf.close();
+
+ try
+ {
+ sf.write(bb1, true);
+
+ fail("Should throw exception");
+ }
+ catch (Exception e)
+ {
+ //OK
+ }
+
+ sf.open();
+
+ sf.write(bb1, true);
+ }
+
+ // Private ---------------------------------
+
+ private void checkFill(SequentialFile file, int pos, int size, byte fillChar) throws Exception
+ {
+ file.fill(pos, size, fillChar);
+
+ file.close();
+
+ file.open();
+
+ file.position(pos);
+
+ byte[] bytes = new byte[size];
+
+ ByteBuffer bb = ByteBuffer.wrap(bytes);
+
+ int bytesRead = file.read(bb);
+
+ assertEquals(size, bytesRead);
+
+ for (int i = 0; i < size; i++)
+ {
+ //log.info(" i is " + i);
+ assertEquals(fillChar, bytes[i]);
+ }
+
+ }
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/fakes/FakeSequentialFile.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/journal/impl/test/unit/fakes/FakeSequentialFile.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/fakes/FakeSequentialFile.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/fakes/FakeSequentialFile.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,6 @@
+package org.jboss.messaging.tests.unit.core.journal.impl.fakes;
+
+public class FakeSequentialFile
+{
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/fakes/FakeSequentialFileFactory.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/journal/impl/test/unit/fakes/FakeSequentialFileFactory.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/fakes/FakeSequentialFileFactory.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/fakes/FakeSequentialFileFactory.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,251 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.journal.impl.fakes;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.jboss.messaging.core.journal.SequentialFile;
+import org.jboss.messaging.core.journal.SequentialFileFactory;
+import org.jboss.messaging.core.logging.Logger;
+
+/**
+ *
+ * A FakeSequentialFileFactory
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class FakeSequentialFileFactory implements SequentialFileFactory
+{
+ private static final Logger log = Logger.getLogger(FakeSequentialFileFactory.class);
+
+ private Map<String, FakeSequentialFile> fileMap = new ConcurrentHashMap<String, FakeSequentialFile>();
+
+ public SequentialFile createSequentialFile(final String fileName, final boolean sync) throws Exception
+ {
+ FakeSequentialFile sf = fileMap.get(fileName);
+
+ if (sf == null)
+ {
+ sf = new FakeSequentialFile(fileName, sync);
+
+ fileMap.put(fileName, sf);
+ }
+ else
+ {
+ sf.data.position(0);
+
+ //log.info("positioning data to 0");
+ }
+
+ return sf;
+ }
+
+ public List<String> listFiles(final String extension)
+ {
+ List<String> files = new ArrayList<String>();
+
+ for (String s: fileMap.keySet())
+ {
+ if (s.endsWith("." + extension))
+ {
+ files.add(s);
+ }
+ }
+
+ return files;
+ }
+
+ public Map<String, FakeSequentialFile> getFileMap()
+ {
+ return fileMap;
+ }
+
+ public void clear()
+ {
+ fileMap.clear();
+ }
+
+ public class FakeSequentialFile implements SequentialFile
+ {
+ private volatile boolean open;
+
+ private final String fileName;
+
+ private final boolean sync;
+
+ private volatile ByteBuffer data;
+
+ public ByteBuffer getData()
+ {
+ return data;
+ }
+
+ public boolean isSync()
+ {
+ return sync;
+ }
+
+ public boolean isOpen()
+ {
+ //log.info("is open" + System.identityHashCode(this) +" open is now " + open);
+ return open;
+ }
+
+ public FakeSequentialFile(final String fileName, final boolean sync)
+ {
+ this.fileName = fileName;
+
+ this.sync = sync;
+ }
+
+ public void close() throws Exception
+ {
+ open = false;
+
+ if (data != null)
+ {
+ data.position(0);
+ }
+ }
+
+ public void delete() throws Exception
+ {
+ if (!open)
+ {
+ throw new IllegalStateException("Is closed");
+ }
+ close();
+
+ fileMap.remove(fileName);
+ }
+
+ public String getFileName()
+ {
+ if (!open)
+ {
+ throw new IllegalStateException("Is closed");
+ }
+ return fileName;
+ }
+
+ public void open() throws Exception
+ {
+ open = true;
+ }
+
+ public void fill(int pos, int size, byte fillCharacter) throws Exception
+ {
+ if (!open)
+ {
+ throw new IllegalStateException("Is closed");
+ }
+
+ checkAndResize(pos + size);
+
+ //log.info("size is " + size + " pos is " + pos);
+
+ for (int i = pos; i < size + pos; i++)
+ {
+ data.array()[i] = fillCharacter;
+
+ //log.info("Filling " + pos + " with char " + fillCharacter);
+ }
+ }
+
+ public int read(ByteBuffer bytes) throws Exception
+ {
+ if (!open)
+ {
+ throw new IllegalStateException("Is closed");
+ }
+
+ //log.info("read called " + bytes.array().length);
+
+ byte[] bytesRead = new byte[bytes.array().length];
+
+ //log.info("reading, data pos is " + data.position() + " data size is " + data.array().length);
+
+ data.get(bytesRead);
+
+ bytes.put(bytesRead);
+
+ return bytesRead.length;
+ }
+
+ public void position(int pos) throws Exception
+ {
+ if (!open)
+ {
+ throw new IllegalStateException("Is closed");
+ }
+
+ //log.info("reset called");
+
+ data.position(pos);
+ }
+
+ public int write(ByteBuffer bytes, boolean sync) throws Exception
+ {
+ if (!open)
+ {
+ throw new IllegalStateException("Is closed");
+ }
+
+ int position = data == null ? 0 : data.position();
+
+ checkAndResize(bytes.capacity() + position);
+
+ //log.info("write called, position is " + data.position() + " bytes is " + bytes.array().length);
+
+ data.put(bytes);
+
+ return bytes.array().length;
+ }
+
+ private void checkAndResize(int size)
+ {
+ int oldpos = data == null ? 0 : data.position();
+
+ if (data == null || data.array().length < size)
+ {
+ byte[] newBytes = new byte[size];
+
+ if (data != null)
+ {
+ System.arraycopy(data.array(), 0, newBytes, 0, data.array().length);
+ }
+
+ data = ByteBuffer.wrap(newBytes);
+
+ data.position(oldpos);
+ }
+ }
+
+
+ }
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/timing/FakeJournalImplTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/journal/impl/test/timing/FakeJournalImplTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/timing/FakeJournalImplTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/timing/FakeJournalImplTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,41 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.journal.impl.timing;
+
+import org.jboss.messaging.core.journal.SequentialFileFactory;
+import org.jboss.messaging.tests.unit.core.journal.impl.fakes.FakeSequentialFileFactory;
+
+/**
+ *
+ * A FakeJournalImplTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class FakeJournalImplTest extends JournalImplTestUnit
+{
+ protected SequentialFileFactory getFileFactory() throws Exception
+ {
+ return new FakeSequentialFileFactory();
+ }
+}
+
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/timing/JournalImplTestUnit.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/journal/impl/test/timing/JournalImplTestUnit.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/timing/JournalImplTestUnit.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/timing/JournalImplTestUnit.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,170 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.journal.impl.timing;
+
+import org.jboss.messaging.tests.unit.core.journal.impl.JournalImplTestBase;
+import org.jboss.messaging.core.logging.Logger;
+
+/**
+ *
+ * A RealJournalImplTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public abstract class JournalImplTestUnit extends JournalImplTestBase
+{
+ private static final Logger log = Logger.getLogger(JournalImplTestUnit.class);
+
+
+
+ public void testAddUpdateDeleteManyLargeFileSize() throws Exception
+ {
+ final int numberAdds = 10000;
+
+ final int numberUpdates = 5000;
+
+ final int numberDeletes = 3000;
+
+ long[] adds = new long[numberAdds];
+
+ for (int i = 0; i < numberAdds; i++)
+ {
+ adds[i] = i;
+ }
+
+ long[] updates = new long[numberUpdates];
+
+ for (int i = 0; i < numberUpdates; i++)
+ {
+ updates[i] = i;
+ }
+
+ long[] deletes = new long[numberDeletes];
+
+ for (int i = 0; i < numberDeletes; i++)
+ {
+ deletes[i] = i;
+ }
+
+ setup(10, 10 * 1024 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(adds);
+ update(updates);
+ delete(deletes);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+
+ }
+
+ public void testAddUpdateDeleteManySmallFileSize() throws Exception
+ {
+ final int numberAdds = 10000;
+
+ final int numberUpdates = 5000;
+
+ final int numberDeletes = 3000;
+
+ long[] adds = new long[numberAdds];
+
+ for (int i = 0; i < numberAdds; i++)
+ {
+ adds[i] = i;
+ }
+
+ long[] updates = new long[numberUpdates];
+
+ for (int i = 0; i < numberUpdates; i++)
+ {
+ updates[i] = i;
+ }
+
+ long[] deletes = new long[numberDeletes];
+
+ for (int i = 0; i < numberDeletes; i++)
+ {
+ deletes[i] = i;
+ }
+
+ setup(10, 10 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+ add(adds);
+ update(updates);
+ delete(deletes);
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+
+ }
+
+ public void testReclaimAndReload() throws Exception
+ {
+ setup(5, 10 * 1024 * 1024, true);
+ createJournal();
+ startJournal();
+ load();
+
+ journal.startReclaimer();
+
+ long start = System.currentTimeMillis();
+
+ for (int count = 0; count < 100000; count++)
+ {
+ add(count);
+
+ if (count >= 5000)
+ {
+ delete(count - 5000);
+ }
+
+ if (count % 10000 == 0)
+ {
+ log.info("Done: " + count);
+ }
+ }
+
+ long end = System.currentTimeMillis();
+
+ double rate = 1000 * ((double)100000) / (end - start);
+
+ log.info("Rate of " + rate + " adds/removes per sec");
+
+ stopJournal();
+ createJournal();
+ startJournal();
+ loadAndCheck();
+
+ assertEquals(5000, journal.getIDMapSize());
+
+ stopJournal();
+ }
+
+}
+
+
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/timing/RealJournalImplTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/journal/impl/test/timing/RealJournalImplTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/timing/RealJournalImplTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/timing/RealJournalImplTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,121 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.journal.impl.timing;
+
+import java.io.File;
+import java.util.ArrayList;
+
+import org.jboss.messaging.core.journal.Journal;
+import org.jboss.messaging.core.journal.RecordInfo;
+import org.jboss.messaging.core.journal.SequentialFileFactory;
+import org.jboss.messaging.core.journal.impl.JournalImpl;
+import org.jboss.messaging.core.journal.impl.NIOSequentialFileFactory;
+import org.jboss.messaging.core.logging.Logger;
+
+/**
+ *
+ * A RealJournalImplTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class RealJournalImplTest extends JournalImplTestUnit
+{
+ private static final Logger log = Logger.getLogger(RealJournalImplTest.class);
+
+ protected String journalDir = System.getProperty("user.home") + "/journal-test";
+
+ protected SequentialFileFactory getFileFactory() throws Exception
+ {
+ File file = new File(journalDir);
+
+ log.info("deleting directory " + journalDir);
+
+ deleteDirectory(file);
+
+ file.mkdir();
+
+ return new NIOSequentialFileFactory(journalDir);
+ }
+
+ public void testSpeedNonTransactional() throws Exception
+ {
+ Journal journal =
+ new JournalImpl(10 * 1024 * 1024, 10, true, new NIOSequentialFileFactory(journalDir),
+ 5000, "jbm-data", "jbm");
+
+ journal.start();
+
+ journal.load(new ArrayList<RecordInfo>(), null);
+
+ final int numMessages = 10000;
+
+ byte[] data = new byte[1024];
+
+ long start = System.currentTimeMillis();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ journal.appendAddRecord(i, data);
+ }
+
+ long end = System.currentTimeMillis();
+
+ double rate = 1000 * (double)numMessages / (end - start);
+
+ log.info("Rate " + rate + " records/sec");
+
+ }
+
+ public void testSpeedTransactional() throws Exception
+ {
+ Journal journal =
+ new JournalImpl(10 * 1024 * 1024, 10, true, new NIOSequentialFileFactory(journalDir),
+ 5000, "jbm-data", "jbm");
+
+ journal.start();
+
+ journal.load(new ArrayList<RecordInfo>(), null);
+
+ final int numMessages = 10000;
+
+ byte[] data = new byte[1024];
+
+ long start = System.currentTimeMillis();
+
+ int count = 0;
+ for (int i = 0; i < numMessages; i++)
+ {
+ journal.appendAddRecordTransactional(i, count++, data);
+
+ journal.appendCommitRecord(i);
+ }
+
+ long end = System.currentTimeMillis();
+
+ double rate = 1000 * (double)numMessages / (end - start);
+
+ log.info("Rate " + rate + " records/sec");
+
+ }
+}
+
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/list/impl/PriorityLinkedListTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/list/impl/test/unit/PriorityLinkedListTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/list/impl/PriorityLinkedListTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/list/impl/PriorityLinkedListTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,607 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.list.impl;
+
+import java.util.Iterator;
+import java.util.ListIterator;
+
+import org.jboss.messaging.core.list.PriorityLinkedList;
+import org.jboss.messaging.core.list.impl.PriorityLinkedListImpl;
+import org.jboss.messaging.tests.util.UnitTestCase;
+
+/**
+ * @author <a href="tim.fox at jboss.com>Tim Fox</a>
+ *
+ * $Id$
+ */
+public class PriorityLinkedListTest extends UnitTestCase
+{
+ protected PriorityLinkedList<Wibble> list;
+
+ protected Wibble a;
+ protected Wibble b;
+ protected Wibble c;
+ protected Wibble d;
+ protected Wibble e;
+ protected Wibble f;
+ protected Wibble g;
+ protected Wibble h;
+ protected Wibble i;
+ protected Wibble j;
+ protected Wibble k;
+ protected Wibble l;
+ protected Wibble m;
+ protected Wibble n;
+ protected Wibble o;
+ protected Wibble p;
+ protected Wibble q;
+ protected Wibble r;
+ protected Wibble s;
+ protected Wibble t;
+ protected Wibble u;
+ protected Wibble v;
+ protected Wibble w;
+ protected Wibble x;
+ protected Wibble y;
+ protected Wibble z;
+
+ public void setUp() throws Exception
+ {
+ super.setUp();
+
+ list = new PriorityLinkedListImpl<Wibble>(10);
+
+ a = new Wibble("a");
+ b = new Wibble("b");
+ c = new Wibble("c");
+ d = new Wibble("d");
+ e = new Wibble("e");
+ f = new Wibble("f");
+ g = new Wibble("g");
+ h = new Wibble("h");
+ i = new Wibble("i");
+ j = new Wibble("j");
+ k = new Wibble("k");
+ l = new Wibble("l");
+ m = new Wibble("m");
+ n = new Wibble("n");
+ o = new Wibble("o");
+ p = new Wibble("p");
+ q = new Wibble("q");
+ r = new Wibble("r");
+ s = new Wibble("s");
+ t = new Wibble("t");
+ u = new Wibble("u");
+ v = new Wibble("v");
+ w = new Wibble("w");
+ x = new Wibble("x");
+ y = new Wibble("y");
+ z = new Wibble("z");
+ }
+
+
+ public void tearDown() throws Exception
+ {
+ super.tearDown();
+ }
+
+ public void testAddFirst() throws Exception
+ {
+ list.addFirst(a, 0);
+ list.addFirst(b, 0);
+ list.addFirst(c, 0);
+ list.addFirst(d, 0);
+ list.addFirst(e, 0);
+
+
+ assertEquals(e, list.removeFirst());
+ assertEquals(d, list.removeFirst());
+ assertEquals(c, list.removeFirst());
+ assertEquals(b, list.removeFirst());
+ assertEquals(a, list.removeFirst());
+ assertNull(list.removeFirst());
+ }
+
+ public void testAddLast() throws Exception
+ {
+ list.addLast(a, 0);
+ list.addLast(b, 0);
+ list.addLast(c, 0);
+ list.addLast(d, 0);
+ list.addLast(e, 0);
+
+ assertEquals(a, list.removeFirst());
+ assertEquals(b, list.removeFirst());
+ assertEquals(c, list.removeFirst());
+ assertEquals(d, list.removeFirst());
+ assertEquals(e, list.removeFirst());
+ assertNull(list.removeFirst());
+
+ }
+
+
+ public void testRemoveFirst() throws Exception
+ {
+ list.addLast(a, 0);
+ list.addLast(b, 1);
+ list.addLast(c, 2);
+ list.addLast(d, 3);
+ list.addLast(e, 4);
+ list.addLast(f, 5);
+ list.addLast(g, 6);
+ list.addLast(h, 7);
+ list.addLast(i, 8);
+ list.addLast(j, 9);
+
+ assertEquals(j, list.removeFirst());
+ assertEquals(i, list.removeFirst());
+ assertEquals(h, list.removeFirst());
+ assertEquals(g, list.removeFirst());
+ assertEquals(f, list.removeFirst());
+ assertEquals(e, list.removeFirst());
+ assertEquals(d, list.removeFirst());
+ assertEquals(c, list.removeFirst());
+ assertEquals(b, list.removeFirst());
+ assertEquals(a, list.removeFirst());
+
+ assertNull(list.removeFirst());
+
+ list.addLast(a, 9);
+ list.addLast(b, 8);
+ list.addLast(c, 7);
+ list.addLast(d, 6);
+ list.addLast(e, 5);
+ list.addLast(f, 4);
+ list.addLast(g, 3);
+ list.addLast(h, 2);
+ list.addLast(i, 1);
+ list.addLast(j, 0);
+
+ assertEquals(a, list.removeFirst());
+ assertEquals(b, list.removeFirst());
+ assertEquals(c, list.removeFirst());
+ assertEquals(d, list.removeFirst());
+ assertEquals(e, list.removeFirst());
+ assertEquals(f, list.removeFirst());
+ assertEquals(g, list.removeFirst());
+ assertEquals(h, list.removeFirst());
+ assertEquals(i, list.removeFirst());
+ assertEquals(j, list.removeFirst());
+
+ assertNull(list.removeFirst());
+
+ list.addLast(a, 9);
+ list.addLast(b, 0);
+ list.addLast(c, 8);
+ list.addLast(d, 1);
+ list.addLast(e, 7);
+ list.addLast(f, 2);
+ list.addLast(g, 6);
+ list.addLast(h, 3);
+ list.addLast(i, 5);
+ list.addLast(j, 4);
+
+ assertEquals(a, list.removeFirst());
+ assertEquals(c, list.removeFirst());
+ assertEquals(e, list.removeFirst());
+ assertEquals(g, list.removeFirst());
+ assertEquals(i, list.removeFirst());
+ assertEquals(j, list.removeFirst());
+ assertEquals(h, list.removeFirst());
+ assertEquals(f, list.removeFirst());
+ assertEquals(d, list.removeFirst());
+ assertEquals(b, list.removeFirst());
+
+ assertNull(list.removeFirst());
+
+ list.addLast(a, 0);
+ list.addLast(b, 3);
+ list.addLast(c, 3);
+ list.addLast(d, 3);
+ list.addLast(e, 6);
+ list.addLast(f, 6);
+ list.addLast(g, 6);
+ list.addLast(h, 9);
+ list.addLast(i, 9);
+ list.addLast(j, 9);
+
+ assertEquals(h, list.removeFirst());
+ assertEquals(i, list.removeFirst());
+ assertEquals(j, list.removeFirst());
+ assertEquals(e, list.removeFirst());
+ assertEquals(f, list.removeFirst());
+ assertEquals(g, list.removeFirst());
+ assertEquals(b, list.removeFirst());
+ assertEquals(c, list.removeFirst());
+ assertEquals(d, list.removeFirst());
+ assertEquals(a, list.removeFirst());
+
+ assertNull(list.removeFirst());
+
+ list.addLast(a, 5);
+ list.addLast(b, 5);
+ list.addLast(c, 5);
+ list.addLast(d, 5);
+ list.addLast(e, 5);
+ list.addLast(f, 5);
+ list.addLast(g, 5);
+ list.addLast(h, 5);
+ list.addLast(i, 5);
+ list.addLast(j, 5);
+
+ assertEquals(a, list.removeFirst());
+ assertEquals(b, list.removeFirst());
+ assertEquals(c, list.removeFirst());
+ assertEquals(d, list.removeFirst());
+ assertEquals(e, list.removeFirst());
+ assertEquals(f, list.removeFirst());
+ assertEquals(g, list.removeFirst());
+ assertEquals(h, list.removeFirst());
+ assertEquals(i, list.removeFirst());
+ assertEquals(j, list.removeFirst());
+
+ assertNull(list.removeFirst());
+
+ list.addLast(j, 5);
+ list.addLast(i, 5);
+ list.addLast(h, 5);
+ list.addLast(g, 5);
+ list.addLast(f, 5);
+ list.addLast(e, 5);
+ list.addLast(d, 5);
+ list.addLast(c, 5);
+ list.addLast(b, 5);
+ list.addLast(a, 5);
+
+ assertEquals(j, list.removeFirst());
+ assertEquals(i, list.removeFirst());
+ assertEquals(h, list.removeFirst());
+ assertEquals(g, list.removeFirst());
+ assertEquals(f, list.removeFirst());
+ assertEquals(e, list.removeFirst());
+ assertEquals(d, list.removeFirst());
+ assertEquals(c, list.removeFirst());
+ assertEquals(b, list.removeFirst());
+ assertEquals(a, list.removeFirst());
+
+ assertNull(list.removeFirst());
+
+ }
+
+ public void testGetAll() throws Exception
+ {
+ list.addLast(a, 0);
+ list.addLast(b, 3);
+ list.addLast(c, 3);
+ list.addLast(d, 3);
+ list.addLast(e, 6);
+ list.addLast(f, 6);
+ list.addLast(g, 6);
+ list.addLast(h, 9);
+ list.addLast(i, 9);
+ list.addLast(j, 9);
+
+
+ Iterator iter = list.getAll().iterator();
+ int count = 0;
+ while (iter.hasNext())
+ {
+ Object o = iter.next();
+ if (count == 0)
+ {
+ assertEquals(h, o);
+ }
+ if (count == 1)
+ {
+ assertEquals(i, o);
+ }
+ if (count == 2)
+ {
+ assertEquals(j, o);
+ }
+ if (count == 3)
+ {
+ assertEquals(e, o);
+ }
+ if (count == 4)
+ {
+ assertEquals(f, o);
+ }
+ if (count == 5)
+ {
+ assertEquals(g, o);
+ }
+ if (count == 6)
+ {
+ assertEquals(b, o);
+ }
+ if (count == 7)
+ {
+ assertEquals(c, o);
+ }
+ if (count == 8)
+ {
+ assertEquals(d, o);
+ }
+ if (count == 9)
+ {
+ assertEquals(a, o);
+ }
+ count++;
+ }
+ assertEquals(10, count);
+ }
+
+ public void testIterator()
+ {
+ list.addLast(a, 9);
+ list.addLast(b, 9);
+ list.addLast(c, 8);
+ list.addLast(d, 8);
+ list.addLast(e, 7);
+ list.addLast(f, 7);
+ list.addLast(g, 7);
+ list.addLast(h, 6);
+ list.addLast(i, 6);
+ list.addLast(j, 6);
+ list.addLast(k, 5);
+ list.addLast(l, 5);
+ list.addLast(m, 4);
+ list.addLast(n, 4);
+ list.addLast(o, 4);
+ list.addLast(p, 3);
+ list.addLast(q, 3);
+ list.addLast(r, 3);
+ list.addLast(s, 2);
+ list.addLast(t, 2);
+ list.addLast(u, 2);
+ list.addLast(v, 1);
+ list.addLast(w, 1);
+ list.addLast(x, 1);
+ list.addLast(y, 0);
+ list.addLast(z, 0);
+
+ ListIterator iter = list.iterator();
+
+ int c = 0;
+ while (iter.hasNext())
+ {
+ iter.next();
+ c++;
+ }
+ assertEquals(c, 26);
+ assertEquals(26, list.size());
+
+ iter = list.iterator();
+ assertTrue(iter.hasNext());
+ Wibble w = (Wibble)iter.next();
+ assertEquals("a", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("b", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("c", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("d", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("e", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("f", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("g", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("h", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("i", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("j", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("k", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("l", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("m", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("n", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("o", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("p", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("q", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("r", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("s", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("t", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("u", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("v", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("w", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("x", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("y", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("z", w.s);
+ assertFalse(iter.hasNext());
+
+ iter = list.iterator();
+ assertTrue(iter.hasNext());
+ w = (Wibble)iter.next();
+ assertEquals("a", w.s);
+
+ iter.remove();
+
+ assertEquals(25, list.size());
+
+ w = (Wibble)iter.next();
+ assertEquals("b", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("c", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("d", w.s);
+
+ iter.remove();
+
+ assertEquals(24, list.size());
+
+ w = (Wibble)iter.next();
+ assertEquals("e", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("f", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("g", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("h", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("i", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("j", w.s);
+
+ iter.remove();
+
+ assertEquals(23, list.size());
+
+ w = (Wibble)iter.next();
+ assertEquals("k", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("l", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("m", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("n", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("o", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("p", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("q", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("r", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("s", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("t", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("u", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("v", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("w", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("x", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("y", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("z", w.s);
+ iter.remove();
+ assertFalse(iter.hasNext());
+
+ iter = list.iterator();
+ assertTrue(iter.hasNext());
+ w = (Wibble)iter.next();
+ assertEquals("b", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("c", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("e", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("f", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("g", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("h", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("i", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("k", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("l", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("m", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("n", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("o", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("p", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("q", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("r", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("s", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("t", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("u", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("v", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("w", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("x", w.s);
+ w = (Wibble)iter.next();
+ assertEquals("y", w.s);
+ assertFalse(iter.hasNext());
+
+ }
+
+
+ public void testClear()
+ {
+ list.addLast(a, 0);
+ list.addLast(b, 3);
+ list.addLast(c, 3);
+ list.addLast(d, 3);
+ list.addLast(e, 6);
+ list.addLast(f, 6);
+ list.addLast(g, 6);
+ list.addLast(h, 9);
+ list.addLast(i, 9);
+ list.addLast(j, 9);
+
+ list.clear();
+
+ assertNull(list.removeFirst());
+
+ assertTrue(list.getAll().isEmpty());
+ }
+
+ class Wibble
+ {
+ String s;
+ Wibble(String s)
+ {
+ this.s = s;
+ }
+ public String toString()
+ {
+ return s;
+ }
+ }
+
+}
+
Property changes on: trunk/tests/src/org/jboss/messaging/tests/unit/core/list/impl/PriorityLinkedListTest.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/message/impl/MessageTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/message/impl/test/unit/MessageTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/message/impl/MessageTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/message/impl/MessageTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,388 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.message.impl;
+
+import static org.jboss.messaging.tests.util.RandomUtil.randomByte;
+import static org.jboss.messaging.tests.util.RandomUtil.randomInt;
+import static org.jboss.messaging.tests.util.RandomUtil.randomLong;
+
+import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.core.message.MessageReference;
+import org.jboss.messaging.core.message.impl.MessageImpl;
+import org.jboss.messaging.core.server.Queue;
+import org.jboss.messaging.core.server.QueueFactory;
+import org.jboss.messaging.tests.unit.core.server.impl.fakes.FakeQueueFactory;
+import org.jboss.messaging.tests.util.UnitTestCase;
+import org.jboss.messaging.util.StreamUtils;
+
+/**
+ *
+ * Tests for Message and MessageReference
+ *
+ * TODO - Test streaming and destreaming
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class MessageTest extends UnitTestCase
+{
+ private QueueFactory queueFactory = new FakeQueueFactory();
+
+ public void testCreateMessage()
+ {
+ long id = 56465;
+ int type = 655;
+ boolean reliable = true;
+ long expiration = 6712671;
+ long timestamp = 82798172;
+ byte priority = 32;
+
+ Message message = new MessageImpl(type, reliable, expiration, timestamp, priority);
+ message.setMessageID(id);
+
+ assertEquals(id, message.getMessageID());
+ assertEquals(type, message.getType());
+ assertEquals(reliable, message.isDurable());
+ assertEquals(timestamp, message.getTimestamp());
+ assertEquals(priority, message.getPriority());
+
+ reliable = false;
+
+ message = new MessageImpl(type, reliable, expiration, timestamp, priority);
+ message.setMessageID(id);
+
+ assertEquals(id, message.getMessageID());
+ assertEquals(type, message.getType());
+ assertEquals(reliable, message.isDurable());
+ assertEquals(timestamp, message.getTimestamp());
+ assertEquals(priority, message.getPriority());
+ }
+
+ public void testCreateMessageFromStorage() throws Exception
+ {
+ long id = 56465;
+ int type = 655;
+ boolean reliable = true;
+ long expiration = 6712671;
+ long timestamp = 82798172;
+ byte priority = 32;
+
+ byte[] bytes = "blah blah blah".getBytes();
+
+ Message message = new MessageImpl(id, type, reliable, expiration, timestamp, priority,
+ null, bytes);
+
+ assertEquals(id, message.getMessageID());
+ assertEquals(type, message.getType());
+ assertEquals(reliable, message.isDurable());
+ assertEquals(timestamp, message.getTimestamp());
+ assertEquals(priority, message.getPriority());
+
+ assertByteArraysEquivalent(bytes, message.getPayload());
+
+ //TODO - headers - they should really be combined into single blob
+ }
+
+ public void testCopy()
+ {
+ long id = 56465;
+ int type = 655;
+ boolean reliable = true;
+ long expiration = 6712671;
+ long timestamp = 82798172;
+ byte priority = 32;
+
+ Message message = new MessageImpl(type, reliable, expiration, timestamp, priority);
+ message.setMessageID(id);
+
+ Message message2 = message.copy();
+
+ assertEquivalent(message, message2);
+ }
+
+ public void testSetAndGetMessageID()
+ {
+ Message message = new MessageImpl();
+
+ assertEquals(0, message.getMessageID());
+
+ message = new MessageImpl(655, true, 767676, 989898, (byte)32);
+
+ assertEquals(0, message.getMessageID());
+
+ long id = 765432;
+ message.setMessageID(id);
+ assertEquals(id, message.getMessageID());
+ }
+
+ public void testSetAndGetReliable()
+ {
+ Message message = new MessageImpl();
+
+ boolean reliable = true;
+ message.setDurable(reliable);
+ assertEquals(reliable, message.isDurable());
+
+ reliable = false;
+ message.setDurable(reliable);
+ assertEquals(reliable, message.isDurable());
+ }
+
+ public void testSetAndGetExpiration()
+ {
+ Message message = new MessageImpl();
+
+ long expiration = System.currentTimeMillis() + 10000;
+ message.setExpiration(expiration);
+ assertEquals(expiration, message.getExpiration());
+ assertFalse(message.isExpired());
+ message.setExpiration(System.currentTimeMillis() - 1);
+ assertTrue(message.isExpired());
+
+ expiration = 0; //O means never expire
+ message.setExpiration(expiration);
+ assertEquals(expiration, message.getExpiration());
+ assertFalse(message.isExpired());
+ }
+
+ public void testSetAndGetTimestamp()
+ {
+ Message message = new MessageImpl();
+
+ long timestamp = System.currentTimeMillis();
+ message.setTimestamp(timestamp);
+ assertEquals(timestamp, message.getTimestamp());
+ }
+
+ public void testSetAndGetPriority()
+ {
+ Message message = new MessageImpl();
+ byte priority = 7;
+ message.setPriority(priority);
+ assertEquals(priority, message.getPriority());
+ }
+
+ public void testSetAndGetConnectionID()
+ {
+ Message message = new MessageImpl();
+
+ assertEquals(0, message.getConnectionID());
+ long connectionID = 781628;
+ message.setConnectionID(connectionID);
+ assertEquals(connectionID, message.getConnectionID());
+ }
+
+ public void testSetAndGetPayload()
+ {
+ Message message = new MessageImpl();
+
+ assertNull(message.getPayload());
+
+ byte[] bytes = "blah blah blah".getBytes();
+ message.setPayload(bytes);
+
+ assertByteArraysEquivalent(bytes, message.getPayload());
+ }
+
+ public void testHeaders()
+ {
+ Message message = new MessageImpl();
+
+ assertNotNull(message.getHeaders());
+ assertTrue(message.getHeaders().isEmpty());
+
+ String key1 = "key1";
+ String val1 = "wibble";
+ String key2 = "key2";
+ Object val2 = new Object();
+ String key3 = "key3";
+ Double val3 = new Double(123.456);
+ Long val4 = new Long(77777);
+ message.putHeader(key1, val1);
+ assertEquals(val1, message.getHeaders().get(key1));
+ assertEquals(1, message.getHeaders().size());
+ assertTrue(message.containsHeader(key1));
+ assertFalse(message.containsHeader("does not exist"));
+ message.putHeader(key2, val2);
+ assertEquals(val2, message.getHeaders().get(key2));
+ assertEquals(2, message.getHeaders().size());
+ assertTrue(message.containsHeader(key2));
+ message.putHeader(key3, val3);
+ assertEquals(val3, message.getHeaders().get(key3));
+ assertEquals(3, message.getHeaders().size());
+ assertTrue(message.containsHeader(key3));
+ message.putHeader(key3, val4);
+ assertEquals(val4, message.getHeaders().get(key3));
+ assertEquals(3, message.getHeaders().size());
+ assertEquals(val2, message.removeHeader(key2));
+ assertEquals(2, message.getHeaders().size());
+ assertFalse(message.containsHeader(key2));
+ assertNull(message.removeHeader("does not exist"));
+ assertEquals(val1, message.removeHeader(key1));
+ assertFalse(message.containsHeader(key2));
+ assertEquals(1, message.getHeaders().size());
+ assertEquals(val4, message.removeHeader(key3));
+ assertFalse(message.containsHeader(key3));
+ assertTrue(message.getHeaders().isEmpty());
+ }
+
+ public void testEquals()
+ {
+ Message message1 = new MessageImpl();
+ message1.setMessageID(1);
+
+ Message message2 = new MessageImpl();
+ message2.setMessageID(2);
+
+ Message message3 = new MessageImpl();
+ message3.setMessageID(1);
+
+ assertTrue(message1.equals(message1));
+ assertTrue(message2.equals(message2));
+ assertTrue(message3.equals(message3));
+
+ assertFalse(message1.equals(message2));
+ assertFalse(message2.equals(message1));
+
+ assertFalse(message2.equals(message3));
+ assertFalse(message3.equals(message2));
+
+ assertTrue(message1.equals(message3));
+ assertTrue(message3.equals(message1));
+
+ }
+
+ public void testHashcode()
+ {
+ long id1 = 6567575;
+ Message message1 = new MessageImpl();
+ message1.setMessageID(id1);
+
+ assertEquals((int) ((id1 >>> 32) ^ id1), message1.hashCode());
+ }
+
+ public void testMessageReference()
+ {
+ Message message = new MessageImpl();
+
+ Queue queue1 = queueFactory.createQueue(1, "queue1", null, false, true);
+ Queue queue2 = queueFactory.createQueue(2, "queue2", null, false, true);
+
+ MessageReference ref1 = message.createReference(queue1);
+ MessageReference ref2 = message.createReference(queue2);
+ MessageReference ref3 = message.createReference(queue1);
+ MessageReference ref4 = message.createReference(queue2);
+
+ assertEquals(queue1, ref1.getQueue());
+ assertEquals(queue2, ref2.getQueue());
+ assertEquals(queue1, ref3.getQueue());
+ assertEquals(queue2, ref4.getQueue());
+
+ int deliveryCount = 65235;
+ ref1.setDeliveryCount(deliveryCount);
+ assertEquals(deliveryCount, ref1.getDeliveryCount());
+
+ long scheduledDeliveryTime = 908298123;
+ ref1.setScheduledDeliveryTime(scheduledDeliveryTime);
+ assertEquals(scheduledDeliveryTime, ref1.getScheduledDeliveryTime());
+
+ Queue queue3 = queueFactory.createQueue(3, "queue3", null, false, true);
+ MessageReference ref5 = ref1.copy(queue3);
+
+ assertEquals(deliveryCount, ref5.getDeliveryCount());
+ assertEquals(scheduledDeliveryTime, ref5.getScheduledDeliveryTime());
+ assertEquals(queue3, ref5.getQueue());
+ }
+
+
+ public void testDurableReferences()
+ {
+ Message messageDurable = new MessageImpl();
+ messageDurable.setDurable(true);
+
+ Message messageNonDurable = new MessageImpl();
+ messageNonDurable.setDurable(false);
+
+ //Durable queue
+ Queue queue1 = queueFactory.createQueue(1, "queue1", null, true, false);
+
+ //Non durable queue
+ Queue queue2 = queueFactory.createQueue(2, "queue2", null, false, false);
+
+ assertEquals(0, messageDurable.getDurableRefCount());
+
+ MessageReference ref1 = messageDurable.createReference(queue1);
+
+ assertEquals(1, messageDurable.getDurableRefCount());
+
+ MessageReference ref2 = messageDurable.createReference(queue2);
+
+ assertEquals(1, messageDurable.getDurableRefCount());
+
+ assertEquals(0, messageNonDurable.getDurableRefCount());
+
+ MessageReference ref3 = messageNonDurable.createReference(queue1);
+
+ assertEquals(0, messageNonDurable.getDurableRefCount());
+
+ MessageReference ref4 = messageNonDurable.createReference(queue2);
+
+ assertEquals(0, messageNonDurable.getDurableRefCount());
+
+ MessageReference ref5 = messageDurable.createReference(queue1);
+
+ assertEquals(2, messageDurable.getDurableRefCount());
+
+ messageDurable.decrementDurableRefCount();
+
+ assertEquals(1, messageDurable.getDurableRefCount());
+
+ messageDurable.decrementDurableRefCount();
+
+ assertEquals(0, messageDurable.getDurableRefCount());
+
+ messageDurable.incrementDurableRefCount();
+
+ assertEquals(1, messageDurable.getDurableRefCount());
+ }
+
+
+ public void testMarshalling() throws Exception
+ {
+ Message msg = new MessageImpl(randomLong(), randomInt(), true, randomLong(), randomLong(), randomByte(),null, null);
+ msg.setDeliveryCount(randomInt());
+
+ byte[] bytes = StreamUtils.toBytes(msg);
+ Message unmarshalledMsg = new MessageImpl();
+ StreamUtils.fromBytes(unmarshalledMsg, bytes);
+
+ assertEquals(msg, unmarshalledMsg);
+ assertEquals("messageID", msg.getMessageID(), unmarshalledMsg.getMessageID());
+ assertEquals("type", msg.getType(), unmarshalledMsg.getType());
+ assertEquals("durable", msg.isDurable(), unmarshalledMsg.isDurable());
+ assertEquals("expiration", msg.getExpiration(), unmarshalledMsg.getExpiration());
+ assertEquals("timestamp", msg.getTimestamp(), unmarshalledMsg.getTimestamp());
+ assertEquals("priority", msg.getPriority(), unmarshalledMsg.getPriority());
+ assertEquals("deliveryCount", msg.getDeliveryCount(), unmarshalledMsg.getDeliveryCount());
+ }
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/postoffice/impl/PostOfficeTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/postoffice/impl/test/unit/PostOfficeTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/postoffice/impl/PostOfficeTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/postoffice/impl/PostOfficeTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,262 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.postoffice.impl;
+
+import java.util.List;
+import java.util.Map;
+
+import org.easymock.EasyMock;
+import org.jboss.messaging.core.filter.Filter;
+import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.core.persistence.StorageManager;
+import org.jboss.messaging.core.postoffice.Binding;
+import org.jboss.messaging.core.postoffice.PostOffice;
+import org.jboss.messaging.core.postoffice.impl.BindingImpl;
+import org.jboss.messaging.core.postoffice.impl.PostOfficeImpl;
+import org.jboss.messaging.core.server.Queue;
+import org.jboss.messaging.core.server.QueueFactory;
+import org.jboss.messaging.tests.unit.core.server.impl.fakes.FakeQueueFactory;
+import org.jboss.messaging.tests.util.UnitTestCase;
+
+/**
+ *
+ * A PostOfficeTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class PostOfficeTest extends UnitTestCase
+{
+ private QueueFactory queueFactory = new FakeQueueFactory();
+
+ public void testAddQueue() throws Exception
+ {
+ StorageManager pm = EasyMock.createStrictMock(StorageManager.class);
+
+ QueueFactory qf = EasyMock.createStrictMock(QueueFactory.class);
+
+ final int nodeID = 21;
+
+ PostOffice po = new PostOfficeImpl(nodeID, pm, qf, false);
+
+ final long id = 324;
+ final String name = "wibb22";
+ final Filter filter = new FakeFilter();
+ final boolean durable = true;
+ final boolean temporary = true;
+
+ Queue queue = queueFactory.createQueue(id, name, filter, durable, temporary);
+
+ EasyMock.expect(qf.createQueue(-1, name, filter, durable, temporary)).andReturn(queue);
+
+ final String condition = "queue.wibble";
+
+ Binding expected = new BindingImpl(nodeID, condition, queue);
+
+ pm.addBinding(EasyMock.eq(expected));
+
+ EasyMock.replay(qf);
+
+ EasyMock.replay(pm);
+
+ po.addBinding(condition, name, filter, durable, temporary);
+
+ EasyMock.verify(qf);
+
+ EasyMock.verify(pm);
+
+ EasyMock.reset(qf);
+
+ EasyMock.reset(pm);
+
+ final boolean durable2 = false;
+
+ queue = queueFactory.createQueue(id, name, filter, durable2, temporary);
+
+ EasyMock.expect(qf.createQueue(-1, name, filter, durable2, temporary)).andReturn(queue);
+
+ EasyMock.replay(qf);
+
+ EasyMock.replay(pm);
+ }
+
+ public void testRemoveQueue() throws Exception
+ {
+ StorageManager pm = EasyMock.createStrictMock(StorageManager.class);
+
+ QueueFactory qf = EasyMock.createStrictMock(QueueFactory.class);
+
+ final int nodeID = 21;
+
+ PostOffice po = new PostOfficeImpl(nodeID, pm, qf, false);
+
+ final long id = 324;
+ final String name = "wibb22";
+ final Filter filter = new FakeFilter();
+ final boolean durable = true;
+ final boolean temporary = true;
+
+ Queue queue = queueFactory.createQueue(id, name, filter, durable, temporary);
+
+ EasyMock.expect(qf.createQueue(-1, name, filter, durable, temporary)).andReturn(queue);
+
+ final String condition = "queue.wibble";
+
+ Binding expected = new BindingImpl(nodeID, condition, queue);
+
+ pm.addBinding(EasyMock.eq(expected));
+
+ pm.deleteBinding(EasyMock.eq(expected));
+
+ EasyMock.replay(qf);
+
+ EasyMock.replay(pm);
+
+ po.addBinding(condition, name, filter, durable, temporary);
+
+ po.removeBinding(name);
+
+ EasyMock.verify(qf);
+
+ EasyMock.verify(pm);
+
+ EasyMock.reset(qf);
+
+ EasyMock.reset(pm);
+
+ final boolean durable2 = false;
+
+ queue = queueFactory.createQueue(id, name, filter, durable2, temporary);
+
+ EasyMock.expect(qf.createQueue(-1, name, filter, durable2, temporary)).andReturn(queue);
+
+ EasyMock.replay(qf);
+
+ EasyMock.replay(pm);
+
+ po.addBinding(condition, name, filter, durable2, temporary);
+
+ po.removeBinding(name);
+
+ EasyMock.verify(qf);
+
+ EasyMock.verify(pm);
+ }
+
+ public void testAddRemoveMultipleWithDifferentConditions() throws Exception
+ {
+ StorageManager pm = EasyMock.createStrictMock(StorageManager.class);
+
+ QueueFactory qf = new FakeQueueFactory();
+
+ final int nodeID = 21;
+
+ PostOffice po = new PostOfficeImpl(nodeID, pm, qf, false);
+
+ final String condition1 = "queue.wibble";
+
+ po.addBinding(condition1, "queue1", null, false, false);
+ Map<String, List<Binding>> mappings = po.getMappings();
+ assertEquals(1, mappings.size());
+
+ po.addBinding(condition1, "queue2", null, false, false);
+ mappings = po.getMappings();
+ assertEquals(1, mappings.size());
+
+ po.addBinding(condition1, "queue3", null, false, false);
+ mappings = po.getMappings();
+ assertEquals(1, mappings.size());
+
+ List<Binding> bindings = mappings.get(condition1);
+ assertNotNull(bindings);
+ assertEquals(3, bindings.size());
+
+ Binding binding1 = bindings.get(0);
+ Queue queue1 = binding1.getQueue();
+ assertEquals("queue1", queue1.getName());
+
+ Binding binding2 = bindings.get(1);
+ Queue queue2 = binding2.getQueue();
+ assertEquals("queue2", queue2.getName());
+
+ Binding binding3 = bindings.get(2);
+ Queue queue3 = binding3.getQueue();
+ assertEquals("queue3", queue3.getName());
+
+ final String condition2 = "queue.wibble2";
+
+ po.addBinding(condition2, "queue4", null, false, false);
+ mappings = po.getMappings();
+ assertEquals(2, mappings.size());
+
+ po.addBinding(condition2, "queue5", null, false, false);
+ mappings = po.getMappings();
+ assertEquals(2, mappings.size());
+
+ final String condition3 = "topic.wibblexyz";
+
+ po.addBinding(condition3, "queue6", null, false, false);
+ mappings = po.getMappings();
+ assertEquals(3, mappings.size());
+
+ po.removeBinding("queue6");
+ mappings = po.getMappings();
+ assertEquals(2, mappings.size());
+
+ po.removeBinding("queue4");
+ mappings = po.getMappings();
+ assertEquals(2, mappings.size());
+
+ po.removeBinding("queue5");
+ mappings = po.getMappings();
+ assertEquals(1, mappings.size());
+
+ po.removeBinding("queue1");
+ mappings = po.getMappings();
+ assertEquals(1, mappings.size());
+
+ po.removeBinding("queue2");
+ mappings = po.getMappings();
+ assertEquals(1, mappings.size());
+
+ po.removeBinding("queue3");
+ mappings = po.getMappings();
+ assertEquals(0, mappings.size());
+ }
+
+
+
+
+ class FakeFilter implements Filter
+ {
+ public String getFilterString()
+ {
+ return "aardvark";
+ }
+
+ public boolean match(Message message)
+ {
+ return true;
+ }
+
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/ConnectorRegistryTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/test/unit/ConnectorRegistryTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/ConnectorRegistryTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/ConnectorRegistryTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,195 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.unit.core.remoting;
+
+import static org.jboss.messaging.core.remoting.TransportType.INVM;
+import static org.jboss.messaging.core.remoting.TransportType.TCP;
+import static org.jboss.messaging.tests.integration.core.remoting.mina.TestSupport.PORT;
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.config.Configuration;
+import org.jboss.messaging.core.remoting.ConnectorRegistry;
+import org.jboss.messaging.core.remoting.NIOConnector;
+import org.jboss.messaging.core.remoting.PacketDispatcher;
+import org.jboss.messaging.tests.unit.core.remoting.impl.ConfigurationHelper;
+import org.jboss.messaging.core.remoting.impl.ConnectorRegistryImpl;
+import org.jboss.messaging.core.remoting.impl.PacketDispatcherImpl;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class ConnectorRegistryTest extends TestCase
+{
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ private ConnectorRegistry registry;
+ private PacketDispatcher dispatcher;
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ registry = new ConnectorRegistryImpl();
+ dispatcher = new PacketDispatcherImpl(null);
+ assertEquals(0, registry.getRegisteredConfigurationSize());
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ assertEquals(0, registry.getRegisteredConfigurationSize());
+ registry = null;
+ }
+
+ public void testConfigurationRegistration() throws Exception
+ {
+ Configuration config = ConfigurationHelper.newConfiguration(TCP, "localhost", PORT);
+
+ assertTrue(registry.register(config, dispatcher));
+ assertFalse(registry.register(config, dispatcher));
+
+ assertTrue(registry.unregister(config));
+ assertFalse(registry.unregister(config));
+
+ assertTrue(registry.register(config, dispatcher));
+ assertTrue(registry.unregister(config));
+ }
+
+ public void testRegistrationForTwoConfigurations() throws Exception
+ {
+ Configuration config_1 = ConfigurationHelper.newConfiguration(TCP, "localhost", PORT);
+ Configuration config_2 = ConfigurationHelper.newConfiguration(TCP, "localhost", PORT + 1);
+ PacketDispatcher dispatcher_1 = new PacketDispatcherImpl(null);
+ PacketDispatcher dispatcher_2 = new PacketDispatcherImpl(null);
+
+ assertTrue(registry.register(config_1, dispatcher_1));
+ assertTrue(registry.register(config_2, dispatcher_2));
+
+ assertTrue(registry.unregister(config_1));
+ assertTrue(registry.unregister(config_2));
+ }
+
+ public void testINVMConnectorFromTCPConfiguration() throws Exception
+ {
+ Configuration config = ConfigurationHelper.newConfiguration(TCP, "localhost", PORT);
+
+ // config is registered -> client and server are in the same vm
+ assertTrue(registry.register(config, dispatcher));
+
+ NIOConnector connector = registry.getConnector(config, dispatcher);
+
+ assertTrue(connector.getServerURI().startsWith(INVM.toString()));
+
+ assertTrue(registry.unregister(config));
+
+ assertNotNull(registry.removeConnector(config));
+ }
+
+
+ public void testTCPConnectorFromTCPConfiguration() throws Exception
+ {
+ Configuration config = ConfigurationHelper.newConfiguration(TCP, "localhost", PORT);
+
+ // config is not registered -> client and server are not in the same vm
+
+ NIOConnector connector = registry.getConnector(config, dispatcher);
+
+ assertNotNull(connector);
+ assertEquals(config.getURI(), connector.getServerURI());
+
+ assertNotNull(registry.removeConnector(config));
+ }
+
+ public void testConnectorCount() throws Exception
+ {
+ Configuration config = ConfigurationHelper.newConfiguration(TCP, "localhost", PORT);
+ assertEquals(0, registry.getConnectorCount(config));
+
+ NIOConnector connector1 = registry.getConnector(config, dispatcher);
+ assertEquals(1, registry.getConnectorCount(config));
+
+ NIOConnector connector2 = registry.getConnector(config, dispatcher);
+ assertEquals(2, registry.getConnectorCount(config));
+
+ assertSame(connector1, connector2);
+
+ assertNull(registry.removeConnector(config));
+ assertEquals(1, registry.getConnectorCount(config));
+
+ NIOConnector connector3 = registry.getConnector(config, dispatcher);
+ assertEquals(2, registry.getConnectorCount(config));
+
+ assertSame(connector1, connector3);
+
+ assertNull(registry.removeConnector(config));
+ assertNotNull(registry.removeConnector(config));
+ assertEquals(0, registry.getConnectorCount(config));
+ }
+
+ public void testConnectorCount_2() throws Exception
+ {
+ Configuration config1 = ConfigurationHelper.newConfiguration(TCP, "localhost", PORT);
+ Configuration config2 = ConfigurationHelper.newConfiguration(TCP, "127.0.0.1", PORT);
+
+ assertNotSame(config1, config2);
+
+ assertEquals(0, registry.getConnectorCount(config1));
+ assertEquals(0, registry.getConnectorCount(config2));
+
+ NIOConnector connector1 = registry.getConnector(config1, dispatcher);
+ assertEquals(1, registry.getConnectorCount(config1));
+
+ NIOConnector connector2 = registry.getConnector(config2, dispatcher);
+ assertEquals(1, registry.getConnectorCount(config2));
+
+ assertNotSame(connector1, connector2);
+
+ assertNotNull(registry.removeConnector(config1));
+ assertNotNull(registry.removeConnector(config2));
+ }
+
+ /**
+ * Check that 2 configuration which are similar (but not the same object) will
+ * return the same NIOConnector
+ */
+ public void testConfigurationEquality() throws Exception
+ {
+ Configuration config1 = ConfigurationHelper.newConfiguration(TCP, "localhost", PORT);
+ Configuration config2 = ConfigurationHelper.newConfiguration(TCP, "localhost", PORT);
+
+ assertNotSame(config1, config2);
+
+ NIOConnector connector1 = registry.getConnector(config1, dispatcher);
+ assertEquals(1, registry.getConnectorCount(config1));
+
+ NIOConnector connector2 = registry.getConnector(config2, dispatcher);
+ assertEquals(2, registry.getConnectorCount(config2));
+
+ assertSame(connector1, connector2);
+
+ assertNull(registry.removeConnector(config1));
+ assertNotNull(registry.removeConnector(config2));
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/PacketDispatcherTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/test/unit/PacketDispatcherTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/PacketDispatcherTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/PacketDispatcherTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,144 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.unit.core.remoting;
+
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.expectLastCall;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
+import static org.jboss.messaging.tests.util.RandomUtil.randomLong;
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.remoting.PacketHandler;
+import org.jboss.messaging.core.remoting.PacketHandlerRegistrationListener;
+import org.jboss.messaging.core.remoting.PacketSender;
+import org.jboss.messaging.core.remoting.impl.PacketDispatcherImpl;
+import org.jboss.messaging.core.remoting.impl.wireformat.TextPacket;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class PacketDispatcherTest extends TestCase
+{
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ PacketDispatcherImpl dispatcher;
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ // TestCase overrides --------------------------------------------
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ dispatcher = new PacketDispatcherImpl(null);
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ dispatcher = null;
+ }
+
+ public void testUnregisterAnUnregisteredHandlerReturnsNull() throws Exception
+ {
+ PacketHandler handler = createMock(PacketHandler.class);
+ long id = randomLong();
+
+ replay(handler);
+
+ dispatcher.unregister(id);
+ assertNull(dispatcher.getHandler(id));
+
+ verify(handler);
+ }
+
+ public void testRegisterAndUnregisterValidHandler() throws Exception
+ {
+ PacketHandler handler = createMock(PacketHandler.class);
+ long id = randomLong();
+ expect(handler.getID()).andReturn(id).anyTimes();
+
+ replay(handler);
+
+ dispatcher.register(handler);
+
+ PacketHandler registeredHandler = dispatcher.getHandler(id);
+ assertSame(handler, registeredHandler);
+
+ dispatcher.unregister(id);
+ assertNull(dispatcher.getHandler(id));
+
+ verify(handler);
+ }
+
+ public void testDispatchPacketWithRegisteredHandler() throws Exception
+ {
+ PacketHandler handler = createMock(PacketHandler.class);
+ PacketSender sender = createMock(PacketSender.class);
+
+ TextPacket packet = new TextPacket("testDispatch");
+
+ long id = randomLong();
+ expect(handler.getID()).andStubReturn(id);
+ handler.handle(packet, sender);
+ expectLastCall().once();
+
+ replay(handler, sender);
+
+ dispatcher.register(handler);
+
+ PacketHandler registeredHandler = dispatcher.getHandler(id);
+ assertSame(handler, registeredHandler);
+
+ packet.setTargetID(handler.getID());
+ dispatcher.dispatch(packet, sender);
+
+ dispatcher.unregister(id);
+ assertNull(dispatcher.getHandler(id));
+
+ verify(handler, sender);
+ }
+
+ public void testRegistrationListener() throws Exception
+ {
+ PacketHandlerRegistrationListener listener = createMock(PacketHandlerRegistrationListener.class);
+ PacketHandler handler = createMock(PacketHandler.class);
+
+ long id = randomLong();
+ expect(handler.getID()).andStubReturn(id);
+ listener.handlerRegistered(id);
+ expectLastCall().once();
+ listener.handlerUnregistered(id);
+ expectLastCall().once();
+
+ replay(handler, listener);
+
+ dispatcher.setListener(listener);
+ dispatcher.register(handler);
+ dispatcher.unregister(id);
+
+ verify(handler, listener);
+ }
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/RemotingConfigurationValidatorTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/test/unit/RemotingConfigurationValidatorTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/RemotingConfigurationValidatorTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/RemotingConfigurationValidatorTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,159 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.unit.core.remoting;
+
+import static org.jboss.messaging.core.remoting.TransportType.INVM;
+import static org.jboss.messaging.core.remoting.TransportType.TCP;
+import static org.jboss.messaging.core.remoting.impl.RemotingConfigurationValidator.validate;
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.config.Configuration;
+import org.jboss.messaging.core.config.impl.ConfigurationImpl;
+import org.jboss.messaging.tests.unit.core.remoting.impl.ConfigurationHelper;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class RemotingConfigurationValidatorTest extends TestCase
+{
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ public void testINVMConfiguration()
+ {
+ Configuration config = ConfigurationHelper.newConfiguration(INVM, "localhost", -1);
+
+ validate(config);
+ }
+
+ public void testNegativePort()
+ {
+ Configuration config = ConfigurationHelper.newConfiguration(TCP, "localhost", -1);
+
+ try
+ {
+ validate(config);
+ fail("can not set a negative port");
+ } catch (Exception e)
+ {
+ }
+ }
+
+ public void test_TcpReceiveBufferSize_to_0()
+ {
+ ConfigurationImpl config = ConfigurationHelper.newConfiguration(TCP, "localhost", 9000);
+ config.setTcpReceiveBufferSize(0);
+ try
+ {
+ validate(config);
+ fail("can not set tcp receive buffer size to 0");
+ } catch (Exception e)
+ {
+ }
+ }
+
+ public void test_TcpReceiveBufferSize_to_minusOne()
+ {
+ ConfigurationImpl config = ConfigurationHelper.newConfiguration(TCP, "localhost", 9000);
+ config.setTcpReceiveBufferSize(-1);
+ validate(config);
+ }
+
+ public void test_TcpReceiveBufferSize_to_NegativeNumber()
+ {
+ ConfigurationImpl config = ConfigurationHelper.newConfiguration(TCP, "localhost", 9000);
+ config.setTcpReceiveBufferSize(-2);
+ try
+ {
+ validate(config);
+ fail("can not set tcp receive buffer size to a negative number other than -1");
+ } catch (Exception e)
+ {
+ }
+ }
+
+ public void test_TcpSendBufferSize_to_0()
+ {
+ ConfigurationImpl config = ConfigurationHelper.newConfiguration(TCP, "localhost", 9000);
+ config.setTcpSendBufferSize(0);
+ try
+ {
+ validate(config);
+ fail("can not set tcp send buffer size to 0");
+ } catch (Exception e)
+ {
+ }
+ }
+
+ public void test_TcpSendBufferSize_to_minusOne()
+ {
+ ConfigurationImpl config = ConfigurationHelper.newConfiguration(TCP, "localhost", 9000);
+ config.setTcpSendBufferSize(-1);
+ validate(config);
+ }
+
+ public void test_TcpSendBufferSize_to_NegativeNumber()
+ {
+ ConfigurationImpl config = ConfigurationHelper.newConfiguration(TCP, "localhost", 9000);
+ config.setTcpSendBufferSize(-2);
+ try
+ {
+ validate(config);
+ fail("can not set tcp send buffer size to a negative number other than -1");
+ } catch (Exception e)
+ {
+ }
+ }
+
+ public void test_DisableINVM_With_INVMTransport()
+ {
+ ConfigurationImpl config = ConfigurationHelper.newConfiguration(INVM, "localhost", 9000);
+ config.setInvmDisabled(true);
+
+ try
+ {
+ validate(config);
+ fail("can not disable INVM when INVM transport is set");
+ } catch (Exception e)
+ {
+
+ }
+ }
+
+ public void test_EnableSSL_With_INVMTransport()
+ {
+ ConfigurationImpl config = ConfigurationHelper.newConfiguration(INVM, "localhost", 9000);
+ config.setSSLEnabled(true);
+
+ try
+ {
+ validate(config);
+ fail("can not enable SSL when INVM transport is set");
+ } catch (Exception e)
+ {
+
+ }
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/TestPacketHandler.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/test/unit/TestPacketHandler.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/TestPacketHandler.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/TestPacketHandler.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,66 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.unit.core.remoting;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.jboss.messaging.core.remoting.Packet;
+import org.jboss.messaging.core.remoting.PacketHandler;
+import org.jboss.messaging.core.remoting.PacketSender;
+import org.jboss.messaging.core.remoting.impl.wireformat.TextPacket;
+
+public class TestPacketHandler implements PacketHandler
+{
+ private final long id;
+ private final List<TextPacket> packets;
+ private CountDownLatch latch;
+
+ public TestPacketHandler(final long id)
+ {
+ this.id = id;
+ packets = new ArrayList<TextPacket>();
+ }
+
+ public long getID()
+ {
+ return id;
+ }
+
+ public boolean await(long time, TimeUnit timeUnit) throws InterruptedException
+ {
+ if (latch == null)
+ return false;
+ return latch.await(time, timeUnit);
+ }
+
+ public void expectMessage(int count)
+ {
+ this.latch = new CountDownLatch(count);
+ }
+
+ public void handle(Packet packet, PacketSender sender)
+ {
+ packets.add((TextPacket) packet);
+
+ doHandle(packet, sender);
+
+ if (latch != null)
+ latch.countDown();
+ }
+
+ protected void doHandle(Packet packet, PacketSender sender)
+ {
+ }
+
+ public List<TextPacket> getPackets()
+ {
+ return packets;
+ }
+}
\ No newline at end of file
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/ConfigurationHelper.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/ConfigurationHelper.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/ConfigurationHelper.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/ConfigurationHelper.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,36 @@
+package org.jboss.messaging.tests.unit.core.remoting.impl;
+
+import org.jboss.messaging.core.config.impl.ConfigurationImpl;
+import org.jboss.messaging.core.remoting.TransportType;
+
+public class ConfigurationHelper
+{
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ public static ConfigurationImpl newConfiguration(TransportType transport, String localhost, int port)
+ {
+ ConfigurationImpl config = new ConfigurationImpl();
+ if (transport == TransportType.INVM)
+ config.setInvmDisabled(false);
+ config.setTransport(transport);
+ config.setHost(localhost);
+ config.setPort(port);
+ return config;
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/SessionTestBase.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/SessionTestBase.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/SessionTestBase.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/SessionTestBase.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,215 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.unit.core.remoting.impl;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.jboss.messaging.tests.integration.core.remoting.mina.TestSupport.MANY_MESSAGES;
+import static org.jboss.messaging.tests.integration.core.remoting.mina.TestSupport.REQRES_TIMEOUT;
+import static org.jboss.messaging.tests.integration.core.remoting.mina.TestSupport.reverse;
+
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.config.Configuration;
+import org.jboss.messaging.core.remoting.NIOConnector;
+import org.jboss.messaging.core.remoting.NIOSession;
+import org.jboss.messaging.core.remoting.PacketDispatcher;
+import org.jboss.messaging.core.remoting.PacketSender;
+import org.jboss.messaging.tests.integration.core.remoting.mina.ReversePacketHandler;
+import org.jboss.messaging.tests.unit.core.remoting.TestPacketHandler;
+import org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl;
+import org.jboss.messaging.core.remoting.impl.wireformat.TextPacket;
+import org.jboss.messaging.core.remoting.impl.PacketDispatcherImpl;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>.
+ *
+ * @version <tt>$Revision$</tt>
+ */
+public abstract class SessionTestBase extends TestCase
+{
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ protected ReversePacketHandler serverPacketHandler;
+
+ protected PacketDispatcher serverDispatcher;
+ protected PacketDispatcher clientDispatcher;
+
+ protected NIOConnector connector;
+
+ protected NIOSession session;
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ public void testConnected() throws Exception
+ {
+ NIOConnector connector = createNIOConnector(new PacketDispatcherImpl(null));
+ NIOSession session = connector.connect();
+
+ assertTrue(session.isConnected());
+
+ assertTrue(connector.disconnect());
+ assertFalse(session.isConnected());
+
+ }
+
+ public void testWrite() throws Exception
+ {
+ serverPacketHandler.expectMessage(1);
+
+ TextPacket packet = new TextPacket("testSendOneWay");
+ packet.setTargetID(serverPacketHandler.getID());
+
+ session.write(packet);
+
+ assertTrue(serverPacketHandler.await(2, SECONDS));
+
+ List<TextPacket> messages = serverPacketHandler.getPackets();
+ assertEquals(1, messages.size());
+ String response = ((TextPacket) messages.get(0)).getText();
+ assertEquals(packet.getText(), response);
+ }
+
+ public void testWriteMany() throws Exception
+ {
+ serverPacketHandler.expectMessage(MANY_MESSAGES);
+
+ TextPacket[] packets = new TextPacket[MANY_MESSAGES];
+ for (int i = 0; i < MANY_MESSAGES; i++)
+ {
+ packets[i] = new TextPacket("testSendManyOneWay " + i);
+ packets[i].setTargetID(serverPacketHandler.getID());
+ session.write(packets[i]);
+ }
+
+ assertTrue(serverPacketHandler.await(10, SECONDS));
+
+ List<TextPacket> receivedPackets = serverPacketHandler.getPackets();
+ assertEquals(MANY_MESSAGES, receivedPackets.size());
+ for (int i = 0; i < MANY_MESSAGES; i++)
+ {
+ TextPacket receivedPacket = (TextPacket) receivedPackets.get(i);
+ assertEquals(packets[i].getText(), receivedPacket.getText());
+ }
+ }
+
+
+ public void testWriteAndBlock() throws Exception
+ {
+ TextPacket request = new TextPacket("testSendBlocking");
+ request.setTargetID(serverPacketHandler.getID());
+
+ PacketImpl receivedPacket = (PacketImpl) session.writeAndBlock(request, REQRES_TIMEOUT, SECONDS);
+
+ assertNotNull(receivedPacket);
+ assertTrue(receivedPacket instanceof TextPacket);
+ TextPacket response = (TextPacket) receivedPacket;
+ assertEquals(reverse(request.getText()), response.getText());
+ }
+
+ public void testCorrelationCounter() throws Exception
+ {
+ TextPacket request = new TextPacket("testSendBlocking");
+ request.setTargetID(serverPacketHandler.getID());
+
+ PacketImpl receivedPacket = (PacketImpl) session.writeAndBlock(request, REQRES_TIMEOUT, SECONDS);
+ long correlationID = request.getCorrelationID();
+
+ assertNotNull(receivedPacket);
+ assertEquals(request.getCorrelationID(), receivedPacket.getCorrelationID());
+
+ receivedPacket = (PacketImpl) session.writeAndBlock(request, REQRES_TIMEOUT, SECONDS);
+ assertEquals(correlationID + 1, request.getCorrelationID());
+ assertEquals(correlationID + 1, receivedPacket.getCorrelationID());
+ }
+
+
+ public void testClientHandlePacketSentByServer() throws Exception
+ {
+ TestPacketHandler clientHandler = new TestPacketHandler(generateID());
+ clientDispatcher.register(clientHandler);
+
+ serverPacketHandler.expectMessage(1);
+ clientHandler.expectMessage(1);
+
+ TextPacket packet = new TextPacket(
+ "testClientHandlePacketSentByServer from client");
+ packet.setTargetID(serverPacketHandler.getID());
+ // send a packet to create a sender when the server
+ // handles the packet
+ session.write(packet);
+
+ assertTrue(serverPacketHandler.await(2, SECONDS));
+
+ assertNotNull(serverPacketHandler.getLastSender());
+ PacketSender sender = serverPacketHandler.getLastSender();
+ TextPacket packetFromServer = new TextPacket(
+ "testClientHandlePacketSentByServer from server");
+ packetFromServer.setTargetID(clientHandler.getID());
+ sender.send(packetFromServer);
+
+ assertTrue(clientHandler.await(2, SECONDS));
+
+ List<TextPacket> packets = clientHandler.getPackets();
+ assertEquals(1, packets.size());
+ TextPacket packetReceivedByClient = (TextPacket) packets.get(0);
+ assertEquals(packetFromServer.getText(), packetReceivedByClient.getText());
+ }
+
+ // Protected -----------------------------------------------------
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ serverDispatcher = startServer();
+
+ clientDispatcher = new PacketDispatcherImpl(null);
+
+ connector = createNIOConnector(clientDispatcher);
+ session = connector.connect();
+
+ serverPacketHandler = new ReversePacketHandler(generateID());
+ serverDispatcher.register(serverPacketHandler);
+
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ serverDispatcher.unregister(serverPacketHandler.getID());
+
+ connector.disconnect();
+ stopServer();
+
+ connector = null;
+ session = null;
+ serverDispatcher = null;
+ }
+
+ protected abstract Configuration createRemotingConfiguration();
+
+ protected abstract NIOConnector createNIOConnector(PacketDispatcher dispatcher);
+
+ protected abstract PacketDispatcher startServer() throws Exception;
+
+ protected abstract void stopServer();
+
+ private AtomicLong idSequence = new AtomicLong(0);
+
+ private long generateID()
+ {
+ return idSequence.getAndIncrement();
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/invm/INVMSessionTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/invm/test/unit/INVMSessionTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/invm/INVMSessionTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/invm/INVMSessionTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,73 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.unit.core.remoting.impl.invm;
+
+import static org.jboss.messaging.core.remoting.TransportType.INVM;
+import static org.jboss.messaging.tests.integration.core.remoting.mina.TestSupport.PORT;
+
+import org.jboss.messaging.core.config.Configuration;
+import org.jboss.messaging.core.remoting.NIOConnector;
+import org.jboss.messaging.core.remoting.PacketDispatcher;
+import org.jboss.messaging.tests.unit.core.remoting.impl.ConfigurationHelper;
+import org.jboss.messaging.core.remoting.impl.PacketDispatcherImpl;
+import org.jboss.messaging.tests.unit.core.remoting.impl.SessionTestBase;
+import org.jboss.messaging.core.remoting.impl.invm.INVMConnector;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class INVMSessionTest extends SessionTestBase
+{
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ PacketDispatcher serverDispatcher = new PacketDispatcherImpl(null);
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ // ClientTestBase overrides --------------------------------------
+
+ @Override
+ protected NIOConnector createNIOConnector(PacketDispatcher dispatcher)
+ {
+ return new INVMConnector(1, dispatcher, serverDispatcher);
+ }
+
+ @Override
+ protected Configuration createRemotingConfiguration()
+ {
+ return ConfigurationHelper.newConfiguration(INVM, "localhost", PORT);
+ }
+
+ @Override
+ protected PacketDispatcher startServer() throws Exception
+ {
+ return serverDispatcher;
+ }
+
+ @Override
+ protected void stopServer()
+ {
+ serverDispatcher = null;
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/ssl/SSLSupportTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/ssl/test/unit/SSLSupportTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/ssl/SSLSupportTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/ssl/SSLSupportTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,122 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.unit.core.remoting.impl.ssl;
+
+import java.io.File;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.remoting.impl.ssl.SSLSupport;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class SSLSupportTest extends TestCase
+{
+ private String keyStorePath;
+ private String keyStorePassword;
+ private String trustStorePath;
+ private String trustStorePassword;
+
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ keyStorePath = "messaging.keystore";
+ keyStorePassword = "secureexample";
+ trustStorePath = "messaging.truststore";
+ trustStorePassword = keyStorePassword;
+ }
+
+ public void testServerContextWithRightParameters() throws Exception
+ {
+ SSLSupport.createServerContext(keyStorePath, keyStorePassword,
+ trustStorePath, trustStorePassword);
+ }
+
+ public void testServerContextWithBadKeyStorePath() throws Exception
+ {
+ try
+ {
+ SSLSupport.createServerContext("not a keystore", keyStorePassword,
+ trustStorePath, trustStorePassword);
+ fail();
+ } catch (Exception e)
+ {
+ }
+ }
+
+ public void testServerContextWithKeyStorePathAsRelativePath() throws Exception
+ {
+ // this test is dependent on a path relative to the tests directory.
+ // it will fail if launch from somewhere else (or from an IDE)
+ File currentDir = new File(System.getProperty("user.dir"));
+ if (!currentDir.getAbsolutePath().endsWith("tests"))
+ {
+ return;
+ }
+
+ SSLSupport.createServerContext("etc/messaging.keystore",
+ keyStorePassword, trustStorePath, trustStorePassword);
+ }
+
+ public void testServerContextWithBadKeyStorePassword() throws Exception
+ {
+ try
+ {
+ SSLSupport.createServerContext(keyStorePath, "bad password",
+ trustStorePath, trustStorePassword);
+ fail();
+ } catch (Exception e)
+ {
+ }
+ }
+
+ public void testServerContextWithBadTrustStorePath() throws Exception
+ {
+ try
+ {
+ SSLSupport.createServerContext(keyStorePath, keyStorePassword,
+ "not a trust store", trustStorePassword);
+ fail();
+ } catch (Exception e)
+ {
+ }
+ }
+
+ public void testServerContextWithBadTrustStorePassword() throws Exception
+ {
+ try
+ {
+ SSLSupport.createServerContext(keyStorePath, keyStorePassword,
+ trustStorePath, "bad passord");
+ fail();
+ } catch (Exception e)
+ {
+ }
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/wireformat/CodecAssert.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/wireformat/test/unit/CodecAssert.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/wireformat/CodecAssert.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/wireformat/CodecAssert.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,75 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.unit.core.remoting.impl.wireformat;
+
+import junit.framework.Assert;
+
+import org.jboss.messaging.core.transaction.impl.XidImpl;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class CodecAssert extends Assert
+{
+ // Constants -----------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ static void assertSameXids(XidImpl[] expected, XidImpl[] actual)
+ {
+ assertEquals(expected.length, actual.length);
+ for (int i = 0; i < expected.length; i++)
+ {
+ XidImpl expectedXid = expected[i];
+ XidImpl actualXid = actual[i];
+ assertEqualsByteArrays(expectedXid.getBranchQualifier(), actualXid
+ .getBranchQualifier());
+ assertEquals(expectedXid.getFormatId(), actualXid.getFormatId());
+ assertEqualsByteArrays(expectedXid.getGlobalTransactionId(), actualXid
+ .getGlobalTransactionId());
+ }
+ }
+
+ static void assertEqualsByteArrays(byte[] expected, byte[] actual)
+ {
+ assertEquals(expected.length, actual.length);
+ for (int i = 0; i < expected.length; i++)
+ {
+ assertEquals("byte at index " + i, expected[i], actual[i]);
+ }
+ }
+
+ static void assertEqualsByteArrays(int length, byte[] expected, byte[] actual)
+ {
+ // we check only for the given length (the arrays might be
+ // larger)
+ assertTrue(expected.length >= length);
+ assertTrue(actual.length >= length);
+ for (int i = 0; i < length; i++)
+ {
+ assertEquals("byte at index " + i, expected[i], actual[i]);
+ }
+ }
+
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/wireformat/PacketTypeTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/remoting/impl/wireformat/test/unit/PacketTypeTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/wireformat/PacketTypeTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/impl/wireformat/PacketTypeTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,1525 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.unit.core.remoting.impl.wireformat;
+
+import static org.jboss.messaging.core.remoting.impl.codec.AbstractPacketCodec.FALSE;
+import static org.jboss.messaging.core.remoting.impl.codec.AbstractPacketCodec.TRUE;
+import static org.jboss.messaging.core.remoting.impl.mina.BufferWrapper.NOT_NULL_STRING;
+import static org.jboss.messaging.core.remoting.impl.mina.BufferWrapper.NULL_BYTE;
+import static org.jboss.messaging.core.remoting.impl.mina.BufferWrapper.NULL_STRING;
+import static org.jboss.messaging.core.remoting.impl.mina.BufferWrapper.UTF_8_ENCODER;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.BYTES;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.CLOSE;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.CONN_CREATESESSION;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.CONN_CREATESESSION_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.CONN_START;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.CONN_STOP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.CONS_DELIVER;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.CONS_FLOWTOKEN;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.CREATECONNECTION;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.CREATECONNECTION_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.NULL;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.PING;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.PONG;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.PROD_SEND;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_ACKNOWLEDGE;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_ADD_DESTINATION;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_BINDINGQUERY;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_BINDINGQUERY_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_BROWSER_HASNEXTMESSAGE;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_BROWSER_HASNEXTMESSAGE_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_BROWSER_NEXTMESSAGE;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_BROWSER_NEXTMESSAGEBLOCK;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_BROWSER_NEXTMESSAGEBLOCK_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_BROWSER_NEXTMESSAGE_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_BROWSER_RESET;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_CANCEL;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_COMMIT;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_CREATEBROWSER;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_CREATEBROWSER_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_CREATECONSUMER;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_CREATECONSUMER_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_CREATEPRODUCER;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_CREATEPRODUCER_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_CREATEQUEUE;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_DELETE_QUEUE;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_QUEUEQUERY;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_QUEUEQUERY_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_RECOVER;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_REMOVE_DESTINATION;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_ROLLBACK;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_COMMIT;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_END;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_FORGET;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_GET_TIMEOUT;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_GET_TIMEOUT_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_INDOUBT_XIDS;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_INDOUBT_XIDS_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_JOIN;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_PREPARE;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_RESUME;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_ROLLBACK;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_SET_TIMEOUT;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_SET_TIMEOUT_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_START;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.SESS_XA_SUSPEND;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketType.TEXT;
+import static org.jboss.messaging.tests.unit.core.remoting.impl.wireformat.CodecAssert.assertEqualsByteArrays;
+import static org.jboss.messaging.tests.util.RandomUtil.randomBytes;
+import static org.jboss.messaging.tests.util.RandomUtil.randomInt;
+import static org.jboss.messaging.tests.util.RandomUtil.randomLong;
+import static org.jboss.messaging.tests.util.RandomUtil.randomString;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.transaction.xa.Xid;
+
+import org.apache.mina.common.IoBuffer;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.core.message.impl.MessageImpl;
+import org.jboss.messaging.core.remoting.Packet;
+import org.jboss.messaging.core.remoting.impl.codec.AbstractPacketCodec;
+import org.jboss.messaging.core.remoting.impl.codec.BytesPacketCodec;
+import org.jboss.messaging.core.remoting.impl.codec.ConnectionCreateSessionMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.ConnectionCreateSessionResponseMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.ConsumerDeliverMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.ConsumerFlowTokenMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.CreateConnectionMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.CreateConnectionResponseMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.PingCodec;
+import org.jboss.messaging.core.remoting.impl.codec.PongCodec;
+import org.jboss.messaging.core.remoting.impl.codec.ProducerReceiveTokensMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.ProducerSendMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.RemotingBuffer;
+import org.jboss.messaging.core.remoting.impl.codec.SessionAcknowledgeMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionAddDestinationMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionBindingQueryMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionBindingQueryResponseMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionBrowserHasNextMessageResponseMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionBrowserNextMessageBlockMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionBrowserNextMessageBlockResponseMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionBrowserNextMessageResponseMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionCancelMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionCreateBrowserMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionCreateBrowserResponseMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionCreateConsumerMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionCreateConsumerResponseMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionCreateProducerMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionCreateProducerResponseMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionCreateQueueMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionDeleteQueueMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionQueueQueryMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionQueueQueryResponseMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionRemoveDestinationMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionXACommitMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionXAEndMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionXAForgetMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionXAGetInDoubtXidsResponseMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionXAGetTimeoutResponseMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionXAJoinMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionXAPrepareMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionXAResponseMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionXAResumeMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionXARollbackMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionXASetTimeoutMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionXASetTimeoutResponseMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.SessionXAStartMessageCodec;
+import org.jboss.messaging.core.remoting.impl.codec.TextPacketCodec;
+import org.jboss.messaging.core.remoting.impl.mina.BufferWrapper;
+import org.jboss.messaging.core.remoting.impl.mina.PacketCodecFactory;
+import org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl;
+import org.jboss.messaging.core.remoting.impl.wireformat.BytesPacket;
+import org.jboss.messaging.core.remoting.impl.wireformat.ConnectionCreateSessionMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.ConnectionCreateSessionResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.ConsumerDeliverMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.ConsumerFlowTokenMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.CreateConnectionRequest;
+import org.jboss.messaging.core.remoting.impl.wireformat.CreateConnectionResponse;
+import org.jboss.messaging.core.remoting.impl.wireformat.PacketType;
+import org.jboss.messaging.core.remoting.impl.wireformat.Ping;
+import org.jboss.messaging.core.remoting.impl.wireformat.Pong;
+import org.jboss.messaging.core.remoting.impl.wireformat.ProducerReceiveTokensMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.ProducerSendMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionAcknowledgeMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionAddDestinationMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionBindingQueryMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionBindingQueryResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowserHasNextMessageResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowserNextMessageBlockMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowserNextMessageBlockResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowserNextMessageResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionCancelMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateBrowserMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateBrowserResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateConsumerMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateConsumerResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateProducerMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateProducerResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateQueueMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionDeleteQueueMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionQueueQueryMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionQueueQueryResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionRemoveDestinationMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionXACommitMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAEndMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAForgetMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAGetInDoubtXidsResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAGetTimeoutResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAJoinMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAPrepareMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAResumeMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionXARollbackMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionXASetTimeoutMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionXASetTimeoutResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAStartMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.TextPacket;
+import org.jboss.messaging.tests.util.RandomUtil;
+import org.jboss.messaging.tests.util.UnitTestCase;
+import org.jboss.messaging.util.StreamUtils;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>.
+ *
+ * FIXME - tidy up tests so test names match the actual packets
+ *
+ * @version <tt>$Revision$</tt>
+ */
+public class PacketTypeTest extends UnitTestCase
+{
+
+ // Constants -----------------------------------------------------
+
+ private static final Logger log = Logger.getLogger(PacketTypeTest.class);
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ private static ByteBuffer encode(int length, Object... args)
+ {
+ ByteBuffer buffer = ByteBuffer.allocate(length);
+ for (Object arg : args)
+ {
+ if (arg instanceof Byte)
+ buffer.put(((Byte) arg).byteValue());
+ else if (arg instanceof Boolean)
+ {
+ Boolean bool = (Boolean) arg;
+ buffer.put(bool ? TRUE : FALSE);
+ } else if (arg instanceof Integer)
+ buffer.putInt(((Integer) arg).intValue());
+ else if (arg instanceof Long)
+ buffer.putLong(((Long) arg).longValue());
+ else if (arg instanceof Float)
+ buffer.putFloat(((Float) arg).floatValue());
+ else if (arg instanceof String)
+ putNullableString((String) arg, buffer);
+ else if (arg == null)
+ putNullableString(null, buffer);
+ else if (arg instanceof byte[])
+ {
+ byte[] b = (byte[]) arg;
+ buffer.putInt(b.length);
+ buffer.put(b);
+ } else if (arg instanceof long[])
+ {
+ long[] longs = (long[]) arg;
+ for (long l : longs)
+ {
+ buffer.putLong(l);
+ }
+ } else
+ {
+ fail("no encoding defined for " + arg);
+ }
+ }
+ buffer.flip();
+ return buffer;
+ }
+
+ private static void putNullableString(String string, ByteBuffer buffer)
+ {
+ if (string == null)
+ {
+ buffer.put(NULL_STRING);
+ } else
+ {
+ buffer.put(NOT_NULL_STRING);
+ UTF_8_ENCODER.reset();
+ UTF_8_ENCODER.encode(CharBuffer.wrap(string), buffer, true);
+ buffer.put(NULL_BYTE);
+ }
+ }
+
+ private static void checkHeader(SimpleRemotingBuffer buffer,
+ PacketImpl packet) throws Exception
+ {
+ assertEquals(buffer.get(), packet.getType().byteValue());
+
+ long correlationID = buffer.getLong();
+ long targetID = buffer.getLong();
+ long executorID = buffer.getLong();
+ boolean oneWay = buffer.getBoolean();
+
+ assertEquals(packet.getCorrelationID(), correlationID);
+ assertEquals(packet.getTargetID(), targetID);
+ assertEquals(packet.getExecutorID(), executorID);
+ assertEquals(oneWay, packet.isOneWay());
+ }
+
+ private static void checkBodyIsEmpty(RemotingBuffer buffer)
+ {
+ assertEquals(0, buffer.getInt());
+ // check the buffer has been wholly read
+ assertEquals(0, buffer.remaining());
+ }
+
+ private static void checkBody(RemotingBuffer buffer, Object... bodyObjects)
+ {
+ byte[] actualBody = new byte[buffer.getInt()];
+ buffer.get(actualBody);
+ ByteBuffer expectedBody = encode(actualBody.length, bodyObjects);
+ CodecAssert.assertEqualsByteArrays(expectedBody.array(), actualBody);
+ // check the buffer has been wholly read
+ assertEquals(0, buffer.remaining());
+ }
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ public void testNullPacket() throws Exception
+ {
+ PacketImpl packet = new PacketImpl(NULL);
+ packet.setCorrelationID(randomLong());
+ packet.setTargetID(randomLong());
+ packet.setExecutorID(randomLong());
+
+ AbstractPacketCodec<Packet> codec = PacketCodecFactory
+ .createCodecForEmptyPacket(NULL);
+ SimpleRemotingBuffer buffer = encode(packet, codec);
+ checkHeader(buffer, packet);
+ checkBodyIsEmpty(buffer);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertEquals(NULL, decodedPacket.getType());
+ assertEquals(packet.getCorrelationID(), decodedPacket.getCorrelationID());
+ assertEquals(packet.getTargetID(), decodedPacket.getTargetID());
+ }
+
+ public void testPing() throws Exception
+ {
+ Ping ping = new Ping(randomLong());
+ AbstractPacketCodec<Ping> codec = new PingCodec();
+
+ SimpleRemotingBuffer buffer = encode(ping, codec);
+ checkHeader(buffer, ping);
+ checkBody(buffer, ping.getSessionID());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof Ping);
+ Ping decodedPing = (Ping) decodedPacket;
+ assertEquals(PING, decodedPing.getType());
+ assertEquals(ping.getSessionID(), decodedPing.getSessionID());
+ }
+
+ public void testPong() throws Exception
+ {
+ Pong pong = new Pong(randomLong(), true);
+ AbstractPacketCodec<Pong> codec = new PongCodec();
+
+ SimpleRemotingBuffer buffer = encode(pong, codec);
+ checkHeader(buffer, pong);
+ checkBody(buffer, pong.getSessionID(), pong.isSessionFailed());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof Pong);
+ Pong decodedPong = (Pong) decodedPacket;
+ assertEquals(PONG, decodedPong.getType());
+ assertEquals(pong.getSessionID(), decodedPong.getSessionID());
+ assertEquals(pong.isSessionFailed(), decodedPong.isSessionFailed());
+ }
+
+ public void testTextPacket() throws Exception
+ {
+ TextPacket packet = new TextPacket("testTextPacket");
+ AbstractPacketCodec<TextPacket> codec = new TextPacketCodec();
+
+ SimpleRemotingBuffer buffer = encode(packet, codec);
+ checkHeader(buffer, packet);
+ checkBody(buffer, packet.getText());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof TextPacket);
+ TextPacket p = (TextPacket) decodedPacket;
+
+ assertEquals(TEXT, p.getType());
+ assertEquals(packet.getText(), p.getText());
+ }
+
+ public void testBytesPacket() throws Exception
+ {
+ BytesPacket packet = new BytesPacket(randomBytes());
+
+ AbstractPacketCodec codec = new BytesPacketCodec();
+ SimpleRemotingBuffer buffer = encode(packet, codec);
+ checkHeader(buffer, packet);
+ checkBody(buffer, packet.getBytes());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof BytesPacket);
+ BytesPacket p = (BytesPacket) decodedPacket;
+
+ assertEquals(BYTES, p.getType());
+ CodecAssert.assertEqualsByteArrays(packet.getBytes(), p.getBytes());
+ }
+
+ public void testCreateConnectionRequest() throws Exception
+ {
+ int version = randomInt();
+ long remotingSessionID = randomLong();
+ String clientVMID = randomString();
+ String username = null;
+ String password = null;
+
+ CreateConnectionRequest request = new CreateConnectionRequest(version,
+ remotingSessionID, clientVMID, username, password);
+
+ AbstractPacketCodec<CreateConnectionRequest> codec = new CreateConnectionMessageCodec();
+ SimpleRemotingBuffer buffer = encode(request, codec);
+ checkHeader(buffer, request);
+ checkBody(buffer, version, remotingSessionID, clientVMID, username, password);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof CreateConnectionRequest);
+ CreateConnectionRequest decodedRequest = (CreateConnectionRequest) decodedPacket;
+
+ assertEquals(CREATECONNECTION, decodedPacket.getType());
+ assertEquals(request.getVersion(), decodedRequest.getVersion());
+ assertEquals(request.getRemotingSessionID(), decodedRequest
+ .getRemotingSessionID());
+ assertEquals(request.getClientVMID(), decodedRequest.getClientVMID());
+ assertEquals(request.getUsername(), decodedRequest.getUsername());
+ assertEquals(request.getPassword(), decodedRequest.getPassword());
+ }
+
+ public void testCreateConnectionResponse() throws Exception
+ {
+ CreateConnectionResponse response = new CreateConnectionResponse(randomLong());
+
+ AbstractPacketCodec<CreateConnectionResponse> codec = new CreateConnectionResponseMessageCodec();
+ SimpleRemotingBuffer buffer = encode(response, codec);
+ checkHeader(buffer, response);
+ checkBody(buffer, response.getConnectionTargetID());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof CreateConnectionResponse);
+ CreateConnectionResponse decodedResponse = (CreateConnectionResponse) decodedPacket;
+ assertEquals(CREATECONNECTION_RESP, decodedResponse.getType());
+ assertEquals(response.getConnectionTargetID(), decodedResponse.getConnectionTargetID());
+ }
+
+ public void testCreateSessionRequest() throws Exception
+ {
+ //TODO test this more thoroughly
+
+ ConnectionCreateSessionMessage request = new ConnectionCreateSessionMessage(true, true, true);
+
+ AbstractPacketCodec codec = new ConnectionCreateSessionMessageCodec();
+ SimpleRemotingBuffer buffer = encode(request, codec);
+ checkHeader(buffer, request);
+ checkBody(buffer, request.isXA(), request.isAutoCommitSends(), request.isAutoCommitAcks());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof ConnectionCreateSessionMessage);
+ ConnectionCreateSessionMessage decodedRequest = (ConnectionCreateSessionMessage) decodedPacket;
+ assertEquals(CONN_CREATESESSION, decodedRequest.getType());
+ assertEquals(request.isXA(), decodedRequest.isXA());
+ assertEquals(request.isAutoCommitSends(), decodedRequest.isAutoCommitSends());
+ assertEquals(request.isAutoCommitAcks(), decodedRequest.isAutoCommitAcks());
+ assertEquals(request.isXA(), decodedRequest.isXA());
+ }
+
+ public void testCreateSessionResponse() throws Exception
+ {
+ ConnectionCreateSessionResponseMessage response = new ConnectionCreateSessionResponseMessage(randomLong());
+
+ AbstractPacketCodec codec = new ConnectionCreateSessionResponseMessageCodec();
+ SimpleRemotingBuffer buffer = encode(response, codec);
+ checkHeader(buffer, response);
+ checkBody(buffer, response.getSessionID());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof ConnectionCreateSessionResponseMessage);
+ ConnectionCreateSessionResponseMessage decodedResponse = (ConnectionCreateSessionResponseMessage) decodedPacket;
+ assertEquals(CONN_CREATESESSION_RESP, decodedResponse.getType());
+ assertEquals(response.getSessionID(), decodedResponse.getSessionID());
+ }
+
+ public void testSendMessage() throws Exception
+ {
+ ProducerSendMessage packet = new ProducerSendMessage(randomString(), new MessageImpl());
+
+ AbstractPacketCodec codec = new ProducerSendMessageCodec();
+ SimpleRemotingBuffer buffer = encode(packet, codec);
+ checkHeader(buffer, packet);
+ checkBody(buffer, packet.getAddress(), StreamUtils.toBytes(packet.getMessage()));
+ buffer.rewind();
+
+ Packet p = codec.decode(buffer);
+
+ assertTrue(p instanceof ProducerSendMessage);
+ ProducerSendMessage decodedPacket = (ProducerSendMessage) p;
+ assertEquals(PROD_SEND, decodedPacket.getType());
+ assertEquals(packet.getAddress(), decodedPacket.getAddress());
+ assertEquals(packet.getMessage().getMessageID(), decodedPacket
+ .getMessage().getMessageID());
+ }
+
+ public void testCreateConsumerRequest() throws Exception
+ {
+ String destination = "queue.testCreateConsumerRequest";
+ SessionCreateConsumerMessage request = new SessionCreateConsumerMessage(destination,
+ "color = 'red'", false, false, randomInt(), randomInt());
+
+ AbstractPacketCodec codec = new SessionCreateConsumerMessageCodec();
+ SimpleRemotingBuffer buffer = encode(request, codec);
+ checkHeader(buffer, request);
+ checkBody(buffer, request.getQueueName(), request
+ .getFilterString(), request.isNoLocal(), request.isAutoDeleteQueue(), request.getWindowSize(), request.getMaxRate());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionCreateConsumerMessage);
+ SessionCreateConsumerMessage decodedRequest = (SessionCreateConsumerMessage) decodedPacket;
+ assertEquals(SESS_CREATECONSUMER, decodedRequest.getType());
+ assertEquals(request.getQueueName(), decodedRequest.getQueueName());
+ assertEquals(request.getFilterString(), decodedRequest.getFilterString());
+ assertEquals(request.isNoLocal(), decodedRequest.isNoLocal());
+ assertEquals(request.isAutoDeleteQueue(), decodedRequest.isAutoDeleteQueue());
+ assertEquals(request.getWindowSize(), decodedRequest.getWindowSize());
+ assertEquals(request.getMaxRate(), decodedRequest.getMaxRate());
+ }
+
+ public void testCreateConsumerResponse() throws Exception
+ {
+ SessionCreateConsumerResponseMessage response =
+ new SessionCreateConsumerResponseMessage(randomLong(), randomInt());
+
+ AbstractPacketCodec codec = new SessionCreateConsumerResponseMessageCodec();
+ SimpleRemotingBuffer buffer = encode(response, codec);
+ checkHeader(buffer, response);
+ checkBody(buffer, response.getConsumerTargetID(), response.getWindowSize());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionCreateConsumerResponseMessage);
+ SessionCreateConsumerResponseMessage decodedResponse = (SessionCreateConsumerResponseMessage) decodedPacket;
+ assertEquals(SESS_CREATECONSUMER_RESP, decodedResponse.getType());
+
+ assertEquals(response.getConsumerTargetID(), decodedResponse.getConsumerTargetID());
+ assertEquals(response.getWindowSize(), decodedResponse.getWindowSize());
+ }
+
+ public void testCreateProducerRequest() throws Exception
+ {
+ String destination = "queue.testCreateProducerRequest";
+ int windowSize = randomInt();
+ int maxRate = randomInt();
+ SessionCreateProducerMessage request = new SessionCreateProducerMessage(destination, windowSize, maxRate);
+
+ AbstractPacketCodec codec = new SessionCreateProducerMessageCodec();
+ SimpleRemotingBuffer buffer = encode(request, codec);
+ checkHeader(buffer, request);
+ checkBody(buffer, request.getAddress(), request.getWindowSize(), request.getMaxRate());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionCreateProducerMessage);
+ SessionCreateProducerMessage decodedRequest = (SessionCreateProducerMessage) decodedPacket;
+ assertEquals(SESS_CREATEPRODUCER, decodedRequest.getType());
+ assertEquals(request.getAddress(), decodedRequest.getAddress());
+ assertEquals(request.getWindowSize(), decodedRequest.getWindowSize());
+ assertEquals(request.getMaxRate(), decodedRequest.getMaxRate());
+ }
+
+ public void testCreateProducerResponse() throws Exception
+ {
+ SessionCreateProducerResponseMessage response =
+ new SessionCreateProducerResponseMessage(randomLong(), randomInt(), randomInt());
+
+ AbstractPacketCodec codec = new SessionCreateProducerResponseMessageCodec();
+ SimpleRemotingBuffer buffer = encode(response, codec);
+ checkHeader(buffer, response);
+ checkBody(buffer, response.getProducerTargetID(), response.getWindowSize(), response.getMaxRate());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionCreateProducerResponseMessage);
+ SessionCreateProducerResponseMessage decodedResponse = (SessionCreateProducerResponseMessage) decodedPacket;
+ assertEquals(SESS_CREATEPRODUCER_RESP, decodedResponse.getType());
+ assertEquals(response.getProducerTargetID(), decodedResponse.getProducerTargetID());
+ assertEquals(response.getWindowSize(), decodedResponse.getWindowSize());
+ assertEquals(response.getMaxRate(), decodedResponse.getMaxRate());
+ }
+
+ public void testStartConnectionMessage() throws Exception
+ {
+ PacketImpl packet = new PacketImpl(CONN_START);
+
+ AbstractPacketCodec codec = PacketCodecFactory.createCodecForEmptyPacket(
+ CONN_START);
+ SimpleRemotingBuffer buffer = encode(packet, codec);
+ checkHeader(buffer, packet);
+ checkBodyIsEmpty(buffer);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertEquals(CONN_START, decodedPacket.getType());
+ }
+
+ public void testStopConnectionMessage() throws Exception
+ {
+ PacketImpl packet = new PacketImpl(CONN_STOP);
+
+ AbstractPacketCodec codec = PacketCodecFactory.createCodecForEmptyPacket(
+ CONN_STOP);
+ SimpleRemotingBuffer buffer = encode(packet, codec);
+ checkHeader(buffer, packet);
+ checkBodyIsEmpty(buffer);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertEquals(CONN_STOP, decodedPacket.getType());
+ }
+
+ public void testConsumerFlowTokenMessage() throws Exception
+ {
+ ConsumerFlowTokenMessage message = new ConsumerFlowTokenMessage(10);
+ AbstractPacketCodec codec = new ConsumerFlowTokenMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ checkBody(buffer, message.getTokens());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof ConsumerFlowTokenMessage);
+ ConsumerFlowTokenMessage decodedMessage = (ConsumerFlowTokenMessage) decodedPacket;
+ assertEquals(CONS_FLOWTOKEN, decodedMessage.getType());
+ assertEquals(message.getTokens(), decodedMessage.getTokens());
+ }
+
+ public void testProducerReceiveTokensMessage() throws Exception
+ {
+ ProducerReceiveTokensMessage message = new ProducerReceiveTokensMessage(10);
+ AbstractPacketCodec codec = new ProducerReceiveTokensMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ checkBody(buffer, message.getTokens());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof ProducerReceiveTokensMessage);
+ ProducerReceiveTokensMessage decodedMessage = (ProducerReceiveTokensMessage) decodedPacket;
+ assertEquals(PacketType.PROD_RECEIVETOKENS, decodedMessage.getType());
+ assertEquals(message.getTokens(), decodedMessage.getTokens());
+ }
+
+ public void testDeliverMessage() throws Exception
+ {
+ Message msg = new MessageImpl();
+ ConsumerDeliverMessage message = new ConsumerDeliverMessage(msg, randomLong());
+
+ AbstractPacketCodec codec = new ConsumerDeliverMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ checkBody(buffer, StreamUtils.toBytes(msg), message.getDeliveryID());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof ConsumerDeliverMessage);
+ ConsumerDeliverMessage decodedMessage = (ConsumerDeliverMessage) decodedPacket;
+ assertEquals(CONS_DELIVER, decodedMessage.getType());
+ assertEquals(message.getMessage().getMessageID(), decodedMessage
+ .getMessage().getMessageID());
+ assertEquals(message.getDeliveryID(), decodedMessage.getDeliveryID());
+ }
+
+ public void testSessionAcknowledgeMessage() throws Exception
+ {
+ SessionAcknowledgeMessage message = new SessionAcknowledgeMessage(
+ randomLong(), true);
+
+ AbstractPacketCodec codec = new SessionAcknowledgeMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ checkBody(buffer, message.getDeliveryID(), message.isAllUpTo());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionAcknowledgeMessage);
+ SessionAcknowledgeMessage decodedMessage = (SessionAcknowledgeMessage) decodedPacket;
+ assertEquals(SESS_ACKNOWLEDGE, decodedMessage.getType());
+ assertEquals(message.getDeliveryID(), decodedMessage.getDeliveryID());
+ assertEquals(message.isAllUpTo(), decodedMessage.isAllUpTo());
+ }
+
+ public void testSessionCancelMessage() throws Exception
+ {
+ SessionCancelMessage message = new SessionCancelMessage(randomLong(),
+ true);
+
+ AbstractPacketCodec codec = new SessionCancelMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ checkBody(buffer, message.getDeliveryID(), message.isExpired());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionCancelMessage);
+ SessionCancelMessage decodedMessage = (SessionCancelMessage) decodedPacket;
+ assertEquals(SESS_CANCEL, decodedMessage.getType());
+ assertEquals(message.getDeliveryID(), decodedMessage.getDeliveryID());
+ assertEquals(message.isExpired(), decodedMessage.isExpired());
+ }
+
+ public void testSessionCommitMessage() throws Exception
+ {
+ PacketImpl message = new PacketImpl(SESS_COMMIT);
+
+ AbstractPacketCodec codec = PacketCodecFactory.createCodecForEmptyPacket(
+ SESS_COMMIT);
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ checkBodyIsEmpty(buffer);
+
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertEquals(SESS_COMMIT, decodedPacket.getType());
+ }
+
+ public void testSessionRollbackMessage() throws Exception
+ {
+ PacketImpl message = new PacketImpl(SESS_ROLLBACK);
+
+ AbstractPacketCodec codec = PacketCodecFactory.createCodecForEmptyPacket(
+ SESS_ROLLBACK);
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ checkBodyIsEmpty(buffer);
+
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertEquals(SESS_ROLLBACK, decodedPacket.getType());
+ }
+
+ public void testSessionRecoverMessage() throws Exception
+ {
+ PacketImpl message = new PacketImpl(SESS_RECOVER);
+
+ AbstractPacketCodec codec = PacketCodecFactory.createCodecForEmptyPacket(
+ SESS_RECOVER);
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ checkBodyIsEmpty(buffer);
+
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertEquals(SESS_RECOVER, decodedPacket.getType());
+ }
+
+ public void testCloseMessage() throws Exception
+ {
+ PacketImpl message = new PacketImpl(CLOSE);
+
+ AbstractPacketCodec codec = PacketCodecFactory.createCodecForEmptyPacket(
+ CLOSE);
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ checkBodyIsEmpty(buffer);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertEquals(CLOSE, decodedPacket.getType());
+ }
+
+
+ public void testCreateBrowserRequest() throws Exception
+ {
+ String destination = "queue.testCreateBrowserRequest";
+ SessionCreateBrowserMessage request = new SessionCreateBrowserMessage(destination,
+ "color = 'red'");
+
+ AbstractPacketCodec codec = new SessionCreateBrowserMessageCodec();
+ SimpleRemotingBuffer buffer = encode(request, codec);
+ checkHeader(buffer, request);
+ checkBody(buffer, request.getQueueName(), request.getFilterString());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionCreateBrowserMessage);
+ SessionCreateBrowserMessage decodedRequest = (SessionCreateBrowserMessage) decodedPacket;
+ assertEquals(SESS_CREATEBROWSER, decodedRequest.getType());
+ assertEquals(request.getQueueName(), decodedRequest.getQueueName());
+ assertEquals(request.getFilterString(), decodedRequest.getFilterString());
+ }
+
+ public void testCreateBrowserResponse() throws Exception
+ {
+ SessionCreateBrowserResponseMessage response = new SessionCreateBrowserResponseMessage(randomLong());
+
+ AbstractPacketCodec codec = new SessionCreateBrowserResponseMessageCodec();
+ SimpleRemotingBuffer buffer = encode(response, codec);
+ checkHeader(buffer, response);
+ checkBody(buffer, response.getBrowserTargetID());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionCreateBrowserResponseMessage);
+ SessionCreateBrowserResponseMessage decodedResponse = (SessionCreateBrowserResponseMessage) decodedPacket;
+ assertEquals(SESS_CREATEBROWSER_RESP, decodedResponse.getType());
+ assertEquals(response.getBrowserTargetID(), decodedResponse.getBrowserTargetID());
+ }
+
+ public void testBrowserResetMessage() throws Exception
+ {
+ PacketImpl message = new PacketImpl(SESS_BROWSER_RESET);
+
+ AbstractPacketCodec codec = PacketCodecFactory.createCodecForEmptyPacket(
+ SESS_BROWSER_RESET);
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ checkBodyIsEmpty(buffer);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertEquals(SESS_BROWSER_RESET, decodedPacket.getType());
+ }
+
+ public void testBrowserHasNextMessageRequest() throws Exception
+ {
+ PacketImpl request = new PacketImpl(SESS_BROWSER_HASNEXTMESSAGE);
+
+ AbstractPacketCodec codec = PacketCodecFactory.createCodecForEmptyPacket(
+ SESS_BROWSER_HASNEXTMESSAGE);
+ SimpleRemotingBuffer buffer = encode(request, codec);
+ checkHeader(buffer, request);
+ checkBodyIsEmpty(buffer);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertEquals(SESS_BROWSER_HASNEXTMESSAGE, decodedPacket.getType());
+ }
+
+ public void testBrowserHasNextMessageResponse() throws Exception
+ {
+ SessionBrowserHasNextMessageResponseMessage response = new SessionBrowserHasNextMessageResponseMessage(
+ false);
+ AbstractPacketCodec codec = new SessionBrowserHasNextMessageResponseMessageCodec();
+ SimpleRemotingBuffer buffer = encode(response, codec);
+ checkHeader(buffer, response);
+ checkBody(buffer, response.hasNext());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionBrowserHasNextMessageResponseMessage);
+ SessionBrowserHasNextMessageResponseMessage decodedResponse = (SessionBrowserHasNextMessageResponseMessage) decodedPacket;
+ assertEquals(SESS_BROWSER_HASNEXTMESSAGE_RESP, decodedResponse.getType());
+ assertEquals(response.hasNext(), decodedResponse.hasNext());
+ }
+
+ public void testBrowserNextMessageRequest() throws Exception
+ {
+ PacketImpl request = new PacketImpl(SESS_BROWSER_NEXTMESSAGE);
+
+ AbstractPacketCodec codec = PacketCodecFactory.createCodecForEmptyPacket(
+ SESS_BROWSER_NEXTMESSAGE);
+ SimpleRemotingBuffer buffer = encode(request, codec);
+ checkHeader(buffer, request);
+ checkBodyIsEmpty(buffer);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertEquals(SESS_BROWSER_NEXTMESSAGE, decodedPacket.getType());
+ }
+
+ public void testBrowserNextMessageResponse() throws Exception
+ {
+ Message msg = new MessageImpl();
+ SessionBrowserNextMessageResponseMessage response = new SessionBrowserNextMessageResponseMessage(msg);
+
+ AbstractPacketCodec codec = new SessionBrowserNextMessageResponseMessageCodec();
+ SimpleRemotingBuffer buffer = encode(response, codec);
+ checkHeader(buffer, response);
+ checkBody(buffer, StreamUtils.toBytes(msg));
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionBrowserNextMessageResponseMessage);
+ SessionBrowserNextMessageResponseMessage decodedResponse = (SessionBrowserNextMessageResponseMessage) decodedPacket;
+ assertEquals(SESS_BROWSER_NEXTMESSAGE_RESP, decodedResponse.getType());
+ assertEquals(response.getMessage().getMessageID(), decodedResponse
+ .getMessage().getMessageID());
+ }
+
+ public void testBrowserNextMessageBlockRequest() throws Exception
+ {
+ SessionBrowserNextMessageBlockMessage request = new SessionBrowserNextMessageBlockMessage(
+ randomLong());
+
+ AbstractPacketCodec codec = new SessionBrowserNextMessageBlockMessageCodec();
+ SimpleRemotingBuffer buffer = encode(request, codec);
+ checkHeader(buffer, request);
+ checkBody(buffer, request.getMaxMessages());
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionBrowserNextMessageBlockMessage);
+ SessionBrowserNextMessageBlockMessage decodedRequest = (SessionBrowserNextMessageBlockMessage) decodedPacket;
+ assertEquals(SESS_BROWSER_NEXTMESSAGEBLOCK, decodedPacket.getType());
+ assertEquals(request.getMaxMessages(), decodedRequest.getMaxMessages());
+ }
+
+ public void testBrowserNextMessageBlockResponse() throws Exception
+ {
+ Message[] messages = new Message[] { new MessageImpl(), new MessageImpl() };
+ SessionBrowserNextMessageBlockResponseMessage response = new SessionBrowserNextMessageBlockResponseMessage(
+ messages);
+
+ AbstractPacketCodec codec = new SessionBrowserNextMessageBlockResponseMessageCodec();
+ SimpleRemotingBuffer buffer = encode(response, codec);
+ checkHeader(buffer, response);
+ checkBody(buffer, messages.length, SessionBrowserNextMessageBlockResponseMessageCodec
+ .encode(messages));
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionBrowserNextMessageBlockResponseMessage);
+ SessionBrowserNextMessageBlockResponseMessage decodedResponse = (SessionBrowserNextMessageBlockResponseMessage) decodedPacket;
+ assertEquals(SESS_BROWSER_NEXTMESSAGEBLOCK_RESP, decodedResponse.getType());
+ assertEquals(response.getMessages()[0].getMessageID(), decodedResponse
+ .getMessages()[0].getMessageID());
+ assertEquals(response.getMessages()[1].getMessageID(), decodedResponse
+ .getMessages()[1].getMessageID());
+ }
+
+
+ public void testSesssionXACommitMessageOnePhase() throws Exception
+ {
+ this.testSessionXACommitMessage(true);
+ }
+
+ public void testSessionXACommitMessageNotOnePhase() throws Exception
+ {
+ this.testSessionXACommitMessage(false);
+ }
+
+ private void testSessionXACommitMessage(boolean onePhase) throws Exception
+ {
+ Xid xid = this.generateXid();
+ SessionXACommitMessage message = new SessionXACommitMessage(xid, onePhase);
+ AbstractPacketCodec codec = new SessionXACommitMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+ assertTrue(decodedPacket instanceof SessionXACommitMessage);
+ SessionXACommitMessage decodedMessage = (SessionXACommitMessage)decodedPacket;
+ assertEquals(SESS_XA_COMMIT, decodedMessage.getType());
+ assertEquals(xid, decodedMessage.getXid());
+ assertEquals(onePhase, decodedMessage.isOnePhase());
+ }
+
+ public void testSessionXAEndMessageFailed() throws Exception
+ {
+ this.testSessionXAEndMessage(true);
+ }
+
+ public void testSessionXAEndMessageNotFailed() throws Exception
+ {
+ this.testSessionXACommitMessage(false);
+ }
+
+ private void testSessionXAEndMessage(boolean failed) throws Exception
+ {
+ Xid xid = this.generateXid();
+ SessionXAEndMessage message = new SessionXAEndMessage(xid, failed);
+ AbstractPacketCodec codec = new SessionXAEndMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+ assertTrue(decodedPacket instanceof SessionXAEndMessage);
+ SessionXAEndMessage decodedMessage = (SessionXAEndMessage)decodedPacket;
+ assertEquals(SESS_XA_END, decodedMessage.getType());
+ assertEquals(xid, decodedMessage.getXid());
+ assertEquals(failed, decodedMessage.isFailed());
+ }
+
+ public void testSessionXAForgetMessage() throws Exception
+ {
+ Xid xid = this.generateXid();
+ SessionXAForgetMessage message = new SessionXAForgetMessage(xid);
+ AbstractPacketCodec codec = new SessionXAForgetMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+ assertTrue(decodedPacket instanceof SessionXAForgetMessage);
+ SessionXAForgetMessage decodedMessage = (SessionXAForgetMessage)decodedPacket;
+ assertEquals(SESS_XA_FORGET, decodedMessage.getType());
+ assertEquals(xid, decodedMessage.getXid());
+ }
+
+ public void testSessionXAGetInDoubtXidsMessage() throws Exception
+ {
+ PacketImpl request = new PacketImpl(SESS_XA_INDOUBT_XIDS);
+
+ AbstractPacketCodec codec = PacketCodecFactory.createCodecForEmptyPacket(
+ SESS_XA_INDOUBT_XIDS);
+ SimpleRemotingBuffer buffer = encode(request, codec);
+ checkHeader(buffer, request);
+ checkBodyIsEmpty(buffer);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertEquals(SESS_XA_INDOUBT_XIDS, decodedPacket.getType());
+ }
+
+ public void testSessionGetInDoubtXidsResponse() throws Exception
+ {
+ final int numXids = 10;
+ List<Xid> xids = new ArrayList<Xid>();
+ for (int i = 0; i < numXids; i++)
+ {
+ xids.add(generateXid());
+ }
+
+ SessionXAGetInDoubtXidsResponseMessage message = new SessionXAGetInDoubtXidsResponseMessage(xids);
+ AbstractPacketCodec codec = new SessionXAGetInDoubtXidsResponseMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+ assertTrue(decodedPacket instanceof SessionXAGetInDoubtXidsResponseMessage);
+ SessionXAGetInDoubtXidsResponseMessage decodedMessage = (SessionXAGetInDoubtXidsResponseMessage)decodedPacket;
+ assertEquals(SESS_XA_INDOUBT_XIDS_RESP, decodedMessage.getType());
+
+ List<Xid> decodedXids = decodedMessage.getXids();
+ assertNotNull(decodedXids);
+ assertEquals(xids.size(), decodedXids.size());
+
+ for (int i = 0; i < numXids; i++)
+ {
+ assertEquals(xids.get(i), decodedXids.get(i));
+ }
+ }
+
+ public void testSessionXAGetTimeoutMessage() throws Exception
+ {
+ PacketImpl message = new PacketImpl(SESS_XA_GET_TIMEOUT);
+
+ AbstractPacketCodec codec = PacketCodecFactory.createCodecForEmptyPacket(
+ PacketType.SESS_XA_GET_TIMEOUT);
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ checkBodyIsEmpty(buffer);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertEquals(SESS_XA_GET_TIMEOUT, decodedPacket.getType());
+ }
+
+ public void testSessionXAGetTimeoutResponse() throws Exception
+ {
+ final int timeout = RandomUtil.randomInt();
+
+ SessionXAGetTimeoutResponseMessage message = new SessionXAGetTimeoutResponseMessage(timeout);
+ AbstractPacketCodec codec = new SessionXAGetTimeoutResponseMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+ assertTrue(decodedPacket instanceof SessionXAGetTimeoutResponseMessage);
+ SessionXAGetTimeoutResponseMessage decodedMessage = (SessionXAGetTimeoutResponseMessage)decodedPacket;
+ assertEquals(SESS_XA_GET_TIMEOUT_RESP, decodedMessage.getType());
+
+ assertEquals(timeout, decodedMessage.getTimeoutSeconds());
+ }
+
+ public void testSessionXAJoinMessage() throws Exception
+ {
+ Xid xid = this.generateXid();
+ SessionXAJoinMessage message = new SessionXAJoinMessage(xid);
+ AbstractPacketCodec codec = new SessionXAJoinMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+ assertTrue(decodedPacket instanceof SessionXAJoinMessage);
+ SessionXAJoinMessage decodedMessage = (SessionXAJoinMessage)decodedPacket;
+ assertEquals(SESS_XA_JOIN, decodedMessage.getType());
+ assertEquals(xid, decodedMessage.getXid());
+ }
+
+ public void testSessionXAPrepareMessage() throws Exception
+ {
+ Xid xid = this.generateXid();
+ SessionXAPrepareMessage message = new SessionXAPrepareMessage(xid);
+ AbstractPacketCodec codec = new SessionXAPrepareMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+ assertTrue(decodedPacket instanceof SessionXAPrepareMessage);
+ SessionXAPrepareMessage decodedMessage = (SessionXAPrepareMessage)decodedPacket;
+ assertEquals(SESS_XA_PREPARE, decodedMessage.getType());
+ assertEquals(xid, decodedMessage.getXid());
+ }
+
+ public void testSessionXAResponseErrorNullString() throws Exception
+ {
+ testSessionXAResponse(true, true);
+ }
+
+ public void testSessionXAResponseErrorNotNullString() throws Exception
+ {
+ testSessionXAResponse(true, false);
+ }
+
+ public void testSessionXAResponseNoErrorNullString() throws Exception
+ {
+ testSessionXAResponse(false, true);
+ }
+
+ public void testSessionXAResponseNoErrorNotNullString() throws Exception
+ {
+ testSessionXAResponse(false, false);
+ }
+
+ private void testSessionXAResponse(boolean error, boolean nullString) throws Exception
+ {
+ int responseCode = RandomUtil.randomInt();
+
+ String str = nullString ? null : RandomUtil.randomString();
+
+ SessionXAResponseMessage message = new SessionXAResponseMessage(error, responseCode, str);
+ AbstractPacketCodec codec = new SessionXAResponseMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+ assertTrue(decodedPacket instanceof SessionXAResponseMessage);
+ SessionXAResponseMessage decodedMessage = (SessionXAResponseMessage)decodedPacket;
+ assertEquals(SESS_XA_RESP, decodedMessage.getType());
+ assertEquals(error, decodedMessage.isError());
+ assertEquals(responseCode, decodedMessage.getResponseCode());
+ assertEquals(str, decodedMessage.getMessage());
+ }
+
+ public void testSessionXAResumeMessage() throws Exception
+ {
+ Xid xid = this.generateXid();
+ SessionXAResumeMessage message = new SessionXAResumeMessage(xid);
+ AbstractPacketCodec codec = new SessionXAResumeMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+ assertTrue(decodedPacket instanceof SessionXAResumeMessage);
+ SessionXAResumeMessage decodedMessage = (SessionXAResumeMessage)decodedPacket;
+ assertEquals(SESS_XA_RESUME, decodedMessage.getType());
+ assertEquals(xid, decodedMessage.getXid());
+ }
+
+ public void testSessionXARollbackMessage() throws Exception
+ {
+ Xid xid = this.generateXid();
+ SessionXARollbackMessage message = new SessionXARollbackMessage(xid);
+ AbstractPacketCodec codec = new SessionXARollbackMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+ assertTrue(decodedPacket instanceof SessionXARollbackMessage);
+ SessionXARollbackMessage decodedMessage = (SessionXARollbackMessage)decodedPacket;
+ assertEquals(SESS_XA_ROLLBACK, decodedMessage.getType());
+ assertEquals(xid, decodedMessage.getXid());
+ }
+
+ public void testSessionXASetTimeoutMessage() throws Exception
+ {
+ final int timeout = RandomUtil.randomInt();
+ SessionXASetTimeoutMessage message = new SessionXASetTimeoutMessage(timeout);
+ AbstractPacketCodec codec = new SessionXASetTimeoutMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+ assertTrue(decodedPacket instanceof SessionXASetTimeoutMessage);
+ SessionXASetTimeoutMessage decodedMessage = (SessionXASetTimeoutMessage)decodedPacket;
+ assertEquals(SESS_XA_SET_TIMEOUT, decodedMessage.getType());
+ assertEquals(timeout, decodedMessage.getTimeoutSeconds());
+ }
+
+ public void testSessionXASetTimeoutResponseMessageOK() throws Exception
+ {
+ testSessionXASetTimeoutResponseMessage(true);
+ }
+
+ public void testSessionXASetTimeoutResponseMessageNotOK() throws Exception
+ {
+ testSessionXASetTimeoutResponseMessage(false);
+ }
+
+ private void testSessionXASetTimeoutResponseMessage(boolean ok) throws Exception
+ {
+ final int timeout = RandomUtil.randomInt();
+ SessionXASetTimeoutResponseMessage message = new SessionXASetTimeoutResponseMessage(ok);
+ AbstractPacketCodec codec = new SessionXASetTimeoutResponseMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+ assertTrue(decodedPacket instanceof SessionXASetTimeoutResponseMessage);
+ SessionXASetTimeoutResponseMessage decodedMessage = (SessionXASetTimeoutResponseMessage)decodedPacket;
+ assertEquals(SESS_XA_SET_TIMEOUT_RESP, decodedMessage.getType());
+ assertEquals(ok, decodedMessage.isOK());
+ }
+
+ public void testSessionXAStartMessage() throws Exception
+ {
+ Xid xid = this.generateXid();
+ SessionXAStartMessage message = new SessionXAStartMessage(xid);
+ AbstractPacketCodec codec = new SessionXAStartMessageCodec();
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+ assertTrue(decodedPacket instanceof SessionXAStartMessage);
+ SessionXAStartMessage decodedMessage = (SessionXAStartMessage)decodedPacket;
+ assertEquals(SESS_XA_START, decodedMessage.getType());
+ assertEquals(xid, decodedMessage.getXid());
+ }
+
+ public void testSessionXASuspendMessage() throws Exception
+ {
+ PacketImpl message = new PacketImpl(SESS_XA_SUSPEND);
+
+ AbstractPacketCodec codec = PacketCodecFactory.createCodecForEmptyPacket(
+ PacketType.SESS_XA_SUSPEND);
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ checkBodyIsEmpty(buffer);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertEquals(SESS_XA_SUSPEND, decodedPacket.getType());
+ }
+
+
+ public void testSessionRemoveAddressMessage() throws Exception
+ {
+ SessionRemoveDestinationMessage message = new SessionRemoveDestinationMessage(randomString(), true);
+
+ AbstractPacketCodec codec = new SessionRemoveDestinationMessageCodec();
+
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionRemoveDestinationMessage);
+ SessionRemoveDestinationMessage decodedMessage = (SessionRemoveDestinationMessage)decodedPacket;
+ assertEquals(SESS_REMOVE_DESTINATION, decodedMessage.getType());
+
+ assertEquals(message.getAddress(), decodedMessage.getAddress());
+ assertEquals(message.isTemporary(), decodedMessage.isTemporary());
+
+ }
+
+ public void testSessionCreateQueueRequest() throws Exception
+ {
+ SessionCreateQueueMessage message = new SessionCreateQueueMessage(randomString(), randomString(), randomString(), true, true);
+
+ AbstractPacketCodec codec = new SessionCreateQueueMessageCodec();
+
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionCreateQueueMessage);
+ SessionCreateQueueMessage decodedMessage = (SessionCreateQueueMessage)decodedPacket;
+ assertEquals(SESS_CREATEQUEUE, decodedMessage.getType());
+
+ assertEquals(message.getAddress(), decodedMessage.getAddress());
+ assertEquals(message.getQueueName(), decodedMessage.getQueueName());
+ assertEquals(message.getFilterString(), decodedMessage.getFilterString());
+ assertEquals(message.isDurable(), decodedMessage.isDurable());
+ assertEquals(message.isTemporary(), decodedMessage.isDurable());
+
+ }
+
+ public void testSessionQueueQueryRequest() throws Exception
+ {
+ SessionQueueQueryMessage message = new SessionQueueQueryMessage(randomString());
+
+ AbstractPacketCodec codec = new SessionQueueQueryMessageCodec();
+
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionQueueQueryMessage);
+ SessionQueueQueryMessage decodedMessage = (SessionQueueQueryMessage)decodedPacket;
+ assertEquals(SESS_QUEUEQUERY, decodedMessage.getType());
+
+ assertEquals(message.getQueueName(), decodedMessage.getQueueName());
+ }
+
+ public void testSessionQueueQueryResponse() throws Exception
+ {
+ SessionQueueQueryResponseMessage message = new SessionQueueQueryResponseMessage(true, true, randomInt(), randomInt(), randomInt(),
+ randomString(), randomString());
+
+ AbstractPacketCodec codec = new SessionQueueQueryResponseMessageCodec();
+
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionQueueQueryResponseMessage);
+ SessionQueueQueryResponseMessage decodedMessage = (SessionQueueQueryResponseMessage)decodedPacket;
+ assertEquals(SESS_QUEUEQUERY_RESP, decodedMessage.getType());
+
+ assertEquals(message.isExists(), decodedMessage.isExists());
+ assertEquals(message.isDurable(), decodedMessage.isDurable());
+ assertEquals(message.isTemporary(), decodedMessage.isTemporary());
+ assertEquals(message.getConsumerCount(), decodedMessage.getConsumerCount());
+ assertEquals(message.getMessageCount(), decodedMessage.getMessageCount());
+ assertEquals(message.getFilterString(), decodedMessage.getFilterString());
+ assertEquals(message.getAddress(), decodedMessage.getAddress());
+ }
+
+ public void testSessionAddAddressMessage() throws Exception
+ {
+ SessionAddDestinationMessage message = new SessionAddDestinationMessage(randomString(), true);
+
+ AbstractPacketCodec<SessionAddDestinationMessage> codec = new SessionAddDestinationMessageCodec();
+
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionAddDestinationMessage);
+ SessionAddDestinationMessage decodedMessage = (SessionAddDestinationMessage)decodedPacket;
+ assertEquals(SESS_ADD_DESTINATION, decodedMessage.getType());
+
+ assertEquals(message.getAddress(), decodedMessage.getAddress());
+ assertEquals(message.isTemporary(), decodedMessage.isTemporary());
+ }
+
+ public void testSessionBindingQueryMessage() throws Exception
+ {
+ SessionBindingQueryMessage message = new SessionBindingQueryMessage(randomString());
+
+ AbstractPacketCodec codec = new SessionBindingQueryMessageCodec();
+
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionBindingQueryMessage);
+ SessionBindingQueryMessage decodedMessage = (SessionBindingQueryMessage)decodedPacket;
+ assertEquals(SESS_BINDINGQUERY, decodedMessage.getType());
+
+ assertEquals(message.getAddress(), decodedMessage.getAddress());
+ }
+
+ public void testSessionBindingQueryResponseMessage() throws Exception
+ {
+ boolean exists = true;
+ List<String> queueNames = new ArrayList<String>();
+ queueNames.add(randomString());
+ queueNames.add(randomString());
+ queueNames.add(randomString());
+ SessionBindingQueryResponseMessage message = new SessionBindingQueryResponseMessage(exists, queueNames);
+
+ AbstractPacketCodec codec = new SessionBindingQueryResponseMessageCodec();
+
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionBindingQueryResponseMessage);
+ SessionBindingQueryResponseMessage decodedMessage = (SessionBindingQueryResponseMessage)decodedPacket;
+ assertEquals(SESS_BINDINGQUERY_RESP, decodedMessage.getType());
+
+ assertEquals(message.isExists(), decodedMessage.isExists());
+
+ List<String> decodedNames = decodedMessage.getQueueNames();
+ assertEquals(queueNames.size(), decodedNames.size());
+ for (int i = 0; i < queueNames.size(); i++)
+ {
+ assertEquals(queueNames.get(i), decodedNames.get(i));
+ }
+ }
+
+
+ public void testDeleteQueueRequest() throws Exception
+ {
+ SessionDeleteQueueMessage message = new SessionDeleteQueueMessage(randomString());
+
+ AbstractPacketCodec codec = new SessionDeleteQueueMessageCodec();
+
+ SimpleRemotingBuffer buffer = encode(message, codec);
+ checkHeader(buffer, message);
+ buffer.rewind();
+
+ Packet decodedPacket = codec.decode(buffer);
+
+ assertTrue(decodedPacket instanceof SessionDeleteQueueMessage);
+ SessionDeleteQueueMessage decodedMessage = (SessionDeleteQueueMessage)decodedPacket;
+ assertEquals(SESS_DELETE_QUEUE, decodedMessage.getType());
+
+ assertEquals(message.getQueueName(), decodedMessage.getQueueName());
+ }
+
+
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ private SimpleRemotingBuffer encode(PacketImpl packet,
+ AbstractPacketCodec codec) throws Exception
+ {
+ log.debug("encode " + packet);
+
+ IoBuffer b = IoBuffer.allocate(256);
+ b.setAutoExpand(true);
+
+ SimpleRemotingBuffer buf = new SimpleRemotingBuffer(b);
+
+ codec.encode(packet, buf);
+ buf.flip();
+
+ return buf;
+ }
+
+ private final class SimpleRemotingBuffer extends BufferWrapper
+ {
+
+ public SimpleRemotingBuffer(IoBuffer buffer)
+ {
+ super(buffer);
+ }
+
+ IoBuffer buffer()
+ {
+ return buffer;
+ }
+
+ public void flip()
+ {
+ buffer.flip();
+ }
+
+ public void rewind() throws IOException
+ {
+ buffer.rewind();
+ }
+
+ public int remaining()
+ {
+ return buffer.remaining();
+ }
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/security/impl/JAASSecurityManagerTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/security/impl/test/unit/JAASSecurityManagerTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/security/impl/JAASSecurityManagerTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/security/impl/JAASSecurityManagerTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,145 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.security.impl;
+
+import junit.framework.TestCase;
+import org.jboss.messaging.core.security.impl.JAASSecurityManager;
+import org.jboss.messaging.core.security.Role;
+import org.jboss.messaging.core.security.CheckType;
+import org.jboss.security.AuthenticationManager;
+import org.jboss.security.SimplePrincipal;
+import org.jboss.security.RealmMapping;
+import org.easymock.EasyMock;
+import org.easymock.IArgumentMatcher;
+
+import javax.security.auth.Subject;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * tests the JAASSecurityManager
+ * @author <a href="ataylor at redhat.com">Andy Taylor</a>
+ */
+public class JAASSecurityManagerTest extends TestCase
+{
+ JAASSecurityManager securityManager;
+ protected void setUp() throws Exception
+ {
+ securityManager = new JAASSecurityManager();
+ }
+
+ protected void tearDown() throws Exception
+ {
+ securityManager = null;
+ }
+
+ public void testValidatingUser()
+ {
+ AuthenticationManager authenticationManager = EasyMock.createStrictMock(AuthenticationManager.class);
+ securityManager.setAuthenticationManager(authenticationManager);
+ SimplePrincipal principal = new SimplePrincipal("newuser1");
+ char[] passwordChars = "newpassword1".toCharArray();
+ Subject subject = new Subject();
+ EasyMock.expect(authenticationManager.isValid(principal(principal), EasyMock.aryEq(passwordChars), subject(subject))).andReturn(true);
+ EasyMock.replay(authenticationManager);
+
+ securityManager.validateUser("newuser1", "newpassword1");
+ }
+
+ public void testValidatingUserAndRole()
+ {
+ AuthenticationManager authenticationManager = EasyMock.createStrictMock(AuthenticationManager.class);
+ securityManager.setAuthenticationManager(authenticationManager);
+ RealmMapping realmMapping = EasyMock.createStrictMock(RealmMapping.class);
+ securityManager.setRealmMapping(realmMapping);
+ SimplePrincipal principal = new SimplePrincipal("newuser1");
+ char[] passwordChars = "newpassword1".toCharArray();
+ Subject subject = new Subject();
+ EasyMock.expect(authenticationManager.isValid(principal(principal), EasyMock.aryEq(passwordChars), subject(subject))).andReturn(true);
+ EasyMock.replay(authenticationManager);
+ EasyMock.expect(realmMapping.doesUserHaveRole(principal(principal), EasyMock.isA(Set.class))).andReturn(true);
+ EasyMock.replay(realmMapping);
+ securityManager.validateUserAndRole("newuser1", "newpassword1", new HashSet<Role>(), CheckType.CREATE );
+ }
+
+ public static SimplePrincipal principal(SimplePrincipal principal)
+ {
+ EasyMock.reportMatcher(new SimplePrincipalMatcher(principal));
+ return principal;
+ }
+
+ public static Subject subject(Subject subject)
+ {
+ EasyMock.reportMatcher(new SubjectMatcher(subject));
+ return subject;
+ }
+
+ static class SimplePrincipalMatcher implements IArgumentMatcher
+ {
+ SimplePrincipal principal;
+
+ public SimplePrincipalMatcher(SimplePrincipal principal)
+ {
+ this.principal = principal;
+ }
+
+ public boolean matches(Object o)
+ {
+ if(o instanceof SimplePrincipal)
+ {
+ SimplePrincipal that = (SimplePrincipal) o;
+ return that.getName().equals(principal.getName());
+ }
+ return false;
+ }
+
+ public void appendTo(StringBuffer stringBuffer)
+ {
+ stringBuffer.append("Invalid Principal created");
+ }
+ }
+
+ static class SubjectMatcher implements IArgumentMatcher
+ {
+ Subject subject;
+
+ public SubjectMatcher(Subject subject)
+ {
+ this.subject = subject;
+ }
+
+ public boolean matches(Object o)
+ {
+ if(o instanceof Subject)
+ {
+ Subject that = (Subject) o;
+ return true;
+ }
+ return false;
+ }
+
+ public void appendTo(StringBuffer stringBuffer)
+ {
+ stringBuffer.append("Invalid Subject created");
+ }
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/security/impl/JBMSecurityManagerImplTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/security/impl/test/unit/JBMSecurityManagerImplTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/security/impl/JBMSecurityManagerImplTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/security/impl/JBMSecurityManagerImplTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,158 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.security.impl;
+
+import junit.framework.TestCase;
+import org.jboss.messaging.core.security.impl.JBMSecurityManagerImpl;
+import org.jboss.messaging.core.security.CheckType;
+import org.jboss.messaging.core.security.Role;
+
+import java.util.HashSet;
+
+/**
+ * tests JBMSecurityManagerImpl
+ * @author <a href="ataylor at redhat.com">Andy Taylor</a>
+ */
+public class JBMSecurityManagerImplTest extends TestCase
+{
+ private JBMSecurityManagerImpl securityManager;
+
+ protected void setUp() throws Exception
+ {
+ securityManager = new JBMSecurityManagerImpl(true);
+ }
+
+ protected void tearDown() throws Exception
+ {
+ securityManager = null;
+ }
+
+ public void testDefaultSecurity()
+ {
+ assertTrue(securityManager.validateUser(null, null));
+ assertTrue(securityManager.validateUser("guest", "guest"));
+ HashSet<Role> roles = new HashSet<Role>();
+ roles.add(new Role("guest", true, true, true));
+ assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.CREATE));
+ assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.WRITE));
+ assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.READ));
+ roles = new HashSet<Role>();
+ roles.add(new Role("guest", true, true, false));
+ assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.CREATE));
+ assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.WRITE));
+ assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.READ));
+ roles = new HashSet<Role>();
+ roles.add(new Role("guest", true, false, false));
+ assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.CREATE));
+ assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.WRITE));
+ assertTrue(securityManager.validateUserAndRole(null, null, roles, CheckType.READ));
+ roles = new HashSet<Role>();
+ roles.add(new Role("guest", false, false, false));
+ assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.CREATE));
+ assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.WRITE));
+ assertFalse(securityManager.validateUserAndRole(null, null, roles, CheckType.READ));
+ }
+
+ public void testAddingUsers()
+ {
+ securityManager.addUser("newuser1", "newpassword1");
+ assertTrue(securityManager.validateUser("newuser1", "newpassword1"));
+ assertFalse(securityManager.validateUser("newuser1", "guest"));
+ assertFalse(securityManager.validateUser("newuser1", null));
+ try
+ {
+ securityManager.addUser("newuser2", null);
+ fail("password cannot be null");
+ }
+ catch (IllegalArgumentException e)
+ {
+ //pass
+ }
+ try
+ {
+ securityManager.addUser(null, "newpassword2");
+ fail("password cannot be null");
+ }
+ catch (IllegalArgumentException e)
+ {
+ //pass
+ }
+ }
+
+ public void testRemovingUsers()
+ {
+ securityManager.addUser("newuser1", "newpassword1");
+ assertTrue(securityManager.validateUser("newuser1", "newpassword1"));
+ securityManager.removeUser("newuser1");
+ assertFalse(securityManager.validateUser("newuser1", "newpassword1"));
+ }
+
+ public void testAddingRoles()
+ {
+ securityManager.addUser("newuser1", "newpassword1");
+ securityManager.addRole("newuser1", "role1");
+ securityManager.addRole("newuser1", "role2");
+ securityManager.addRole("newuser1", "role3");
+ securityManager.addRole("newuser1", "role4");
+ HashSet<Role> roles = new HashSet<Role>();
+ roles.add(new Role("role1", true, true, true));
+ assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.WRITE));
+ roles = new HashSet<Role>();
+ roles.add(new Role("role2", true, true, true));
+ assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.WRITE));
+ roles = new HashSet<Role>();
+ roles.add(new Role("role3", true, true, true));
+ assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.WRITE));
+ roles = new HashSet<Role>();
+ roles.add(new Role("role4", true, true, true));
+ assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.WRITE));
+ roles = new HashSet<Role>();
+ roles.add(new Role("role5", true, true, true));
+ assertFalse(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.WRITE));
+ }
+
+ public void testRemovingRoles()
+ {
+ securityManager.addUser("newuser1", "newpassword1");
+ securityManager.addRole("newuser1", "role1");
+ securityManager.addRole("newuser1", "role2");
+ securityManager.addRole("newuser1", "role3");
+ securityManager.addRole("newuser1", "role4");
+ securityManager.removeRole("newuser1", "role2");
+ securityManager.removeRole("newuser1", "role4");
+ HashSet<Role> roles = new HashSet<Role>();
+ roles.add(new Role("role1", true, true, true));
+ assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.WRITE));
+ roles = new HashSet<Role>();
+ roles.add(new Role("role2", true, true, true));
+ assertFalse(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.WRITE));
+ roles = new HashSet<Role>();
+ roles.add(new Role("role3", true, true, true));
+ assertTrue(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.WRITE));
+ roles = new HashSet<Role>();
+ roles.add(new Role("role4", true, true, true));
+ assertFalse(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.WRITE));
+ roles = new HashSet<Role>();
+ roles.add(new Role("role5", true, true, true));
+ assertFalse(securityManager.validateUserAndRole("newuser1", "newpassword1", roles, CheckType.WRITE));
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/security/impl/SecurityStoreImplTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/security/impl/test/unit/SecurityStoreImplTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/security/impl/SecurityStoreImplTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/security/impl/SecurityStoreImplTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,202 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.security.impl;
+
+import junit.framework.TestCase;
+import org.jboss.messaging.core.security.impl.SecurityStoreImpl;
+import org.jboss.messaging.core.security.JBMSecurityManager;
+import org.jboss.messaging.core.security.Role;
+import org.jboss.messaging.core.security.CheckType;
+import org.jboss.messaging.core.settings.impl.HierarchicalObjectRepository;
+import org.jboss.messaging.core.settings.HierarchicalRepository;
+import org.jboss.messaging.core.server.ServerConnection;
+import org.jboss.messaging.core.server.impl.ServerConnectionImpl;
+import org.easymock.EasyMock;
+
+import java.util.HashSet;
+
+/**
+ * tests SecurityStoreImpl
+ * @author <a href="ataylor at redhat.com">Andy Taylor</a>
+ */
+public class SecurityStoreImplTest extends TestCase
+{
+ SecurityStoreImpl securityStore;
+
+ protected void setUp() throws Exception
+ {
+ securityStore = new SecurityStoreImpl(1000000000);
+ }
+
+ protected void tearDown() throws Exception
+ {
+ securityStore = null;
+ }
+
+ public void testSuccessfulAuthentication() throws Exception
+ {
+ JBMSecurityManager securityManager = EasyMock.createStrictMock(JBMSecurityManager.class);
+ securityStore.setSecurityManager(securityManager);
+ EasyMock.expect(securityManager.validateUser("user", "password")).andReturn(true);
+ EasyMock.replay(securityManager);
+ securityStore.authenticate("user", "password");
+ }
+
+ public void testFailedAuthentication() throws Exception
+ {
+ JBMSecurityManager securityManager = EasyMock.createStrictMock(JBMSecurityManager.class);
+ securityStore.setSecurityManager(securityManager);
+ EasyMock.expect(securityManager.validateUser("user", "password")).andReturn(false);
+ EasyMock.replay(securityManager);
+ try
+ {
+ securityStore.authenticate("user", "password");
+ fail("should throw exception");
+ }
+ catch (Exception e)
+ {
+ //pass
+ }
+ }
+
+ public void testSuccessfulCheck() throws Exception
+ {
+ JBMSecurityManager securityManager = EasyMock.createStrictMock(JBMSecurityManager.class);
+ securityStore.setSecurityManager(securityManager);
+ //noinspection unchecked
+ HierarchicalRepository<HashSet<Role>> repository = EasyMock.createStrictMock(HierarchicalRepository.class);
+
+ String address = "anaddress";
+ HashSet<Role> roles = new HashSet<Role>();
+ roles.add(new Role("user", false, false, true));
+ repository.registerListener(securityStore);
+ EasyMock.expect(repository.getMatch(address)).andReturn(roles);
+ ServerConnection serverConnection = EasyMock.createNiceMock(ServerConnection.class);
+ EasyMock.expect(serverConnection.getUsername()).andReturn("user");
+ EasyMock.expect(serverConnection.getPassword()).andReturn("password");
+ EasyMock.expect(securityManager.validateUserAndRole("user", "password", roles, CheckType.CREATE)).andReturn(true);
+ EasyMock.replay(repository);
+ EasyMock.replay(securityManager);
+ EasyMock.replay(serverConnection);
+ securityStore.setSecurityRepository(repository);
+ securityStore.check(address, CheckType.CREATE, serverConnection );
+ //now checked its cached
+ EasyMock.reset(repository);
+ EasyMock.reset(securityManager);
+ EasyMock.reset(serverConnection);
+ EasyMock.replay(repository);
+ EasyMock.replay(securityManager);
+ securityStore.check(address, CheckType.CREATE, serverConnection );
+
+ }
+
+ public void testUnsuccessfulCheck() throws Exception
+ {
+ JBMSecurityManager securityManager = EasyMock.createStrictMock(JBMSecurityManager.class);
+ securityStore.setSecurityManager(securityManager);
+ //noinspection unchecked
+ HierarchicalRepository<HashSet<Role>> repository = EasyMock.createStrictMock(HierarchicalRepository.class);
+
+ String address = "anaddress";
+ HashSet<Role> roles = new HashSet<Role>();
+ roles.add(new Role("user", false, false, true));
+ repository.registerListener(securityStore);
+ EasyMock.expect(repository.getMatch(address)).andReturn(roles);
+ ServerConnection serverConnection = EasyMock.createNiceMock(ServerConnection.class);
+ EasyMock.expect(serverConnection.getUsername()).andReturn("user");
+ EasyMock.expect(serverConnection.getPassword()).andReturn("password");
+ EasyMock.expect(securityManager.validateUserAndRole("user", "password", roles, CheckType.CREATE)).andReturn(false);
+ EasyMock.replay(repository);
+ EasyMock.replay(securityManager);
+ EasyMock.replay(serverConnection);
+ securityStore.setSecurityRepository(repository);
+ try
+ {
+ securityStore.check(address, CheckType.CREATE, serverConnection );
+ fail("should throw exception");
+ }
+ catch (Exception e)
+ {
+ //pass
+ }
+ }
+
+ public void testSuccessfulCheckInvalidateCache() throws Exception
+ {
+ JBMSecurityManager securityManager = EasyMock.createStrictMock(JBMSecurityManager.class);
+ securityStore.setSecurityManager(securityManager);
+ //noinspection unchecked
+ HierarchicalRepository<HashSet<Role>> repository = EasyMock.createStrictMock(HierarchicalRepository.class);
+
+ String address = "anaddress";
+ HashSet<Role> roles = new HashSet<Role>();
+ roles.add(new Role("user", false, false, true));
+ repository.registerListener(securityStore);
+ EasyMock.expect(repository.getMatch(address)).andReturn(roles);
+ ServerConnection serverConnection = EasyMock.createNiceMock(ServerConnection.class);
+ EasyMock.expect(serverConnection.getUsername()).andReturn("user");
+ EasyMock.expect(serverConnection.getPassword()).andReturn("password");
+ EasyMock.expect(securityManager.validateUserAndRole("user", "password", roles, CheckType.CREATE)).andReturn(true);
+ EasyMock.expect(repository.getMatch(address)).andReturn(roles);
+ EasyMock.expect(serverConnection.getUsername()).andReturn("user");
+ EasyMock.expect(serverConnection.getPassword()).andReturn("password");
+ EasyMock.expect(securityManager.validateUserAndRole("user", "password", roles, CheckType.CREATE)).andReturn(true);
+ EasyMock.replay(repository);
+ EasyMock.replay(securityManager);
+ EasyMock.replay(serverConnection);
+ securityStore.setSecurityRepository(repository);
+ securityStore.check(address, CheckType.CREATE, serverConnection );
+ securityStore.onChange();
+ securityStore.check(address, CheckType.CREATE, serverConnection );
+
+ }
+ public void testSuccessfulCheckTimeoutCache() throws Exception
+ {
+ securityStore = new SecurityStoreImpl(2000);
+ JBMSecurityManager securityManager = EasyMock.createStrictMock(JBMSecurityManager.class);
+ securityStore.setSecurityManager(securityManager);
+ //noinspection unchecked
+ HierarchicalRepository<HashSet<Role>> repository = EasyMock.createStrictMock(HierarchicalRepository.class);
+
+ String address = "anaddress";
+ HashSet<Role> roles = new HashSet<Role>();
+ roles.add(new Role("user", false, false, true));
+ repository.registerListener(securityStore);
+ EasyMock.expect(repository.getMatch(address)).andReturn(roles);
+ ServerConnection serverConnection = EasyMock.createNiceMock(ServerConnection.class);
+ EasyMock.expect(serverConnection.getUsername()).andReturn("user");
+ EasyMock.expect(serverConnection.getPassword()).andReturn("password");
+ EasyMock.expect(securityManager.validateUserAndRole("user", "password", roles, CheckType.CREATE)).andReturn(true);
+ EasyMock.expect(repository.getMatch(address)).andReturn(roles);
+ EasyMock.expect(serverConnection.getUsername()).andReturn("user");
+ EasyMock.expect(serverConnection.getPassword()).andReturn("password");
+ EasyMock.expect(securityManager.validateUserAndRole("user", "password", roles, CheckType.CREATE)).andReturn(true);
+ EasyMock.replay(repository);
+ EasyMock.replay(securityManager);
+ EasyMock.replay(serverConnection);
+ securityStore.setSecurityRepository(repository);
+ securityStore.check(address, CheckType.CREATE, serverConnection );
+ Thread.sleep(2000);
+ securityStore.check(address, CheckType.CREATE, serverConnection );
+
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/QueueTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/QueueTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/QueueTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/QueueTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,1240 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.server.impl;
+
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+
+import org.easymock.EasyMock;
+import org.jboss.messaging.core.filter.Filter;
+import org.jboss.messaging.core.message.MessageReference;
+import org.jboss.messaging.core.persistence.StorageManager;
+import org.jboss.messaging.core.server.Consumer;
+import org.jboss.messaging.core.server.DistributionPolicy;
+import org.jboss.messaging.core.server.HandleStatus;
+import org.jboss.messaging.core.server.Queue;
+import org.jboss.messaging.core.server.impl.QueueImpl;
+import org.jboss.messaging.core.server.impl.RoundRobinDistributionPolicy;
+import org.jboss.messaging.tests.unit.core.server.impl.fakes.FakeConsumer;
+import org.jboss.messaging.tests.unit.core.server.impl.fakes.FakeFilter;
+import org.jboss.messaging.tests.util.UnitTestCase;
+
+/**
+ *
+ * A QueueTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class QueueTest extends UnitTestCase
+{
+ // The tests ----------------------------------------------------------------
+
+ private final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
+
+ public void testID()
+ {
+ final long id = 123;
+
+ Queue queue = new QueueImpl(id, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ assertEquals(id, queue.getPersistenceID());
+
+ final long id2 = 456;
+
+ queue.setPersistenceID(id2);
+
+ assertEquals(id2, queue.getPersistenceID());
+ }
+
+ public void testName()
+ {
+ final String name = "oobblle";
+
+ Queue queue = new QueueImpl(1, name, null, false, true, false, -1, scheduledExecutor);
+
+ assertEquals(name, queue.getName());
+ }
+
+ public void testClustered()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ assertFalse(queue.isClustered());
+
+ queue = new QueueImpl(1, "queue1", null, true, true, false, -1, scheduledExecutor);
+
+ assertTrue(queue.isClustered());
+ }
+
+ public void testDurable()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, false, false, -1, scheduledExecutor);
+
+ assertFalse(queue.isDurable());
+
+ queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ assertTrue(queue.isDurable());
+ }
+
+ public void testTemporary()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, false, false, -1, scheduledExecutor);
+
+ assertFalse(queue.isTemporary());
+
+ queue = new QueueImpl(1, "queue1", null, false, false, true, -1, scheduledExecutor);
+
+ assertTrue(queue.isTemporary());
+ }
+
+ public void testGetSetMaxSize()
+ {
+ final int maxSize = 123456;
+
+ final int id = 123;
+
+ Queue queue = new QueueImpl(id, "queue1", null, false, true, false, maxSize, scheduledExecutor);
+
+ assertEquals(id, queue.getPersistenceID());
+
+ assertEquals(maxSize, queue.getMaxSize());
+
+ final int maxSize2 = 654321;
+
+ queue.setMaxSize(maxSize2);
+
+ assertEquals(maxSize2, queue.getMaxSize());
+ }
+
+ public void testAddRemoveConsumer()
+ {
+ Consumer cons1 = new FakeConsumer();
+
+ Consumer cons2 = new FakeConsumer();
+
+ Consumer cons3 = new FakeConsumer();
+
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ assertEquals(0, queue.getConsumerCount());
+
+ queue.addConsumer(cons1);
+
+ assertEquals(1, queue.getConsumerCount());
+
+ assertTrue(queue.removeConsumer(cons1));
+
+ assertEquals(0, queue.getConsumerCount());
+
+ queue.addConsumer(cons1);
+
+ queue.addConsumer(cons2);
+
+ queue.addConsumer(cons3);
+
+ assertEquals(3, queue.getConsumerCount());
+
+ assertFalse(queue.removeConsumer(new FakeConsumer()));
+
+ assertEquals(3, queue.getConsumerCount());
+
+ assertTrue(queue.removeConsumer(cons1));
+
+ assertEquals(2, queue.getConsumerCount());
+
+ assertTrue(queue.removeConsumer(cons2));
+
+ assertEquals(1, queue.getConsumerCount());
+
+ assertTrue(queue.removeConsumer(cons3));
+
+ assertEquals(0, queue.getConsumerCount());
+
+ assertFalse(queue.removeConsumer(cons3));
+ }
+
+ public void testGetSetDistributionPolicy()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ assertNotNull(queue.getDistributionPolicy());
+
+ assertTrue(queue.getDistributionPolicy() instanceof RoundRobinDistributionPolicy);
+
+ DistributionPolicy policy = new DummyDistributionPolicy();
+
+ queue.setDistributionPolicy(policy);
+
+ assertEquals(policy, queue.getDistributionPolicy());
+ }
+
+ public void testGetSetFilter()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ assertNull(queue.getFilter());
+
+ Filter filter = new FakeFilter();
+
+ queue.setFilter(filter);
+
+ assertEquals(filter, queue.getFilter());
+
+ queue = new QueueImpl(1, "queue1", filter, false, true, false, -1, scheduledExecutor);
+
+ assertEquals(filter, queue.getFilter());
+ }
+
+ public void testDefaultMaxSize()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ assertEquals(-1, queue.getMaxSize());
+ }
+
+ public void testSimpleAddLast()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ final int numMessages = 10;
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ queue.addLast(ref);
+ }
+
+ assertEquals(numMessages, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(0, queue.getDeliveringCount());
+
+ }
+
+ public void testSimpleDirectDelivery()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ FakeConsumer consumer = new FakeConsumer();
+
+ queue.addConsumer(consumer);
+
+ final int numMessages = 10;
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ assertEquals(numMessages, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(numMessages, queue.getDeliveringCount());
+
+ assertRefListsIdenticalRefs(refs, consumer.getReferences());
+ }
+
+ public void testSimpleNonDirectDelivery()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ final int numMessages = 10;
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ assertEquals(10, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(0, queue.getDeliveringCount());
+
+ //Now add a consumer
+ FakeConsumer consumer = new FakeConsumer();
+
+ queue.addConsumer(consumer);
+
+ assertTrue(consumer.getReferences().isEmpty());
+ assertEquals(10, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+
+ queue.deliver();
+
+ assertRefListsIdenticalRefs(refs, consumer.getReferences());
+ assertEquals(numMessages, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(numMessages, queue.getDeliveringCount());
+ }
+
+ public void testBusyConsumer()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ FakeConsumer consumer = new FakeConsumer();
+
+ consumer.setStatusImmediate(HandleStatus.BUSY);
+
+ queue.addConsumer(consumer);
+
+ final int numMessages = 10;
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ assertEquals(10, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(0, queue.getDeliveringCount());
+
+ queue.deliver();
+
+ assertEquals(10, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(0, queue.getDeliveringCount());
+ assertTrue(consumer.getReferences().isEmpty());
+
+ consumer.setStatusImmediate(HandleStatus.HANDLED);
+
+ queue.deliver();
+
+ assertRefListsIdenticalRefs(refs, consumer.getReferences());
+ assertEquals(10, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(10, queue.getDeliveringCount());
+ }
+
+ public void testBusyConsumerThenAddMoreMessages()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ FakeConsumer consumer = new FakeConsumer();
+
+ consumer.setStatusImmediate(HandleStatus.BUSY);
+
+ queue.addConsumer(consumer);
+
+ final int numMessages = 10;
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ assertEquals(10, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(0, queue.getDeliveringCount());
+
+ queue.deliver();
+
+ assertEquals(10, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(0, queue.getDeliveringCount());
+ assertTrue(consumer.getReferences().isEmpty());
+
+ for (int i = numMessages; i < numMessages * 2; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ assertEquals(20, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(0, queue.getDeliveringCount());
+ assertTrue(consumer.getReferences().isEmpty());
+
+ consumer.setStatusImmediate(HandleStatus.HANDLED);
+
+ for (int i = numMessages * 2; i < numMessages * 3; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ queue.deliver();
+
+ assertRefListsIdenticalRefs(refs, consumer.getReferences());
+ assertEquals(30, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(30, queue.getDeliveringCount());
+ }
+
+ public void testAddFirstAddLast()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ final int numMessages = 10;
+
+ List<MessageReference> refs1 = new ArrayList<MessageReference>();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs1.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ LinkedList<MessageReference> refs2 = new LinkedList<MessageReference>();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i + numMessages);
+
+ refs2.addFirst(ref);
+
+ queue.addFirst(ref);
+ }
+
+ List<MessageReference> refs3 = new ArrayList<MessageReference>();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i + 2 * numMessages);
+
+ refs3.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ FakeConsumer consumer = new FakeConsumer();
+
+ queue.addConsumer(consumer);
+
+ queue.deliver();
+
+ List<MessageReference> allRefs = new ArrayList<MessageReference>();
+
+ allRefs.addAll(refs2);
+ allRefs.addAll(refs1);
+ allRefs.addAll(refs3);
+
+ assertRefListsIdenticalRefs(allRefs, consumer.getReferences());
+ }
+
+
+ public void testChangeConsumersAndDeliver() throws Exception
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ final int numMessages = 10;
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ assertEquals(numMessages, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(0, queue.getDeliveringCount());
+
+ FakeConsumer cons1 = new FakeConsumer();
+
+ queue.addConsumer(cons1);
+
+ queue.deliver();
+
+ assertEquals(numMessages, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(numMessages, queue.getDeliveringCount());
+
+ assertRefListsIdenticalRefs(refs, cons1.getReferences());
+
+ FakeConsumer cons2 = new FakeConsumer();
+
+ queue.addConsumer(cons2);
+
+ assertEquals(2, queue.getConsumerCount());
+
+ cons1.getReferences().clear();
+
+ refs.clear();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ queue.referenceAcknowledged();
+ }
+
+ for (int i = 0; i < 2 * numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ assertEquals(numMessages * 2, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(numMessages * 2, queue.getDeliveringCount());
+
+ assertEquals(numMessages, cons1.getReferences().size());
+
+ assertEquals(numMessages, cons2.getReferences().size());
+
+ cons1.getReferences().clear();
+ cons2.getReferences().clear();
+ refs.clear();
+ for (int i = 0; i < 2 * numMessages; i++)
+ {
+ queue.referenceAcknowledged();
+ }
+
+ FakeConsumer cons3 = new FakeConsumer();
+
+ queue.addConsumer(cons3);
+
+ assertEquals(3, queue.getConsumerCount());
+
+ for (int i = 0; i < 3 * numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ assertEquals(numMessages * 3, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(numMessages * 3, queue.getDeliveringCount());
+
+ assertEquals(numMessages, cons1.getReferences().size());
+
+ assertEquals(numMessages, cons2.getReferences().size());
+
+ assertEquals(numMessages, cons3.getReferences().size());
+
+ queue.removeConsumer(cons1);
+
+ cons3.getReferences().clear();
+ cons2.getReferences().clear();
+ refs.clear();
+ for (int i = 0; i < 3 * numMessages; i++)
+ {
+ queue.referenceAcknowledged();
+ }
+
+ for (int i = 0; i < 2 * numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ assertEquals(numMessages * 2, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(numMessages * 2, queue.getDeliveringCount());
+
+ assertEquals(numMessages, cons2.getReferences().size());
+
+ assertEquals(numMessages, cons3.getReferences().size());
+
+ queue.removeConsumer(cons3);
+
+ cons2.getReferences().clear();
+ refs.clear();
+ for (int i = 0; i < 2 * numMessages; i++)
+ {
+ queue.referenceAcknowledged();
+ }
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ assertEquals(numMessages, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(numMessages, queue.getDeliveringCount());
+
+ assertEquals(numMessages, cons2.getReferences().size());
+
+ }
+
+ public void testConsumerReturningNull()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ class NullConsumer implements Consumer
+ {
+ public HandleStatus handle(MessageReference reference)
+ {
+ return null;
+ }
+ }
+
+ queue.addConsumer(new NullConsumer());
+
+ MessageReference ref = generateReference(queue, 1);
+
+ try
+ {
+ queue.addLast(ref);
+
+ fail("Should throw IllegalStateException");
+ }
+ catch (IllegalStateException e)
+ {
+ //Ok
+ }
+ }
+
+ public void testRoundRobinWithQueueing()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ assertTrue(queue.getDistributionPolicy() instanceof RoundRobinDistributionPolicy);
+
+ final int numMessages = 10;
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ //Test first with queueing
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ FakeConsumer cons1 = new FakeConsumer();
+
+ FakeConsumer cons2 = new FakeConsumer();
+
+ queue.addConsumer(cons1);
+
+ queue.addConsumer(cons2);
+
+ queue.deliver();
+
+ assertEquals(numMessages / 2, cons1.getReferences().size());
+
+ assertEquals(numMessages / 2, cons2.getReferences().size());
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref;
+
+ ref = (i % 2 == 0) ? cons1.getReferences().get(i / 2) : cons2.getReferences().get(i / 2);
+
+ assertEquals(refs.get(i), ref);
+ }
+ }
+
+ public void testRoundRobinDirect()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ assertTrue(queue.getDistributionPolicy() instanceof RoundRobinDistributionPolicy);
+
+ final int numMessages = 10;
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ FakeConsumer cons1 = new FakeConsumer();
+
+ FakeConsumer cons2 = new FakeConsumer();
+
+ queue.addConsumer(cons1);
+
+ queue.addConsumer(cons2);
+
+ queue.deliver();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ assertEquals(numMessages / 2, cons1.getReferences().size());
+
+ assertEquals(numMessages / 2, cons2.getReferences().size());
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref;
+
+ ref = (i % 2 == 0) ? cons1.getReferences().get(i / 2) : cons2.getReferences().get(i / 2);
+
+ assertEquals(refs.get(i), ref);
+ }
+ }
+
+ public void testDeleteAllReferences() throws Exception
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ StorageManager storageManager = EasyMock.createStrictMock(StorageManager.class);
+
+ final int numMessages = 10;
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ ref.getMessage().setDurable(i % 2 == 0);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ //Add some scheduled too
+
+ final int numScheduled = 10;
+
+ for (int i = numMessages; i < numMessages + numScheduled; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ ref.setScheduledDeliveryTime(System.currentTimeMillis() + 1000000000);
+
+ ref.getMessage().setDurable(i % 2 == 0);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+
+ assertEquals(numMessages + numScheduled, queue.getMessageCount());
+ assertEquals(numScheduled, queue.getScheduledCount());
+ assertEquals(0, queue.getDeliveringCount());
+
+ //What I expect to get
+
+ EasyMock.expect(storageManager.generateTransactionID()).andReturn(1L);
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ if (i % 2 == 0)
+ {
+ storageManager.storeDeleteTransactional(1, i);
+ }
+ }
+
+ for (int i = numMessages; i < numMessages + numScheduled; i++)
+ {
+ if (i % 2 == 0)
+ {
+ storageManager.storeDeleteTransactional(1, i);
+ }
+ }
+
+ storageManager.commit(1);
+
+ EasyMock.replay(storageManager);
+
+ queue.deleteAllReferences(storageManager);
+
+ EasyMock.verify(storageManager);
+
+ assertEquals(0, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(0, queue.getDeliveringCount());
+
+ FakeConsumer consumer = new FakeConsumer();
+
+ queue.addConsumer(consumer);
+
+ queue.deliver();
+
+ assertTrue(consumer.getReferences().isEmpty());
+ }
+
+ public void testMaxSize()
+ {
+ final int maxSize = 20;
+
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, maxSize, scheduledExecutor);
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ for (int i = 0; i < maxSize; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs.add(ref);
+
+ assertEquals(HandleStatus.HANDLED, queue.addLast(ref));
+ }
+
+ assertEquals(maxSize, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(0, queue.getDeliveringCount());
+
+ //Try to add more
+
+ for (int i = 0; i < 10; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ assertEquals(HandleStatus.BUSY, queue.addLast(ref));
+ }
+
+ assertEquals(maxSize, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(0, queue.getDeliveringCount());
+
+ // Try to add at front too
+
+ for (int i = 0; i < 10; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ assertEquals(HandleStatus.BUSY, queue.addLast(ref));
+ }
+
+ //Increase the max size
+
+ queue.setMaxSize(2 * queue.getMaxSize());
+
+ for (int i = 0; i < maxSize; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ refs.add(ref);
+
+ assertEquals(HandleStatus.HANDLED, queue.addLast(ref));
+ }
+
+ assertEquals(maxSize * 2, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(0, queue.getDeliveringCount());
+
+ //Now try and decrease maxSize
+
+ try
+ {
+ queue.setMaxSize(maxSize);
+
+ fail("Should throw exception");
+ }
+ catch (IllegalArgumentException e)
+ {
+ //Ok
+ }
+
+ assertEquals(2 * maxSize, queue.getMaxSize());
+ }
+
+ public void testWithPriorities()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ final int numMessages = 10;
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ ref.getMessage().setPriority((byte)i);
+
+ refs.add(ref);
+
+ assertEquals(HandleStatus.HANDLED, queue.addLast(ref));
+ }
+
+ FakeConsumer consumer = new FakeConsumer();
+
+ queue.addConsumer(consumer);
+
+ queue.deliver();
+
+ List<MessageReference> receivedRefs = consumer.getReferences();
+
+ //Should be in reverse order
+
+ assertEquals(refs.size(), receivedRefs.size());
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ assertEquals(refs.get(i), receivedRefs.get(9 - i));
+ }
+
+ //But if we send more - since we are now in direct mode - the order will be the send order
+ //since the refs don't get queued
+
+ consumer.clearReferences();
+
+ refs.clear();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ ref.getMessage().setPriority((byte)i);
+
+ refs.add(ref);
+
+ assertEquals(HandleStatus.HANDLED, queue.addLast(ref));
+ }
+
+ assertRefListsIdenticalRefs(refs, consumer.getReferences());
+ }
+
+ public void testConsumerWithFiltersDirect() throws Exception
+ {
+ testConsumerWithFilters(true);
+ }
+
+ public void testConsumerWithFiltersQueueing() throws Exception
+ {
+ testConsumerWithFilters(false);
+ }
+
+ public void testConsumerWithFilterAddAndRemove()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ Filter filter = new FakeFilter("fruit", "orange");
+
+ FakeConsumer consumer = new FakeConsumer(filter);
+ }
+
+ public void testList()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ final int numMessages = 20;
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ queue.addLast(ref);
+
+ refs.add(ref);
+ }
+
+ assertEquals(numMessages, queue.getMessageCount());
+
+ List<MessageReference> list = queue.list(null);
+
+ assertRefListsIdenticalRefs(refs, list);
+ }
+
+ public void testListWithFilter()
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ final int numMessages = 20;
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ if (i % 2 == 0)
+ {
+ ref.getMessage().putHeader("god", "dog");
+ }
+
+ queue.addLast(ref);
+
+ refs.add(ref);
+ }
+
+ assertEquals(numMessages, queue.getMessageCount());
+
+ Filter filter = new FakeFilter("god", "dog");
+
+ List<MessageReference> list = queue.list(filter);
+
+ assertEquals(numMessages / 2, list.size());
+
+ for (int i = 0; i < numMessages; i += 2)
+ {
+ assertEquals(refs.get(i), list.get(i / 2));
+ }
+ }
+
+ /*
+ public void testQuickSpeedTest()
+ {
+ Queue queue = new QueueImpl(1);
+
+ final int numMessages = 1000000;
+
+ FakeConsumer cons = new FakeConsumer();
+
+ queue.addConsumer(cons);
+
+ long start = System.currentTimeMillis();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = this.generateReference(1);
+
+ queue.addLast(ref);
+ }
+
+ long end = System.currentTimeMillis();
+
+ double rate = 1000 * (double)numMessages / (end - start);
+
+ System.out.println("Rate: " + rate);
+
+ assertEquals(numMessages, cons.getReferences().size());
+ }
+ */
+
+ public void testConsumeWithFiltersAddAndRemoveConsumer() throws Exception
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ Filter filter = new FakeFilter("fruit", "orange");
+
+ FakeConsumer consumer = new FakeConsumer(filter);
+
+ queue.addConsumer(consumer);
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ MessageReference ref1 = generateReference(queue, 1);
+
+ ref1.getMessage().putHeader("fruit", "banana");
+
+ assertEquals(HandleStatus.HANDLED, queue.addLast(ref1));
+
+ MessageReference ref2 = generateReference(queue, 2);
+
+ ref2.getMessage().putHeader("fruit", "orange");
+
+ assertEquals(HandleStatus.HANDLED, queue.addLast(ref2));
+
+ refs.add(ref2);
+
+
+ assertEquals(2, queue.getMessageCount());
+
+ assertEquals(1, consumer.getReferences().size());
+
+ assertEquals(1, queue.getDeliveringCount());
+
+ assertRefListsIdenticalRefs(refs, consumer.getReferences());
+
+ queue.referenceAcknowledged();
+
+ queue.removeConsumer(consumer);
+
+ queue.addConsumer(consumer);
+
+ queue.deliver();
+
+
+ refs.clear();
+
+ consumer.clearReferences();
+
+ MessageReference ref3 = generateReference(queue, 3);
+
+ ref3.getMessage().putHeader("fruit", "banana");
+
+ assertEquals(HandleStatus.HANDLED, queue.addLast(ref3));
+
+ MessageReference ref4 = generateReference(queue, 4);
+
+ ref4.getMessage().putHeader("fruit", "orange");
+
+ assertEquals(HandleStatus.HANDLED, queue.addLast(ref4));
+
+ refs.add(ref4);
+
+ assertEquals(3, queue.getMessageCount());
+
+ assertEquals(1, consumer.getReferences().size());
+
+ assertEquals(1, queue.getDeliveringCount());
+
+ assertRefListsIdenticalRefs(refs, consumer.getReferences());
+ }
+
+ // Private ------------------------------------------------------------------------------
+
+ private void testConsumerWithFilters(boolean direct) throws Exception
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ Filter filter = new FakeFilter("fruit", "orange");
+
+ FakeConsumer consumer = new FakeConsumer(filter);
+
+ if (direct)
+ {
+ queue.addConsumer(consumer);
+ }
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ MessageReference ref1 = generateReference(queue, 1);
+
+ ref1.getMessage().putHeader("fruit", "banana");
+
+ assertEquals(HandleStatus.HANDLED, queue.addLast(ref1));
+
+ MessageReference ref2 = generateReference(queue, 2);
+
+ ref2.getMessage().putHeader("cheese", "stilton");
+
+ assertEquals(HandleStatus.HANDLED, queue.addLast(ref2));
+
+ MessageReference ref3 = generateReference(queue, 3);
+
+ ref3.getMessage().putHeader("cake", "sponge");
+
+ assertEquals(HandleStatus.HANDLED, queue.addLast(ref3));
+
+ MessageReference ref4 = generateReference(queue, 4);
+
+ ref4.getMessage().putHeader("fruit", "orange");
+
+ refs.add(ref4);
+
+ assertEquals(HandleStatus.HANDLED, queue.addLast(ref4));
+
+ MessageReference ref5 = generateReference(queue, 5);
+
+ ref5.getMessage().putHeader("fruit", "apple");
+
+ assertEquals(HandleStatus.HANDLED, queue.addLast(ref5));
+
+ MessageReference ref6 = generateReference(queue, 6);
+
+ ref6.getMessage().putHeader("fruit", "orange");
+
+ refs.add(ref6);
+
+ assertEquals(HandleStatus.HANDLED, queue.addLast(ref6));
+
+ if (!direct)
+ {
+ queue.addConsumer(consumer);
+
+ queue.deliver();
+ }
+
+ assertEquals(6, queue.getMessageCount());
+
+ assertEquals(2, consumer.getReferences().size());
+
+ assertEquals(2, queue.getDeliveringCount());
+
+ assertRefListsIdenticalRefs(refs, consumer.getReferences());
+
+ queue.referenceAcknowledged();
+ queue.referenceAcknowledged();
+
+ queue.removeConsumer(consumer);
+
+ consumer = new FakeConsumer();
+
+ queue.addConsumer(consumer);
+
+ queue.deliver();
+
+ assertEquals(4, queue.getMessageCount());
+
+ assertEquals(4, consumer.getReferences().size());
+
+ assertEquals(4, queue.getDeliveringCount());
+ }
+
+
+
+
+
+
+
+ // Inner classes ---------------------------------------------------------------
+
+ class DummyDistributionPolicy implements DistributionPolicy
+ {
+ public int select(List<Consumer> consumers, int lastPos)
+ {
+ return 0;
+ }
+ }
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/RoundRobinDistributionPolicyTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/RoundRobinDistributionPolicyTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/RoundRobinDistributionPolicyTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/RoundRobinDistributionPolicyTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,74 @@
+package org.jboss.messaging.tests.unit.core.server.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.jboss.messaging.core.server.Consumer;
+import org.jboss.messaging.core.server.DistributionPolicy;
+import org.jboss.messaging.core.server.impl.RoundRobinDistributionPolicy;
+import org.jboss.messaging.tests.unit.core.server.impl.fakes.FakeConsumer;
+import org.jboss.messaging.tests.util.UnitTestCase;
+
+/**
+ *
+ * A RoundRobinDistributionPolicyTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class RoundRobinDistributionPolicyTest extends UnitTestCase
+{
+
+ public void testNoConsumers()
+ {
+ List<Consumer> consumers = new ArrayList<Consumer>();
+
+ DistributionPolicy dp = new RoundRobinDistributionPolicy();
+
+ int pos = dp.select(consumers, -1);
+
+ assertEquals(0, pos);
+ }
+
+ public void testConsumers()
+ {
+ List<Consumer> consumers = new ArrayList<Consumer>();
+
+ consumers.add(new FakeConsumer());
+ consumers.add(new FakeConsumer());
+ consumers.add(new FakeConsumer());
+
+ DistributionPolicy dp = new RoundRobinDistributionPolicy();
+
+ int pos = -1;
+
+ pos = dp.select(consumers, pos);
+
+ assertEquals(0, pos);
+
+ pos = dp.select(consumers, pos);
+
+ assertEquals(1, pos);
+
+ pos = dp.select(consumers, pos);
+
+ assertEquals(2, pos);
+
+ pos = dp.select(consumers, pos);
+
+ assertEquals(0, pos);
+
+ pos = dp.select(consumers, pos);
+
+ assertEquals(1, pos);
+
+ pos = dp.select(consumers, pos);
+
+ assertEquals(2, pos);
+
+ pos = dp.select(consumers, pos);
+
+ assertEquals(0, pos);
+ }
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/concurrent/QueueTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/server/impl/test/concurrent/QueueTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/concurrent/QueueTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/concurrent/QueueTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,205 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.server.impl.concurrent;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.core.message.MessageReference;
+import org.jboss.messaging.core.server.HandleStatus;
+import org.jboss.messaging.core.server.Queue;
+import org.jboss.messaging.core.server.QueueFactory;
+import org.jboss.messaging.tests.unit.core.server.impl.fakes.FakeConsumer;
+import org.jboss.messaging.tests.unit.core.server.impl.fakes.FakeQueueFactory;
+import org.jboss.messaging.tests.util.UnitTestCase;
+
+/**
+ *
+ * A concurrent QueueTest
+ *
+ * All the concurrent queue tests go in here
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class QueueTest extends UnitTestCase
+{
+ private QueueFactory queueFactory = new FakeQueueFactory();
+
+ /*
+ * Concurrent set consumer not busy, busy then, call deliver while messages are being added and consumed
+ */
+ public void testConcurrentAddsDeliver() throws Exception
+ {
+ Queue queue = queueFactory.createQueue(1, "queue1", null, false, true);
+
+ FakeConsumer consumer = new FakeConsumer();
+
+ queue.addConsumer(consumer);
+
+ final long testTime = 5000;
+
+ Sender sender = new Sender(queue, testTime);
+
+ Toggler toggler = new Toggler(queue, consumer, testTime);
+
+ sender.start();
+
+ toggler.start();
+
+ sender.join();
+
+ toggler.join();
+
+ consumer.setStatusImmediate(HandleStatus.HANDLED);
+
+ queue.deliver();
+
+ if (sender.getException() != null)
+ {
+ throw sender.getException();
+ }
+
+ if (toggler.getException() != null)
+ {
+ throw toggler.getException();
+ }
+
+ assertRefListsIdenticalRefs(sender.getReferences(), consumer.getReferences());
+
+ System.out.println("num refs: " + sender.getReferences().size());
+
+ System.out.println("num toggles: " + toggler.getNumToggles());
+
+ }
+
+ // Inner classes ---------------------------------------------------------------
+
+ class Sender extends Thread
+ {
+ private volatile Exception e;
+
+ private Queue queue;
+
+ private long testTime;
+
+ private volatile int i;
+
+ public Exception getException()
+ {
+ return e;
+ }
+
+ private List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ public List<MessageReference> getReferences()
+ {
+ return refs;
+ }
+
+ Sender(Queue queue, long testTime)
+ {
+ this.testTime = testTime;
+
+ this.queue = queue;
+ }
+
+ public void run()
+ {
+ long start = System.currentTimeMillis();
+
+ while (System.currentTimeMillis() - start < testTime)
+ {
+ Message message = generateMessage(i);
+
+ MessageReference ref = message.createReference(queue);
+
+ queue.addLast(ref);
+
+ refs.add(ref);
+
+ i++;
+ }
+ }
+ }
+
+ class Toggler extends Thread
+ {
+ private volatile Exception e;
+
+ private Queue queue;
+
+ private FakeConsumer consumer;
+
+ private long testTime;
+
+ private boolean toggle;
+
+ private volatile int numToggles;
+
+ public int getNumToggles()
+ {
+ return numToggles;
+ }
+
+ public Exception getException()
+ {
+ return e;
+ }
+
+ Toggler(Queue queue, FakeConsumer consumer, long testTime)
+ {
+ this.testTime = testTime;
+
+ this.queue = queue;
+
+ this.consumer = consumer;
+ }
+
+ public void run()
+ {
+ long start = System.currentTimeMillis();
+
+ while (System.currentTimeMillis() - start < testTime)
+ {
+ if (toggle)
+ {
+ consumer.setStatusImmediate(HandleStatus.BUSY);
+ }
+ else
+ {
+ consumer.setStatusImmediate(HandleStatus.HANDLED);
+
+ queue.deliver();
+ }
+ toggle = !toggle;
+
+ numToggles++;
+ }
+ }
+ }
+
+}
+
+
+
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/fakes/FakeConsumer.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/fakes/FakeConsumer.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/fakes/FakeConsumer.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/fakes/FakeConsumer.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,144 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.server.impl.fakes;
+
+import java.util.LinkedList;
+import java.util.List;
+
+import org.jboss.messaging.core.filter.Filter;
+import org.jboss.messaging.core.message.MessageReference;
+import org.jboss.messaging.core.server.Consumer;
+import org.jboss.messaging.core.server.HandleStatus;
+
+/**
+ *
+ * A FakeConsumer
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class FakeConsumer implements Consumer
+{
+ private HandleStatus statusToReturn = HandleStatus.HANDLED;
+
+ private HandleStatus newStatus;
+
+ private int delayCountdown = 0;
+
+ private LinkedList<MessageReference> references = new LinkedList<MessageReference>();
+
+ private Filter filter;
+
+ public FakeConsumer()
+ {
+ }
+
+ public FakeConsumer(Filter filter)
+ {
+ this.filter = filter;
+ }
+
+ public synchronized MessageReference waitForNextReference(long timeout)
+ {
+ while (references.isEmpty() && timeout > 0)
+ {
+ long start = System.currentTimeMillis();
+ try
+ {
+ wait();
+ }
+ catch (InterruptedException e)
+ {
+ }
+ timeout -= (System.currentTimeMillis() - start);
+ }
+
+ if (timeout <= 0)
+ {
+ throw new IllegalStateException("Timed out waiting for reference");
+ }
+
+ return references.removeFirst();
+ }
+
+ public synchronized void setStatusImmediate(HandleStatus newStatus)
+ {
+ this.statusToReturn = newStatus;
+ }
+
+ public synchronized void setStatusDelayed(HandleStatus newStatus, int numReferences)
+ {
+ this.newStatus = newStatus;
+
+ this.delayCountdown = numReferences;
+ }
+
+ public synchronized List<MessageReference> getReferences()
+ {
+ return references;
+ }
+
+ public synchronized void clearReferences()
+ {
+ this.references.clear();
+ }
+
+ public synchronized HandleStatus handle(MessageReference reference)
+ {
+ if (filter != null)
+ {
+ if (filter.match(reference.getMessage()))
+ {
+ references.addLast(reference);
+ notify();
+
+ return HandleStatus.HANDLED;
+ }
+ else
+ {
+ return HandleStatus.NO_MATCH;
+ }
+ }
+
+ if (newStatus != null)
+ {
+ if (delayCountdown == 0)
+ {
+ statusToReturn = newStatus;
+
+ newStatus = null;
+ }
+ else
+ {
+ delayCountdown--;
+ }
+ }
+
+ if (statusToReturn == HandleStatus.HANDLED)
+ {
+ references.addLast(reference);
+ notify();
+ }
+
+ return statusToReturn;
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/fakes/FakeFilter.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/fakes/FakeFilter.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/fakes/FakeFilter.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/fakes/FakeFilter.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,72 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.server.impl.fakes;
+
+import org.jboss.messaging.core.filter.Filter;
+import org.jboss.messaging.core.message.Message;
+
+/**
+ *
+ * A FakeFilter
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class FakeFilter implements Filter
+{
+ private String headerName;
+
+ private Object headerValue;
+
+ public FakeFilter(String headerName, Object headerValue)
+ {
+ this.headerName = headerName;
+
+ this.headerValue = headerValue;
+ }
+
+ public FakeFilter()
+ {
+ }
+
+ public boolean match(Message message)
+ {
+ if (headerName != null)
+ {
+ Object value = message.getHeader(headerName);
+
+ if (value != null && headerValue.equals(value))
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+ return true;
+ }
+
+ public String getFilterString()
+ {
+ return null;
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/fakes/FakeQueueFactory.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/fakes/FakeQueueFactory.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/fakes/FakeQueueFactory.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/fakes/FakeQueueFactory.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,49 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.server.impl.fakes;
+
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+
+import org.jboss.messaging.core.filter.Filter;
+import org.jboss.messaging.core.server.Queue;
+import org.jboss.messaging.core.server.QueueFactory;
+import org.jboss.messaging.core.server.impl.QueueImpl;
+
+/**
+ *
+ * A FakeQueueFactory
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class FakeQueueFactory implements QueueFactory
+{
+ private final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
+
+ public Queue createQueue(long persistenceID, String name, Filter filter,
+ boolean durable, boolean temporary)
+ {
+ return new QueueImpl(persistenceID, name, filter, false, durable, temporary, -1, scheduledExecutor);
+ }
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/timing/QueueTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/server/impl/test/timing/QueueTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/timing/QueueTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/timing/QueueTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,337 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.server.impl.timing;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+
+import org.easymock.EasyMock;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.message.MessageReference;
+import org.jboss.messaging.core.persistence.StorageManager;
+import org.jboss.messaging.core.server.Queue;
+import org.jboss.messaging.core.server.impl.QueueImpl;
+import org.jboss.messaging.tests.unit.core.server.impl.fakes.FakeConsumer;
+import org.jboss.messaging.tests.util.UnitTestCase;
+
+/**
+ *
+ * A timing-sensitive QueueTest
+ *
+ * All the queue tests which are timing sensitive - go in here
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class QueueTest extends UnitTestCase
+{
+ private static final long TIMEOUT = 10000;
+
+ private static final Logger log = Logger.getLogger(QueueTest.class);
+
+ private ScheduledExecutorService scheduledExecutor;
+
+ public void setUp() throws Exception
+ {
+ super.setUp();
+
+ scheduledExecutor = new ScheduledThreadPoolExecutor(1);
+ }
+
+ public void tearDown() throws Exception
+ {
+ super.tearDown();
+
+ scheduledExecutor.shutdownNow();
+ }
+
+ // The tests ----------------------------------------------------------------
+
+ public void testScheduledDirect()
+ {
+ testScheduled(true);
+ }
+
+ public void testScheduledQueueing()
+ {
+ testScheduled(false);
+ }
+
+ public void testScheduledNoConsumer() throws Exception
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ //Send one scheduled
+
+ long now = System.currentTimeMillis();
+
+ MessageReference ref1 = generateReference(queue, 1);
+ ref1.setScheduledDeliveryTime(now + 7000);
+ queue.addLast(ref1);
+
+ //Send some non scheduled messages
+
+ MessageReference ref2 = generateReference(queue, 2);
+ queue.addLast(ref2);
+ MessageReference ref3 = generateReference(queue, 3);
+ queue.addLast(ref3);
+ MessageReference ref4 = generateReference(queue, 4);
+ queue.addLast(ref4);
+
+
+ //Now send some more scheduled messages
+
+ MessageReference ref5 = generateReference(queue, 5);
+ ref5.setScheduledDeliveryTime(now + 5000);
+ queue.addLast(ref5);
+
+ MessageReference ref6 = generateReference(queue, 6);
+ ref6.setScheduledDeliveryTime(now + 4000);
+ queue.addLast(ref6);
+
+ MessageReference ref7 = generateReference(queue, 7);
+ ref7.setScheduledDeliveryTime(now + 3000);
+ queue.addLast(ref7);
+
+ MessageReference ref8 = generateReference(queue, 8);
+ ref8.setScheduledDeliveryTime(now + 6000);
+ queue.addLast(ref8);
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ //Scheduled refs are added back to *FRONT* of queue - otherwise if there were many messages in the queue
+ //They may get stranded behind a big backlog
+
+ refs.add(ref1);
+ refs.add(ref8);
+ refs.add(ref5);
+ refs.add(ref6);
+ refs.add(ref7);
+
+ refs.add(ref2);
+ refs.add(ref3);
+ refs.add(ref4);
+
+ Thread.sleep(7500);
+
+ FakeConsumer consumer = new FakeConsumer();
+
+ queue.addConsumer(consumer);
+
+ queue.deliver();
+
+ assertRefListsIdenticalRefs(refs, consumer.getReferences());
+ }
+
+ private void testScheduled(boolean direct)
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ FakeConsumer consumer = null;
+
+ if (direct)
+ {
+ consumer = new FakeConsumer();
+
+ queue.addConsumer(consumer);
+ }
+
+ //Send one scheduled
+
+ long now = System.currentTimeMillis();
+
+ MessageReference ref1 = generateReference(queue, 1);
+ ref1.setScheduledDeliveryTime(now + 7000);
+ queue.addLast(ref1);
+
+ //Send some non scheduled messages
+
+ MessageReference ref2 = generateReference(queue, 2);
+ queue.addLast(ref2);
+ MessageReference ref3 = generateReference(queue, 3);
+ queue.addLast(ref3);
+ MessageReference ref4 = generateReference(queue, 4);
+ queue.addLast(ref4);
+
+
+ //Now send some more scheduled messages
+
+ MessageReference ref5 = generateReference(queue, 5);
+ ref5.setScheduledDeliveryTime(now + 5000);
+ queue.addLast(ref5);
+
+ MessageReference ref6 = generateReference(queue, 6);
+ ref6.setScheduledDeliveryTime(now + 4000);
+ queue.addLast(ref6);
+
+ MessageReference ref7 = generateReference(queue, 7);
+ ref7.setScheduledDeliveryTime(now + 3000);
+ queue.addLast(ref7);
+
+ MessageReference ref8 = generateReference(queue, 8);
+ ref8.setScheduledDeliveryTime(now + 6000);
+ queue.addLast(ref8);
+
+ if (!direct)
+ {
+ consumer = new FakeConsumer();
+
+ queue.addConsumer(consumer);
+
+ queue.deliver();
+ }
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ refs.add(ref2);
+ refs.add(ref3);
+ refs.add(ref4);
+
+ assertRefListsIdenticalRefs(refs, consumer.getReferences());
+
+ refs.clear();
+ consumer.getReferences().clear();
+
+ MessageReference ref = consumer.waitForNextReference(TIMEOUT);
+ assertEquals(ref7, ref);
+ long now2 = System.currentTimeMillis();
+ assertTrue(now2 - now >= 3000);
+
+ ref = consumer.waitForNextReference(TIMEOUT);
+ assertEquals(ref6, ref);
+ now2 = System.currentTimeMillis();
+ assertTrue(now2 - now >= 4000);
+
+ ref = consumer.waitForNextReference(TIMEOUT);
+ assertEquals(ref5, ref);
+ now2 = System.currentTimeMillis();
+ assertTrue(now2 - now >= 5000);
+
+ ref = consumer.waitForNextReference(TIMEOUT);
+ assertEquals(ref8, ref);
+ now2 = System.currentTimeMillis();
+ assertTrue(now2 - now >= 6000);
+
+ ref = consumer.waitForNextReference(TIMEOUT);
+ assertEquals(ref1, ref);
+ now2 = System.currentTimeMillis();
+ assertTrue(now2 - now >= 7000);
+
+ assertTrue(consumer.getReferences().isEmpty());
+ }
+
+ public void testDeleteAllReferences() throws Exception
+ {
+ Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ StorageManager storageManager = EasyMock.createStrictMock(StorageManager.class);
+
+ final int numMessages = 10;
+
+ List<MessageReference> refs = new ArrayList<MessageReference>();
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ ref.getMessage().setDurable(i % 2 == 0);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+ //Add some scheduled too
+
+ final long waitTime = 2000;
+
+ final int numScheduled = 10;
+
+ for (int i = numMessages; i < numMessages + numScheduled; i++)
+ {
+ MessageReference ref = generateReference(queue, i);
+
+ ref.setScheduledDeliveryTime(System.currentTimeMillis() + waitTime);
+
+ ref.getMessage().setDurable(i % 2 == 0);
+
+ refs.add(ref);
+
+ queue.addLast(ref);
+ }
+
+
+ assertEquals(numMessages + numScheduled, queue.getMessageCount());
+ assertEquals(numScheduled, queue.getScheduledCount());
+ assertEquals(0, queue.getDeliveringCount());
+
+ //What I expect to get
+
+ EasyMock.expect(storageManager.generateTransactionID()).andReturn(1L);
+
+ for (int i = 0; i < numMessages; i++)
+ {
+ if (i % 2 == 0)
+ {
+ storageManager.storeDeleteTransactional(1, i);
+ }
+ }
+
+ for (int i = numMessages; i < numMessages + numScheduled; i++)
+ {
+ if (i % 2 == 0)
+ {
+ storageManager.storeDeleteTransactional(1, i);
+ }
+ }
+
+ storageManager.commit(1);
+
+ EasyMock.replay(storageManager);
+
+ queue.deleteAllReferences(storageManager);
+
+ EasyMock.verify(storageManager);
+
+ assertEquals(0, queue.getMessageCount());
+ assertEquals(0, queue.getScheduledCount());
+ assertEquals(0, queue.getDeliveringCount());
+
+ Thread.sleep(waitTime + 500);
+
+ //Make sure scheduled don't arrive
+
+ FakeConsumer consumer = new FakeConsumer();
+
+ queue.addConsumer(consumer);
+
+ queue.deliver();
+
+ assertTrue(consumer.getReferences().isEmpty());
+ }
+
+ // Inner classes ---------------------------------------------------------------
+
+}
+
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/QueueSettingsTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/settings/impl/test/unit/QueueSettingsTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/QueueSettingsTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/QueueSettingsTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,146 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.settings.impl;
+
+import junit.framework.TestCase;
+import org.jboss.messaging.core.server.Queue;
+import org.jboss.messaging.core.server.impl.QueueImpl;
+import org.jboss.messaging.core.server.impl.RoundRobinDistributionPolicy;
+import org.jboss.messaging.core.settings.impl.QueueSettings;
+
+/**
+ * @author <a href="ataylor at redhat.com">Andy Taylor</a>
+ */
+public class QueueSettingsTest extends TestCase
+{
+ public void testDefaults()
+ {
+ QueueSettings queueSettings = new QueueSettings();
+ assertEquals(queueSettings.getDistributionPolicy().getClass(), QueueSettings.DEFAULT_DISTRIBUTION_POLICY.getClass());
+ assertEquals(queueSettings.getDistributionPolicyClass(), null);
+ assertEquals(queueSettings.getDLQ(), null);
+ assertEquals(queueSettings.isClustered(), Boolean.valueOf(false));
+ assertEquals(queueSettings.getExpiryQueue(), null);
+ assertEquals(queueSettings.getMaxDeliveryAttempts(), QueueSettings.DEFAULT_MAX_DELIVERY_ATTEMPTS);
+ assertEquals(queueSettings.getMaxSize(), QueueSettings.DEFAULT_MAX_SIZE);
+ assertEquals(queueSettings.getMessageCounterHistoryDayLimit(), QueueSettings.DEFAULT_MESSAGE_COUNTER_HISTORY_DAY_LIMIT);
+ assertEquals(queueSettings.getRedeliveryDelay(), QueueSettings.DEFAULT_REDELIVER_DELAY);
+
+ }
+
+ public void testSingleMerge()
+ {
+ QueueSettings queueSettings = new QueueSettings();
+ QueueSettings queueSettingsToMerge = new QueueSettings();
+ queueSettingsToMerge.setClustered(true);
+ Queue DLQ = new QueueImpl(0,"testDLQ", null, false, false, false, 0, null);
+ Queue exp = new QueueImpl(0,"testExpiryQueue", null, false, false, false, 0, null);
+ queueSettingsToMerge.setDLQ(DLQ);
+ queueSettingsToMerge.setExpiryQueue(exp);
+ queueSettingsToMerge.setMaxDeliveryAttempts(1000);
+ queueSettingsToMerge.setMaxSize(1001);
+ queueSettingsToMerge.setMessageCounterHistoryDayLimit(1002);
+ queueSettingsToMerge.setRedeliveryDelay((long)1003);
+ queueSettings.merge(queueSettingsToMerge);
+ assertEquals(queueSettings.getDistributionPolicy().getClass(), QueueSettings.DEFAULT_DISTRIBUTION_POLICY.getClass());
+ assertEquals(queueSettings.getDistributionPolicyClass(), null);
+ assertEquals(queueSettings.isClustered(), Boolean.valueOf(true));
+ assertEquals(queueSettings.getDLQ(), DLQ);
+ assertEquals(queueSettings.getExpiryQueue(), exp);
+ assertEquals(queueSettings.getMaxDeliveryAttempts(), Integer.valueOf(1000));
+ assertEquals(queueSettings.getMaxSize(), Integer.valueOf(1001));
+ assertEquals(queueSettings.getMessageCounterHistoryDayLimit(), Integer.valueOf(1002));
+ assertEquals(queueSettings.getRedeliveryDelay(), Long.valueOf(1003));
+ }
+
+ public void testMultipleMerge()
+ {
+ QueueSettings queueSettings = new QueueSettings();
+ QueueSettings queueSettingsToMerge = new QueueSettings();
+ queueSettingsToMerge.setClustered(true);
+ Queue DLQ = new QueueImpl(0,"testDLQ", null, false, false, false, 0, null);
+ Queue exp = new QueueImpl(0,"testExpiryQueue", null, false, false, false, 0, null);
+ queueSettingsToMerge.setDLQ(DLQ);
+ queueSettingsToMerge.setExpiryQueue(exp);
+ queueSettingsToMerge.setMaxDeliveryAttempts(1000);
+ queueSettingsToMerge.setMaxSize(1001);
+ queueSettingsToMerge.setMessageCounterHistoryDayLimit(1002);
+ queueSettingsToMerge.setRedeliveryDelay((long)1003);
+ queueSettings.merge(queueSettingsToMerge);
+
+ QueueSettings queueSettingsToMerge2 = new QueueSettings();
+ queueSettingsToMerge2.setClustered(true);
+ Queue exp2 = new QueueImpl(0,"testExpiryQueue2", null, false, false, false, 0, null);
+ queueSettingsToMerge2.setExpiryQueue(exp2);
+ queueSettingsToMerge2.setMaxSize(2001);
+ queueSettingsToMerge2.setRedeliveryDelay((long)2003);
+ queueSettings.merge(queueSettingsToMerge2);
+
+ assertEquals(queueSettings.getDistributionPolicy().getClass(), QueueSettings.DEFAULT_DISTRIBUTION_POLICY.getClass());
+ assertEquals(queueSettings.getDistributionPolicyClass(), null);
+ assertEquals(queueSettings.isClustered(), Boolean.valueOf(true));
+ assertEquals(queueSettings.getDLQ(), DLQ);
+ assertEquals(queueSettings.getExpiryQueue(), exp2);
+ assertEquals(queueSettings.getMaxDeliveryAttempts(), Integer.valueOf(1000));
+ assertEquals(queueSettings.getMaxSize(), Integer.valueOf(2001));
+ assertEquals(queueSettings.getMessageCounterHistoryDayLimit(), Integer.valueOf(1002));
+ assertEquals(queueSettings.getRedeliveryDelay(), Long.valueOf(2003));
+ }
+
+ public void testMultipleMergeAll()
+ {
+ QueueSettings queueSettings = new QueueSettings();
+ QueueSettings queueSettingsToMerge = new QueueSettings();
+ queueSettingsToMerge.setClustered(true);
+ Queue DLQ = new QueueImpl(0,"testDLQ", null, false, false, false, 0, null);
+ Queue exp = new QueueImpl(0,"testExpiryQueue", null, false, false, false, 0, null);
+ queueSettingsToMerge.setDLQ(DLQ);
+ queueSettingsToMerge.setExpiryQueue(exp);
+ queueSettingsToMerge.setMaxDeliveryAttempts(1000);
+ queueSettingsToMerge.setMaxSize(1001);
+ queueSettingsToMerge.setMessageCounterHistoryDayLimit(1002);
+ queueSettingsToMerge.setRedeliveryDelay((long)1003);
+ queueSettings.merge(queueSettingsToMerge);
+
+ QueueSettings queueSettingsToMerge2 = new QueueSettings();
+ queueSettingsToMerge2.setClustered(false);
+ Queue exp2 = new QueueImpl(0,"testExpiryQueue2", null, false, false, false, 0, null);
+ Queue DLQ2 = new QueueImpl(0,"testDlq2", null, false, false, false, 0, null);
+ queueSettingsToMerge2.setExpiryQueue(exp2);
+ queueSettingsToMerge2.setDLQ(DLQ2);
+ queueSettingsToMerge2.setMaxDeliveryAttempts(2000);
+ queueSettingsToMerge2.setMaxSize(2001);
+ queueSettingsToMerge2.setMessageCounterHistoryDayLimit(2002);
+ queueSettingsToMerge2.setRedeliveryDelay((long)2003);
+ queueSettings.merge(queueSettingsToMerge2);
+
+ assertEquals(queueSettings.getDistributionPolicy().getClass(), QueueSettings.DEFAULT_DISTRIBUTION_POLICY.getClass());
+ assertEquals(queueSettings.getDistributionPolicyClass(), null);
+ assertEquals(queueSettings.isClustered(), Boolean.valueOf(true));
+ assertEquals(queueSettings.getDLQ(), DLQ2);
+ assertEquals(queueSettings.getExpiryQueue(), exp2);
+ assertEquals(queueSettings.getMaxDeliveryAttempts(), Integer.valueOf(2000));
+ assertEquals(queueSettings.getMaxSize(), Integer.valueOf(2001));
+ assertEquals(queueSettings.getMessageCounterHistoryDayLimit(), Integer.valueOf(2002));
+ assertEquals(queueSettings.getRedeliveryDelay(), Long.valueOf(2003));
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/RepositoryTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/settings/impl/test/unit/RepositoryTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/RepositoryTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/RepositoryTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,213 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.settings.impl;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.security.Role;
+import org.jboss.messaging.core.settings.HierarchicalRepository;
+import org.jboss.messaging.core.settings.Mergeable;
+import org.jboss.messaging.core.settings.impl.HierarchicalObjectRepository;
+
+/**
+ * @author <a href="ataylor at redhat.com">Andy Taylor</a>
+ */
+public class RepositoryTest extends TestCase
+{
+ HierarchicalRepository<HashSet<Role>> securityRepository;
+
+
+ protected void setUp() throws Exception
+ {
+ securityRepository = new HierarchicalObjectRepository<HashSet<Role>>();
+ }
+
+ public void testDefault()
+ {
+ securityRepository.setDefault(new HashSet<Role>());
+ HashSet<Role> roles = securityRepository.getMatch("queues.something");
+
+ assertEquals(roles.size(), 0);
+ }
+
+ public void testSingleMatch()
+ {
+ securityRepository.addMatch("queues.*", new HashSet<Role>());
+ HashSet<Role> hashSet = securityRepository.getMatch("queues.something");
+ assertEquals(hashSet.size(), 0);
+ }
+
+ public void testSingletwo()
+ {
+ securityRepository.addMatch("queues.another.aq.*", new HashSet<Role>());
+ HashSet<Role> roles = new HashSet<Role>(2);
+ roles.add(new Role("test1"));
+ roles.add(new Role("test2"));
+ securityRepository.addMatch("queues.aq", roles);
+ HashSet<Role> roles2 = new HashSet<Role>(2);
+ roles2.add(new Role("test1"));
+ roles2.add(new Role("test2"));
+ roles2.add(new Role("test3"));
+ securityRepository.addMatch("queues.another.andanother", roles2);
+
+ HashSet<Role> hashSet = securityRepository.getMatch("queues.another.andanother");
+ assertEquals(hashSet.size(), 3);
+ }
+
+ public void testWithoutWildcard()
+ {
+ securityRepository.addMatch("queues.1.*", new HashSet<Role>());
+ HashSet<Role> roles = new HashSet<Role>(2);
+ roles.add(new Role("test1"));
+ roles.add(new Role("test2"));
+ securityRepository.addMatch("queues.2.aq", roles);
+ HashSet<Role> hashSet = securityRepository.getMatch("queues.2.aq");
+ assertEquals(hashSet.size(), 2);
+ }
+
+ public void testMultipleWildcards()
+ {
+ HierarchicalRepository<String> repository = new HierarchicalObjectRepository<String>();
+ repository.addMatch("*", "*");
+ repository.addMatch("a", "a");
+ repository.addMatch("a.*", "a.*");
+ repository.addMatch("a.^", "a.^");
+ repository.addMatch("a.b.c", "a.b.c");
+ repository.addMatch("a.^.c", "a.^.c");
+ repository.addMatch("a.d.c", "a.d.c");
+ repository.addMatch("a.b.*", "a.b.*");
+ repository.addMatch("a.b", "a.b");
+ repository.addMatch("a.b.c.*", "a.b.c.*");
+ repository.addMatch("a.b.c.d", "a.b.c.d");
+ repository.addMatch("a.^.^.d", "a.^.^.d");
+ repository.addMatch("a.^.d.*", "a.^.d.*");
+ String val = repository.getMatch("a");
+ assertEquals("a", val);
+ val = repository.getMatch("a.b");
+ assertEquals("a.b", val);
+ val = repository.getMatch("a.x");
+ assertEquals("a.^", val);
+ val = repository.getMatch("a.b.x");
+ assertEquals("a.b.*", val);
+ val = repository.getMatch("a.b.c");
+ assertEquals("a.b.c", val);
+ val = repository.getMatch("a.d.c");
+ assertEquals("a.d.c", val);
+ val = repository.getMatch("a.x.c");
+ assertEquals("a.^.c", val);
+ val = repository.getMatch("a.b.c.d");
+ assertEquals("a.b.c.d", val);
+ val = repository.getMatch("a.x.c.d");
+ assertEquals("a.^.^.d", val);
+ val = repository.getMatch("a.b.x.d");
+ assertEquals("a.^.^.d", val);
+ val = repository.getMatch("a.d.x.d");
+ assertEquals("a.^.^.d", val);
+ val = repository.getMatch("a.d.d.g");
+ assertEquals("a.^.d.*", val);
+ val = repository.getMatch("zzzz.z.z.z.d.r.g.f.sd.s.fsdfd.fsdfs");
+ assertEquals("*", val);
+ }
+
+ public void testRepositoryMerge()
+ {
+ HierarchicalRepository<DummyMergeable> repository = new HierarchicalObjectRepository<DummyMergeable>();
+ repository.addMatch("*", new DummyMergeable(1));
+ repository.addMatch("a.*", new DummyMergeable(2));
+ repository.addMatch("b.*", new DummyMergeable(3));
+ repository.addMatch("a.b.*", new DummyMergeable(4));
+ repository.addMatch("b.c.*", new DummyMergeable(5));
+ repository.addMatch("a.b.c.*", new DummyMergeable(6));
+ repository.addMatch("a.b.^.d", new DummyMergeable(7));
+ repository.addMatch("a.b.c.^", new DummyMergeable(8));
+ repository.getMatch("a.b.c.d");
+ assertEquals(5, DummyMergeable.timesMerged);
+ assertTrue(DummyMergeable.contains(1));
+ assertTrue(DummyMergeable.contains(2));
+ assertTrue(DummyMergeable.contains(4));
+ assertTrue(DummyMergeable.contains(7));
+ assertTrue(DummyMergeable.contains(8));
+ DummyMergeable.reset();
+ repository.getMatch("a.b.c");
+ assertEquals(2, DummyMergeable.timesMerged);
+ assertTrue(DummyMergeable.contains(1));
+ assertTrue(DummyMergeable.contains(2));
+ assertTrue(DummyMergeable.contains(4));
+ DummyMergeable.reset();
+ repository.getMatch("a");
+ assertEquals(0, DummyMergeable.timesMerged);
+ DummyMergeable.reset();
+ }
+
+ public void testIllegalMatches()
+ {
+ HierarchicalRepository<String> repository = new HierarchicalObjectRepository<String>();
+ try
+ {
+ repository.addMatch("hjhjhjhjh.*.hhh", "test");
+ }
+ catch (IllegalArgumentException e)
+ {
+ //pass
+ }
+ try
+ {
+ repository.addMatch(null, "test");
+ }
+ catch (IllegalArgumentException e)
+ {
+ //pass
+ }
+ }
+
+ static class DummyMergeable implements Mergeable
+ {
+ static int timesMerged = 0;
+ static ArrayList<Integer> merged = new ArrayList<Integer>();
+ private Integer id;
+
+ static void reset()
+ {
+ timesMerged = 0;
+ DummyMergeable.merged = new ArrayList<Integer>();
+ }
+
+ static boolean contains(Integer i)
+ {
+ return DummyMergeable.merged.contains(i);
+ }
+ public DummyMergeable(Integer id)
+ {
+ this.id = id;
+ }
+
+ public void merge(Object merged)
+ {
+ timesMerged++;
+ DummyMergeable.merged.add(id);
+ DummyMergeable.merged.add(((DummyMergeable)merged).id);
+ }
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/MessagingXidTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/transaction/impl/test/unit/MessagingXidTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/MessagingXidTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/MessagingXidTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,161 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.transaction.impl;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+
+import javax.transaction.xa.Xid;
+
+import org.jboss.messaging.core.transaction.impl.XidImpl;
+import org.jboss.messaging.tests.util.RandomUtil;
+import org.jboss.messaging.tests.util.UnitTestCase;
+
+/**
+ *
+ * A MessagingXidTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class MessagingXidTest extends UnitTestCase
+{
+ public void testSerialize() throws Exception
+ {
+ XidImpl xid = new XidImpl(RandomUtil.randomBytes(), RandomUtil.randomInt(),
+ RandomUtil.randomBytes());
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+
+ oos.writeObject(xid);
+
+ oos.flush();
+
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
+
+ Object obj = ois.readObject();
+
+ assertTrue(obj instanceof XidImpl);
+
+ XidImpl xid2 = (XidImpl)obj;
+
+ assertXidsEquivalent(xid, xid2);
+
+ assertEquals(xid, xid2);
+ }
+
+ public void testStandardConstructor()
+ {
+ byte[] bq = RandomUtil.randomBytes();
+
+ byte[] globalTXID = RandomUtil.randomBytes();
+
+ int formatID = RandomUtil.randomInt();
+
+ XidImpl xid1 = new XidImpl(bq, formatID, globalTXID);
+
+ assertByteArraysEquivalent(bq, xid1.getBranchQualifier());
+
+ assertByteArraysEquivalent(globalTXID, xid1.getGlobalTransactionId());
+
+ assertEquals(formatID, xid1.getFormatId());
+ }
+
+ public void testCopyConstructor()
+ {
+ XidImpl xid1 = new XidImpl(RandomUtil.randomBytes(), RandomUtil.randomInt(),
+ RandomUtil.randomBytes());
+
+ XidImpl xid2 = new XidImpl(xid1);
+
+ assertXidsEquivalent(xid1, xid2);
+
+ assertEquals(xid2, xid2);
+ }
+
+ public void testEqualsWithForeign()
+ {
+ XidImpl xid1 = new XidImpl(RandomUtil.randomBytes(), RandomUtil.randomInt(),
+ RandomUtil.randomBytes());
+
+ Xid foreign = new ForeignXid(xid1.getBranchQualifier(), xid1.getFormatId(), xid1.getGlobalTransactionId());
+
+ assertTrue(xid1.equals(foreign));
+
+ foreign = new ForeignXid(RandomUtil.randomBytes(), RandomUtil.randomInt(),
+ RandomUtil.randomBytes());
+
+ assertFalse(xid1.equals(foreign));
+
+ }
+
+ // Private ---------------------------------------------------------------------------------
+
+ private void assertXidsEquivalent(Xid xid1, Xid xid2)
+ {
+ assertByteArraysEquivalent(xid1.getBranchQualifier(), xid2.getBranchQualifier());
+
+ assertEquals(xid1.getFormatId(), xid2.getFormatId());
+
+ assertByteArraysEquivalent(xid1.getGlobalTransactionId(), xid2.getGlobalTransactionId());
+ }
+
+ // Inner classes ---------------------------------------------------------------------------
+
+ class ForeignXid implements Xid
+ {
+ private byte[] branchQualifier;
+
+ private int formatId;
+
+ private byte[] globalTransactionId;
+
+ public ForeignXid(byte[] branchQualifier, int formatId, byte[] globalTransactionId)
+ {
+ this.branchQualifier = branchQualifier;
+ this.formatId = formatId;
+ this.globalTransactionId = globalTransactionId;
+ }
+
+ public byte[] getBranchQualifier()
+ {
+ return this.branchQualifier;
+ }
+
+ public int getFormatId()
+ {
+ return this.formatId;
+ }
+
+ public byte[] getGlobalTransactionId()
+ {
+ return this.globalTransactionId;
+ }
+
+ }
+
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/TransactionTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/transaction/impl/test/unit/TransactionTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/TransactionTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/TransactionTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,642 @@
+package org.jboss.messaging.tests.unit.core.transaction.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+
+import javax.transaction.xa.Xid;
+
+import org.easymock.EasyMock;
+import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.core.message.MessageReference;
+import org.jboss.messaging.core.persistence.StorageManager;
+import org.jboss.messaging.core.postoffice.PostOffice;
+import org.jboss.messaging.core.server.Queue;
+import org.jboss.messaging.core.server.impl.QueueImpl;
+import org.jboss.messaging.core.settings.HierarchicalRepository;
+import org.jboss.messaging.core.settings.impl.HierarchicalObjectRepository;
+import org.jboss.messaging.core.settings.impl.QueueSettings;
+import org.jboss.messaging.core.transaction.Transaction;
+import org.jboss.messaging.core.transaction.impl.TransactionImpl;
+import org.jboss.messaging.tests.util.UnitTestCase;
+
+/**
+ *
+ * A TransactionTest
+ *
+ * TODO test with persistent and non persistent
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class TransactionTest extends UnitTestCase
+{
+ private final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
+
+ private final HierarchicalRepository<QueueSettings> queueSettings =
+ new HierarchicalObjectRepository<QueueSettings>();
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+
+ queueSettings.setDefault(new QueueSettings());
+ }
+
+ public void testNonXAConstructor() throws Exception
+ {
+ StorageManager sm = EasyMock.createStrictMock(StorageManager.class);
+
+ PostOffice po = EasyMock.createStrictMock(PostOffice.class);
+
+ final long txID = 123L;
+
+ EasyMock.expect(sm.generateTransactionID()).andReturn(txID);
+
+ EasyMock.replay(sm);
+
+ Transaction tx = new TransactionImpl(sm, po);
+
+ EasyMock.verify(sm);
+
+ assertEquals(txID, tx.getID());
+
+ assertNull(tx.getXid());
+
+ assertEquals(0, tx.getAcknowledgementsCount());
+
+ assertTrue(tx.isEmpty());
+ }
+
+ public void testXAConstructor() throws Exception
+ {
+ StorageManager sm = EasyMock.createStrictMock(StorageManager.class);
+
+ PostOffice po = EasyMock.createStrictMock(PostOffice.class);
+
+ final long txID = 123L;
+
+ EasyMock.expect(sm.generateTransactionID()).andReturn(txID);
+
+ EasyMock.replay(sm);
+
+ Xid xid = generateXid();
+
+ Transaction tx = new TransactionImpl(xid, sm, po);
+
+ EasyMock.verify(sm);
+
+ assertEquals(txID, tx.getID());
+
+ assertEquals(xid, tx.getXid());
+
+ assertEquals(0, tx.getAcknowledgementsCount());
+
+ assertTrue(tx.isEmpty());
+ }
+
+ public void testState() throws Exception
+ {
+ Transaction tx = createTransaction();
+
+ assertEquals(Transaction.State.ACTIVE, tx.getState());
+
+ tx.suspend();
+
+ assertEquals(Transaction.State.SUSPENDED, tx.getState());
+
+ tx.resume();
+
+ assertEquals(Transaction.State.ACTIVE, tx.getState());
+
+ tx.commit();
+
+ assertEquals(Transaction.State.COMMITTED, tx.getState());
+
+ HierarchicalRepository<QueueSettings> repos = EasyMock.createStrictMock(HierarchicalRepository.class);
+
+ try
+ {
+ tx.rollback(repos);
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.commit();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.prepare();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.suspend();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.resume();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ tx = createTransaction();
+
+ assertEquals(Transaction.State.ACTIVE, tx.getState());
+
+ tx.rollback(repos);
+
+ try
+ {
+ tx.rollback(repos);
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.commit();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.prepare();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.suspend();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.resume();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ tx = createTransaction();
+
+ assertEquals(Transaction.State.ACTIVE, tx.getState());
+
+ try
+ {
+ tx.prepare();
+
+ fail("Should throw exception");
+ }
+ catch (Exception e)
+ {
+ //OK
+ }
+
+
+ tx = createTransactionXA();
+
+ assertEquals(Transaction.State.ACTIVE, tx.getState());
+
+ tx.prepare();
+
+ tx.commit();
+
+ try
+ {
+ tx.rollback(repos);
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.commit();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.prepare();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.suspend();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.resume();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ tx = createTransactionXA();
+
+ assertEquals(Transaction.State.ACTIVE, tx.getState());
+
+ tx.prepare();
+
+ tx.rollback(repos);
+
+ try
+ {
+ tx.rollback(repos);
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.commit();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.prepare();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.suspend();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+
+ try
+ {
+ tx.resume();
+
+ fail("Should throw exception");
+ }
+ catch (IllegalStateException e)
+ {
+ //OK
+ }
+ }
+
+ public void testSendCommit() throws Exception
+ {
+ //Durable queue
+ Queue queue1 = new QueueImpl(12, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ //Durable queue
+ Queue queue2 = new QueueImpl(34, "queue2", null, false, true, false, -1, scheduledExecutor);
+
+ //Non durable queue
+ Queue queue3 = new QueueImpl(65, "queue3", null, false, false, false, -1, scheduledExecutor);
+
+ //Durable message to send
+
+ Message message1 = this.generateMessage(1);
+
+ // Non durable message to send
+
+ Message message2 = this.generateMessage(2);
+
+ message2.setDurable(false);
+
+
+ StorageManager sm = EasyMock.createStrictMock(StorageManager.class);
+
+ PostOffice po= EasyMock.createStrictMock(PostOffice.class);
+
+ final long txID = 123;
+
+ EasyMock.expect(sm.generateTransactionID()).andReturn(txID);
+
+ EasyMock.replay(sm);
+
+ Transaction tx = new TransactionImpl(sm, po);
+
+ assertTrue(tx.isEmpty());
+ assertFalse(tx.isContainsPersistent());
+
+ EasyMock.verify(sm);
+
+ EasyMock.reset(sm);
+
+ final String address1 = "topic1";
+
+ //Expect:
+
+ MessageReference ref5 = message1.createReference(queue1);
+ MessageReference ref6 = message1.createReference(queue2);
+ List<MessageReference> message1Refs = new ArrayList<MessageReference>();
+ message1Refs.add(ref5);
+ message1Refs.add(ref6);
+
+ EasyMock.expect(po.route(address1, message1)).andReturn(message1Refs);
+
+ sm.storeMessageTransactional(txID, address1, message1);
+
+ EasyMock.replay(po);
+
+ EasyMock.replay(sm);
+
+ tx.addMessage(address1, message1);
+
+ assertFalse(tx.isEmpty());
+ assertTrue(tx.isContainsPersistent());
+
+
+ EasyMock.verify(po);
+
+ EasyMock.verify(sm);
+
+ EasyMock.reset(po);
+
+ EasyMock.reset(sm);
+
+
+ //Expect:
+
+ final String address2 = "queue3";
+
+ MessageReference ref7 = message2.createReference(queue3);
+ List<MessageReference> message2Refs = new ArrayList<MessageReference>();
+ message2Refs.add(ref7);
+
+ EasyMock.expect(po.route(address2, message2)).andReturn(message1Refs);
+
+ EasyMock.replay(po);
+
+ EasyMock.replay(sm);
+
+ tx.addMessage(address2, message2);
+
+ EasyMock.verify(po);
+
+ EasyMock.verify(sm);
+
+ EasyMock.reset(po);
+
+ EasyMock.reset(sm);
+
+ //Expect :
+
+ sm.commit(txID);
+
+ EasyMock.replay(sm);
+
+ tx.commit();
+
+ EasyMock.verify(sm);
+
+ //TODO test messages are routed and refs count reduced
+ }
+
+
+
+ public void testAckCommit() throws Exception
+ {
+ //Durable queue
+ Queue queue1 = new QueueImpl(12, "queue1", null, false, true, false, -1, scheduledExecutor);
+
+ //Durable queue
+ Queue queue2 = new QueueImpl(34, "queue2", null, false, true, false, -1, scheduledExecutor);
+
+ //Non durable queue
+ Queue queue3 = new QueueImpl(65, "queue3", null, false, false, false, -1, scheduledExecutor);
+
+ //Some refs to ack
+
+ Message message1 = this.generateMessage(12);
+
+ MessageReference ref1 = message1.createReference(queue1);
+
+ MessageReference ref2 = message1.createReference(queue2);
+
+ MessageReference ref3 = message1.createReference(queue3);
+
+
+ //Non durable message to ack
+ Message message2 = this.generateMessage(23);
+
+ message2.setDurable(false);
+
+ MessageReference ref4 = message2.createReference(queue1);
+
+
+ StorageManager sm = EasyMock.createStrictMock(StorageManager.class);
+
+ PostOffice po= EasyMock.createStrictMock(PostOffice.class);
+
+ final long txID = 123;
+
+ EasyMock.expect(sm.generateTransactionID()).andReturn(txID);
+
+ EasyMock.replay(sm);
+
+ Transaction tx = new TransactionImpl(sm, po);
+
+ assertTrue(tx.isEmpty());
+
+ assertFalse(tx.isContainsPersistent());
+
+ EasyMock.verify(sm);
+
+ EasyMock.reset(sm);
+
+ //Expect:
+
+ sm.storeAcknowledgeTransactional(txID, queue1.getPersistenceID(), message1.getMessageID());
+ sm.storeDeleteTransactional(txID, message1.getMessageID());
+
+ EasyMock.replay(sm);
+
+ tx.addAcknowledgement(ref3);
+
+ assertFalse(tx.isEmpty());
+ assertFalse(tx.isContainsPersistent());
+
+ tx.addAcknowledgement(ref1);
+
+ assertTrue(tx.isContainsPersistent());
+
+ tx.addAcknowledgement(ref2);
+
+ assertTrue(tx.isContainsPersistent());
+
+
+ assertEquals(3, tx.getAcknowledgementsCount());
+
+ EasyMock.verify(sm);
+
+ EasyMock.reset(sm);
+
+ //Expect:
+
+ //Nothing
+
+ EasyMock.replay(sm);
+
+ tx.addAcknowledgement(ref4);
+
+ assertEquals(4, tx.getAcknowledgementsCount());
+
+ EasyMock.verify(sm);
+
+ EasyMock.reset(sm);
+
+ //Expect:
+
+ sm.commit(txID);
+
+ EasyMock.replay(sm);
+
+ tx.commit();
+
+ EasyMock.verify(sm);
+
+ EasyMock.reset(sm);
+
+ //TODO test messages are routed and refs count reduced
+ }
+
+ // Private -------------------------------------------------------------------------
+
+ private Transaction createTransaction()
+ {
+ StorageManager sm = EasyMock.createStrictMock(StorageManager.class);
+
+ PostOffice po = EasyMock.createStrictMock(PostOffice.class);
+
+ final long txID = 123L;
+
+ EasyMock.expect(sm.generateTransactionID()).andReturn(txID);
+
+ EasyMock.replay(sm);
+
+ Transaction tx = new TransactionImpl(sm, po);
+
+ EasyMock.verify(sm);
+
+ return tx;
+ }
+
+ private Transaction createTransactionXA()
+ {
+ StorageManager sm = EasyMock.createStrictMock(StorageManager.class);
+
+ PostOffice po = EasyMock.createStrictMock(PostOffice.class);
+
+ final long txID = 123L;
+
+ EasyMock.expect(sm.generateTransactionID()).andReturn(txID);
+
+ EasyMock.replay(sm);
+
+ Xid xid = this.generateXid();
+
+ Transaction tx = new TransactionImpl(xid, sm, po);
+
+ EasyMock.verify(sm);
+
+ return tx;
+ }
+
+
+ // Inner classes -----------------------------------------------------------------------
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/util/SerializedClientSupport.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/util/SerializedClientSupport.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/util/SerializedClientSupport.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/util/SerializedClientSupport.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,198 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.unit.core.util;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static junit.framework.Assert.assertNotSame;
+import static junit.framework.Assert.assertSame;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.ObjectOutputStream;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeoutException;
+
+import javax.jms.ConnectionFactory;
+import javax.jms.Queue;
+
+import org.jboss.messaging.core.logging.Logger;
+
+/**
+ * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class SerializedClientSupport
+{
+ // Constants -----------------------------------------------------
+
+ private static final Logger log = Logger.getLogger(SerializedClientSupport.class);
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ public static Process spawnVM(String className, String... args)
+ throws Exception
+ {
+ StringBuffer sb = new StringBuffer();
+
+ sb.append("java").append(' ');
+
+ String classPath = System.getProperty("java.class.path");
+
+ // I guess it'd be simpler to check if the OS is Windows...
+ if (System.getProperty("os.name").equals("Linux")
+ || System.getProperty("os.name").equals("Mac OS X"))
+ {
+ sb.append("-cp").append(" ").append(classPath).append(" ");
+ } else
+ {
+ sb.append("-cp").append(" \"").append(classPath).append("\" ");
+ }
+
+ sb.append(className).append(' ');
+
+ for (int i = 0; i < args.length; i++)
+ {
+ sb.append(args[i]).append(' ');
+ }
+
+ String commandLine = sb.toString();
+
+ log.trace("command line: " + commandLine);
+
+ Process process = Runtime.getRuntime().exec(commandLine);
+
+ log.trace("process: " + process);
+
+ ProcessLogger outputLogger = new ProcessLogger(process.getInputStream(),
+ className);
+ outputLogger.start();
+
+ return process;
+ }
+
+ public static File writeToFile(String fileName, ConnectionFactory cf,
+ Queue queue) throws Exception
+ {
+ String moduleOutput = System.getProperty("java.io.tmpdir");
+ if (moduleOutput == null)
+ {
+ throw new Exception("Can't find 'module.output'");
+ }
+ File dir = new File(moduleOutput);
+
+ if (!dir.isDirectory() || !dir.canWrite())
+ {
+ throw new Exception(dir + " is either not a directory or not writable");
+ }
+
+ File file = new File(dir, fileName);
+
+ ObjectOutputStream oos = new ObjectOutputStream(
+ new FileOutputStream(file));
+ oos.writeObject(cf);
+ oos.writeObject(queue);
+ oos.flush();
+ oos.close();
+
+ return file;
+ }
+
+ /**
+ * Assert that a process exits with the expected value (or not depending if
+ * the <code>sameValue</code> is expected or not). The method waits 5
+ * seconds for the process to exit, then an Exception is thrown. In any case,
+ * the process is destroyed before the method returns.
+ */
+ public static void assertProcessExits(boolean sameValue, int value,
+ final Process p) throws InterruptedException, ExecutionException,
+ TimeoutException
+ {
+ ScheduledExecutorService executor = Executors
+ .newSingleThreadScheduledExecutor();
+ Future<Integer> future = executor.submit(new Callable<Integer>()
+ {
+
+ public Integer call() throws Exception
+ {
+ p.waitFor();
+ return p.exitValue();
+ }
+ });
+ try
+ {
+ int exitValue = future.get(10, SECONDS);
+ if (sameValue)
+ {
+ assertSame(value, exitValue);
+ } else
+ {
+ assertNotSame(value, exitValue);
+ }
+ } finally
+ {
+ p.destroy();
+ }
+ }
+
+ /**
+ * Redirect the input stream to a logger (as debug logs)
+ */
+ static class ProcessLogger extends Thread
+ {
+ InputStream is;
+ Logger processLogger;
+
+ ProcessLogger(InputStream is, String className)
+ throws ClassNotFoundException
+ {
+ this.is = is;
+ this.processLogger = Logger.getLogger(Class.forName(className));
+ setDaemon(true);
+ }
+
+ public void run()
+ {
+ try
+ {
+ InputStreamReader isr = new InputStreamReader(is);
+ BufferedReader br = new BufferedReader(isr);
+ String line = null;
+ while ((line = br.readLine()) != null)
+ processLogger.debug(line);
+ } catch (IOException ioe)
+ {
+ ioe.printStackTrace();
+ }
+ }
+ }
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/core/util/TokenBucketLimiterTest.java (from rev 4054, trunk/tests/src/org/jboss/messaging/core/util/test/unit/TokenBucketLimiterTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/util/TokenBucketLimiterTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/util/TokenBucketLimiterTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,130 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.core.util;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.util.TokenBucketLimiter;
+
+/**
+ *
+ * A TokenBucketLimiterTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class TokenBucketLimiterTest extends TestCase
+{
+ private static final Logger log = Logger.getLogger(TokenBucketLimiterTest.class);
+
+ public void testRateWithSpin1() throws Exception
+ {
+ testRate(1, true);
+ }
+
+ public void testRateWithSpin10() throws Exception
+ {
+ testRate(10, true);
+ }
+
+ public void testRateWithSpin100() throws Exception
+ {
+ testRate(100, true);
+ }
+
+ public void testRateWithSpin1000() throws Exception
+ {
+ testRate(1000, true);
+ }
+
+ public void testRateWithSpin10000() throws Exception
+ {
+ testRate(10000, true);
+ }
+
+ public void testRateWithSpin100000() throws Exception
+ {
+ testRate(100000, true);
+ }
+
+ public void testRateWithoutSpin1() throws Exception
+ {
+ testRate(1, false);
+ }
+
+ public void testRateWithoutSpin10() throws Exception
+ {
+ testRate(10, false);
+ }
+
+ public void testRateWithoutSpin100() throws Exception
+ {
+ testRate(100, false);
+ }
+
+ public void testRateWithoutSpin1000() throws Exception
+ {
+ testRate(1000, false);
+ }
+
+ public void testRateWithoutSpin10000() throws Exception
+ {
+ testRate(10000, false);
+ }
+
+ public void testRateWithoutSpin100000() throws Exception
+ {
+ testRate(100000, false);
+ }
+
+ private void testRate(int rate, boolean spin) throws Exception
+ {
+ final double error = 0.05; //Allow for 5% error
+
+ TokenBucketLimiter tbl = new TokenBucketLimiter(rate, spin);
+
+ long start = System.currentTimeMillis();
+
+ long count = 0;
+
+ final long measureTime = 5000;
+
+ while (System.currentTimeMillis() - start < measureTime)
+ {
+ tbl.limit();
+
+ count++;
+ }
+
+ long end = System.currentTimeMillis();
+
+ double actualRate = ((double)(1000 * count)) / ( end - start);
+
+ log.info("Desired rate: " + rate + " Actual rate " + actualRate + " invs/sec");
+
+ assertTrue(actualRate > rate * (1 - error));
+
+ assertTrue(actualRate < rate * (1 + error));
+
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/SelectorTranslatorTest.java (from rev 4054, trunk/tests/src/org/jboss/test/messaging/jms/client/test/unit/SelectorTranslatorTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/SelectorTranslatorTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/SelectorTranslatorTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,241 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.jms.client;
+
+import org.jboss.messaging.jms.client.SelectorTranslator;
+import org.jboss.messaging.tests.util.UnitTestCase;
+
+/**
+ *
+ * A SelectorTranslatorTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class SelectorTranslatorTest extends UnitTestCase
+{
+ public void testParseNull()
+ {
+ assertNull(SelectorTranslator.convertToJBMFilterString(null));
+ }
+
+ public void testParseSimple()
+ {
+ final String selector = "color = 'red'";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+ }
+
+ public void testParseMoreComplex()
+ {
+ final String selector = "color = 'red' OR cheese = 'stilton' OR (age = 3 AND shoesize = 12)";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+ }
+
+ public void testParseJMSDeliveryMode()
+ {
+ String selector = "JMSDeliveryMode='NON_PERSISTENT'";
+
+ assertEquals("JBMDurable='NON_DURABLE'", SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = "JMSDeliveryMode='PERSISTENT'";
+
+ assertEquals("JBMDurable='DURABLE'", SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = "color = 'red' AND 'NON_PERSISTENT' = JMSDeliveryMode";
+
+ assertEquals("color = 'red' AND 'NON_DURABLE' = JBMDurable", SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = "color = 'red' AND 'PERSISTENT' = JMSDeliveryMode";
+
+ assertEquals("color = 'red' AND 'DURABLE' = JBMDurable", SelectorTranslator.convertToJBMFilterString(selector));
+
+ checkNoSubstitute("JMSDeliveryMode");
+ }
+
+ public void testParseJMSPriority()
+ {
+ String selector = "JMSPriority=5";
+
+ assertEquals("JBMPriority=5", SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " JMSPriority = 7";
+
+ assertEquals(" JBMPriority = 7", SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " JMSPriority = 7 OR 1 = JMSPriority AND (JMSPriority= 1 + 4)";
+
+ assertEquals(" JBMPriority = 7 OR 1 = JBMPriority AND (JBMPriority= 1 + 4)", SelectorTranslator.convertToJBMFilterString(selector));
+
+ checkNoSubstitute("JMSPriority");
+
+ selector = "animal = 'lion' JMSPriority = 321 OR animal_name = 'xyzJMSPriorityxyz'";
+
+ assertEquals("animal = 'lion' JBMPriority = 321 OR animal_name = 'xyzJMSPriorityxyz'", SelectorTranslator.convertToJBMFilterString(selector));
+
+ }
+
+ public void testParseJMSMessageID()
+ {
+ String selector = "JMSMessageID='ID:JBM-12435678";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " JMSMessageID='ID:JBM-12435678";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " JMSMessageID = 'ID:JBM-12435678";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " myHeader = JMSMessageID";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " myHeader = JMSMessageID OR (JMSMessageID = 'ID-JBM' + '12345')";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ checkNoSubstitute("JMSMessageID");
+ }
+
+ public void testParseJMSTimestamp()
+ {
+ String selector = "JMSTimestamp=12345678";
+
+ assertEquals("JBMTimestamp=12345678", SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " JMSTimestamp=12345678";
+
+ assertEquals(" JBMTimestamp=12345678", SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " JMSTimestamp=12345678 OR 78766 = JMSTimestamp AND (JMSTimestamp= 1 + 4878787)";
+
+ assertEquals(" JBMTimestamp=12345678 OR 78766 = JBMTimestamp AND (JBMTimestamp= 1 + 4878787)", SelectorTranslator.convertToJBMFilterString(selector));
+
+
+ checkNoSubstitute("JMSTimestamp");
+
+ selector = "animal = 'lion' JMSTimestamp = 321 OR animal_name = 'xyzJMSTimestampxyz'";
+
+ assertEquals("animal = 'lion' JBMTimestamp = 321 OR animal_name = 'xyzJMSTimestampxyz'", SelectorTranslator.convertToJBMFilterString(selector));
+
+ }
+
+ public void testParseJMSCorrelationID()
+ {
+ String selector = "JMSCorrelationID='ID:JBM-12435678";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " JMSCorrelationID='ID:JBM-12435678";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " JMSCorrelationID = 'ID:JBM-12435678";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " myHeader = JMSCorrelationID";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " myHeader = JMSCorrelationID OR (JMSCorrelationID = 'ID-JBM' + '12345')";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ checkNoSubstitute("JMSCorrelationID");
+ }
+
+ public void testParseJMSType()
+ {
+ String selector = "JMSType='aardvark'";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " JMSType='aardvark'";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " JMSType = 'aardvark'";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " myHeader = JMSType";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = " myHeader = JMSType OR (JMSType = 'aardvark' + 'sandwich')";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ checkNoSubstitute("JMSType");
+ }
+
+ // Private -------------------------------------------------------------------------------------
+
+ private void checkNoSubstitute(String fieldName)
+ {
+ String selector = "Other" + fieldName + " = 767868";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = "cheese = 'cheddar' AND Wrong" + fieldName +" = 54";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = "fruit = 'pomegranate' AND " + fieldName + "NotThisOne = 'tuesday'";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = "animal = 'lion' AND animal_name = '" + fieldName + "'";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = "animal = 'lion' AND animal_name = ' " + fieldName + "'";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = "animal = 'lion' AND animal_name = ' " + fieldName + " '";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = "animal = 'lion' AND animal_name = 'xyz " + fieldName +"'";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = "animal = 'lion' AND animal_name = 'xyz" + fieldName + "'";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = "animal = 'lion' AND animal_name = '" + fieldName + "xyz'";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+
+ selector = "animal = 'lion' AND animal_name = 'xyz" + fieldName + "xyz'";
+
+ assertEquals(selector, SelectorTranslator.convertToJBMFilterString(selector));
+ }
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/jms/misc/ManifestTest.java (from rev 4054, trunk/tests/src/org/jboss/test/messaging/jms/misc/ManifestTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/jms/misc/ManifestTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/jms/misc/ManifestTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,104 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.jms.misc;
+
+import junit.framework.TestCase;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionMetaData;
+import java.util.Properties;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+import java.util.jar.Attributes;
+import java.io.File;
+
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.server.MessagingServer;
+import org.jboss.messaging.core.server.impl.MessagingServerImpl;
+import org.jboss.messaging.tests.unit.core.remoting.impl.ConfigurationHelper;
+import org.jboss.messaging.core.remoting.TransportType;
+import org.jboss.messaging.jms.client.JBossConnectionMetaData;
+
+/**
+ * @author <a href="ataylor at redhat.com">Andy Taylor</a>
+ */
+public class ManifestTest extends TestCase
+{
+ // Constants -----------------------------------------------------
+ Logger log = Logger.getLogger(ManifestTest.class);
+ // Static --------------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ public ManifestTest(String name)
+ {
+ super(name);
+ }
+
+ // Public --------------------------------------------------------
+
+ public void testManifestEntries() throws Exception
+ {
+ Properties props = System.getProperties();
+ String userDir = props.getProperty("build.lib");
+
+ log.trace("userDir is " + userDir);
+
+ // The jar must be there
+ File file = new File("build/jars", "jboss-messaging.jar");
+ assertTrue(file.exists());
+
+ // Open the jar and load MANIFEST.MF
+ JarFile jar = new JarFile(file);
+ Manifest manifest = jar.getManifest();
+
+ // Open a connection and get ConnectionMetaData
+ Connection conn = null;
+
+ try
+ {
+ MessagingServer server = new MessagingServerImpl(ConfigurationHelper.newConfiguration(TransportType.INVM, null, 0));
+ //server.getVersion()
+
+ ConnectionMetaData meta = new JBossConnectionMetaData(server.getVersion());
+
+ // Compare the value from ConnectionMetaData and MANIFEST.MF
+ Attributes attrs = manifest.getMainAttributes();
+
+ assertEquals(meta.getProviderVersion(), attrs.getValue("JBossMessaging-Version"));
+ assertEquals("https://svn.jboss.org/repos/messaging/trunk", attrs.getValue("JBossMessaging-SVN-URL"));
+ }
+ finally
+ {
+ if (conn != null)
+ {
+ conn.close();
+ }
+ }
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/jms/network/ClientNetworkFailureTest.java (from rev 4054, trunk/tests/src/org/jboss/test/messaging/jms/network/ClientNetworkFailureTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/jms/network/ClientNetworkFailureTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/jms/network/ClientNetworkFailureTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,204 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.jms.network;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.jboss.messaging.tests.integration.core.remoting.mina.TestSupport.KEEP_ALIVE_INTERVAL;
+import static org.jboss.messaging.tests.integration.core.remoting.mina.TestSupport.KEEP_ALIVE_TIMEOUT;
+
+import java.io.IOException;
+import java.util.concurrent.CountDownLatch;
+
+import org.jboss.messaging.core.client.FailureListener;
+import org.jboss.messaging.core.client.ClientConnectionFactory;
+import org.jboss.messaging.core.client.ClientConnection;
+import org.jboss.messaging.core.client.impl.ClientConnectionFactoryImpl;
+import org.jboss.messaging.core.config.impl.ConfigurationImpl;
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.remoting.impl.mina.MinaService;
+import org.jboss.messaging.core.remoting.TransportType;
+import org.jboss.messaging.core.server.impl.MessagingServerImpl;
+import org.jboss.messaging.core.server.MessagingServer;
+import org.jboss.messaging.core.server.ConnectionManager;
+import org.jboss.messaging.core.logging.Logger;
+import junit.framework.TestCase;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class ClientNetworkFailureTest extends TestCase
+{
+
+ // Constants -----------------------------------------------------
+ Logger log = Logger.getLogger(ClientNetworkFailureTest.class);
+ private MessagingServer server;
+ private MinaService minaService;
+ private NetworkFailureFilter networkFailureFilter;
+
+ // Static --------------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ public ClientNetworkFailureTest(String name)
+ {
+ super(name);
+ }
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+ ConfigurationImpl newConfig = new ConfigurationImpl();
+ newConfig.setInvmDisabled(true);
+ newConfig.setHost("localhost");
+ newConfig.setPort(5400);
+ newConfig.setTransport(TransportType.TCP);
+ newConfig.setKeepAliveInterval(KEEP_ALIVE_INTERVAL);
+ newConfig.setKeepAliveTimeout(KEEP_ALIVE_TIMEOUT);
+ server = new MessagingServerImpl(newConfig);
+ server.start();
+ minaService = (MinaService) server.getRemotingService();
+ networkFailureFilter = new NetworkFailureFilter();
+ minaService.getFilterChain().addFirst("network-failure",
+ networkFailureFilter);
+
+ assertActiveConnectionsOnTheServer(0);
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ assertActiveConnectionsOnTheServer(0);
+ server.stop();
+ //minaService.start();
+
+ super.tearDown();
+ }
+
+ // Public --------------------------------------------------------
+
+ public void testServerResourcesCleanUpWhenClientCommThrowsException()
+ throws Exception
+ {
+ ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0, server.getConfiguration(), server.getVersion());
+
+ ClientConnection conn = cf.createConnection();
+
+ assertActiveConnectionsOnTheServer(1);
+
+ final CountDownLatch exceptionLatch = new CountDownLatch(2);
+ conn.setFailureListener(new FailureListener()
+ {
+ public void onFailure(MessagingException me)
+ {
+ exceptionLatch.countDown();
+ }
+ });
+ FailureListener listener = new FailureListenerWithLatch(exceptionLatch);
+ minaService.addFailureListener(listener);
+
+ networkFailureFilter.messageSentThrowsException = new IOException(
+ "Client is unreachable");
+ networkFailureFilter.messageReceivedDropsPacket = true;
+
+ boolean gotExceptionsOnTheServerAndTheClient = exceptionLatch.await(
+ KEEP_ALIVE_INTERVAL + KEEP_ALIVE_TIMEOUT + 2, SECONDS);
+ assertTrue(gotExceptionsOnTheServerAndTheClient);
+ assertActiveConnectionsOnTheServer(0);
+
+ try
+ {
+ conn.close();
+ fail("close should fail since client resources must have been cleaned up on the server side");
+ } catch (Exception e)
+ {
+ }
+
+ minaService.removeFailureListener(listener);
+ }
+
+ public void testServerResourcesCleanUpWhenClientCommDropsPacket()
+ throws Exception
+ {
+ ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0, server.getConfiguration(), server.getVersion());
+
+ ClientConnection conn = cf.createConnection();
+
+ final CountDownLatch exceptionLatch = new CountDownLatch(1);
+
+ FailureListener listener = new FailureListenerWithLatch(exceptionLatch);
+ minaService.addFailureListener(listener);
+
+ assertActiveConnectionsOnTheServer(1);
+
+ networkFailureFilter.messageSentDropsPacket = true;
+ networkFailureFilter.messageReceivedDropsPacket = true;
+
+ boolean gotExceptionOnTheServer = exceptionLatch.await(
+ KEEP_ALIVE_INTERVAL + KEEP_ALIVE_TIMEOUT + 5, SECONDS);
+ assertTrue(gotExceptionOnTheServer);
+ assertActiveConnectionsOnTheServer(0);
+
+ try
+ {
+ conn.close();
+ fail("close should fail since client resources must have been cleaned up on the server side");
+ } catch (Exception e)
+ {
+ }
+ }
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ private final class FailureListenerWithLatch implements FailureListener
+ {
+ private final CountDownLatch exceptionLatch;
+
+ private FailureListenerWithLatch(CountDownLatch exceptionLatch)
+ {
+ this.exceptionLatch = exceptionLatch;
+ }
+
+ public void onFailure(MessagingException me)
+ {
+ log.warn("got expected exception on the server");
+ exceptionLatch.countDown();
+ }
+ }
+
+ private void assertActiveConnectionsOnTheServer(int expectedSize)
+ throws Exception
+ {
+ ConnectionManager cm = server
+ .getConnectionManager();
+ assertEquals(expectedSize, cm.getActiveConnections().size());
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/jms/network/NetworkFailureFilter.java (from rev 4054, trunk/tests/src/org/jboss/test/messaging/jms/network/NetworkFailureFilter.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/jms/network/NetworkFailureFilter.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/jms/network/NetworkFailureFilter.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,47 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.unit.jms.network;
+
+import org.apache.mina.common.IoFilterAdapter;
+import org.apache.mina.common.IoSession;
+import org.apache.mina.common.WriteRequest;
+
+final class NetworkFailureFilter extends IoFilterAdapter
+{
+ Exception messageSentThrowsException = null;
+ boolean messageSentDropsPacket = false;
+ boolean messageReceivedDropsPacket = false;
+
+ @Override
+ public void messageSent(NextFilter nextFilter, IoSession session,
+ WriteRequest writeRequest) throws Exception
+ {
+ if (messageSentThrowsException != null)
+ {
+ throw messageSentThrowsException;
+ } else if (messageSentDropsPacket)
+ {
+ // do nothing
+ } else
+ {
+ nextFilter.messageSent(session, writeRequest);
+ }
+ }
+
+ @Override
+ public void messageReceived(NextFilter nextFilter, IoSession session,
+ Object message) throws Exception
+ {
+ if (messageReceivedDropsPacket)
+ {
+ // do nothing
+ } else
+ {
+ super.messageReceived(nextFilter, session, message);
+ }
+ }
+}
\ No newline at end of file
Copied: trunk/tests/src/org/jboss/messaging/tests/unit/jms/server/ConnectionManagerTest.java (from rev 4054, trunk/tests/src/org/jboss/test/messaging/jms/server/ConnectionManagerTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/jms/server/ConnectionManagerTest.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/jms/server/ConnectionManagerTest.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,109 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.unit.jms.server;
+
+
+import org.jboss.messaging.core.server.ConnectionManager;
+import org.jboss.messaging.core.server.impl.MessagingServerImpl;
+import org.jboss.messaging.tests.unit.core.remoting.impl.ConfigurationHelper;
+import static org.jboss.messaging.core.remoting.TransportType.INVM;
+import org.jboss.messaging.core.client.ClientConnectionFactory;
+import org.jboss.messaging.core.client.ClientConnection;
+import org.jboss.messaging.core.client.impl.ClientConnectionFactoryImpl;
+import junit.framework.TestCase;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class ConnectionManagerTest extends TestCase
+{
+ // Constants -----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+ private MessagingServerImpl server;
+ // Constructors --------------------------------------------------
+
+ public ConnectionManagerTest(String name)
+ {
+ super(name);
+ }
+
+ protected void setUp() throws Exception
+ {
+ server = new MessagingServerImpl(ConfigurationHelper.newConfiguration(INVM, null, 0));
+ server.start();
+ }
+
+ protected void tearDown() throws Exception
+ {
+ if(server != null)
+ {
+ server.stop();
+ server = null;
+ }
+ }
+
+
+
+ // TestCase overrides -------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ public void testTwoConnectionsFromTheSameVM() throws Exception
+ {
+
+ assertActiveConnectionsOnTheServer(0);
+ ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0, server.getConfiguration(), server.getVersion());
+
+ ClientConnection conn_1 = cf.createConnection();
+
+ assertActiveConnectionsOnTheServer(1);
+
+ ClientConnection conn_2 = cf.createConnection();
+
+ assertActiveConnectionsOnTheServer(2);
+
+ assertFalse(conn_1.equals(conn_2));
+
+ conn_1.close();
+
+ assertActiveConnectionsOnTheServer(1);
+
+ conn_2.close();
+
+ assertActiveConnectionsOnTheServer(0);
+ }
+
+ private void assertActiveConnectionsOnTheServer(int expectedSize)
+ throws Exception
+ {
+ ConnectionManager cm = server
+ .getConnectionManager();
+ assertEquals(expectedSize, cm.getActiveConnections().size());
+ }
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/util/InVMContext.java (from rev 4054, trunk/tests/src/org/jboss/test/util/InVMContext.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/util/InVMContext.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/util/InVMContext.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,388 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* 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.messaging.tests.util;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.naming.Binding;
+import javax.naming.Context;
+import javax.naming.Name;
+import javax.naming.NameAlreadyBoundException;
+import javax.naming.NameNotFoundException;
+import javax.naming.NameParser;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.RefAddr;
+import javax.naming.Reference;
+
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.tests.util.NonSerializableFactory;
+
+
+/**
+ * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>
+ * @version <tt>$Revision: 2868 $</tt>
+ *
+ * $Id: InVMContext.java 2868 2007-07-10 20:22:16Z timfox $
+ */
+public class InVMContext implements Context, Serializable
+{
+ // Constants -----------------------------------------------------
+
+ private static final long serialVersionUID = 385743957345L;
+
+ private static final Logger log = Logger.getLogger(InVMContext.class);
+
+
+ // Static --------------------------------------------------------
+
+ // Attributes ----------------------------------------------------
+
+ protected Map map;
+ protected NameParser parser = new InVMNameParser();
+ private String nameInNamespace = "";
+
+ // Constructors --------------------------------------------------
+
+ public InVMContext()
+ {
+ map = Collections.synchronizedMap(new HashMap());
+ }
+
+ public InVMContext(String nameInNamespace)
+ {
+ this();
+ this.nameInNamespace = nameInNamespace;
+ }
+ // Context implementation ----------------------------------------
+
+ public Object lookup(Name name) throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public Object lookup(String name) throws NamingException
+ {
+ name = trimSlashes(name);
+ int i = name.indexOf("/");
+ String tok = i == -1 ? name : name.substring(0, i);
+ Object value = map.get(tok);
+ if (value == null)
+ {
+ throw new NameNotFoundException("Name not found: " + tok);
+ }
+ if (value instanceof InVMContext && i != -1)
+ {
+ return ((InVMContext)value).lookup(name.substring(i));
+ }
+ if (value instanceof Reference)
+ {
+ Reference ref = (Reference)value;
+ RefAddr refAddr = ref.get("nns");
+
+ // we only deal with references create by NonSerializableFactory
+ String key = (String)refAddr.getContent();
+ return NonSerializableFactory.lookup(key);
+ }
+ else
+ {
+ return value;
+ }
+ }
+
+ public void bind(Name name, Object obj) throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void bind(String name, Object obj) throws NamingException
+ {
+ internalBind(name, obj, false);
+ }
+
+ public void rebind(Name name, Object obj) throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void rebind(String name, Object obj) throws NamingException
+ {
+ internalBind(name, obj, true);
+ }
+
+ public void unbind(Name name) throws NamingException
+ {
+ unbind(name.toString());
+ }
+
+ public void unbind(String name) throws NamingException
+ {
+ name = trimSlashes(name);
+ int i = name.indexOf("/");
+ boolean terminal = i == -1;
+ if (terminal)
+ {
+ map.remove(name);
+ }
+ else
+ {
+ String tok = name.substring(0, i);
+ InVMContext c = (InVMContext)map.get(tok);
+ if (c == null)
+ {
+ throw new NameNotFoundException("Context not found: " + tok);
+ }
+ c.unbind(name.substring(i));
+ }
+ }
+
+ public void rename(Name oldName, Name newName) throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void rename(String oldName, String newName) throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public NamingEnumeration list(Name name) throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public NamingEnumeration list(String name) throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public NamingEnumeration listBindings(Name name) throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public NamingEnumeration listBindings(String contextName) throws NamingException
+ {
+ contextName = trimSlashes(contextName);
+ if (!"".equals(contextName) && !".".equals(contextName))
+ {
+ try
+ {
+ return ((InVMContext)lookup(contextName)).listBindings("");
+ }
+ catch(Throwable t)
+ {
+ throw new NamingException(t.getMessage());
+ }
+ }
+
+ List l = new ArrayList();
+ for(Iterator i = map.keySet().iterator(); i.hasNext(); )
+ {
+ String name = (String)i.next();
+ Object object = map.get(name);
+ l.add(new Binding(name, object));
+ }
+ return new NamingEnumerationImpl(l.iterator());
+ }
+
+ public void destroySubcontext(Name name) throws NamingException
+ {
+ destroySubcontext(name.toString());
+ }
+
+ public void destroySubcontext(String name) throws NamingException
+ {
+ map.remove(trimSlashes(name));
+ }
+
+ public Context createSubcontext(Name name) throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public Context createSubcontext(String name) throws NamingException
+ {
+ name = trimSlashes(name);
+ if (map.get(name) != null)
+ {
+ throw new NameAlreadyBoundException(name);
+ }
+ InVMContext c = new InVMContext(getNameInNamespace());
+ map.put(name, c);
+ return c;
+ }
+
+ public Object lookupLink(Name name) throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public Object lookupLink(String name) throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public NameParser getNameParser(Name name) throws NamingException
+ {
+ return getNameParser(name.toString());
+ }
+
+ public NameParser getNameParser(String name) throws NamingException
+ {
+ return parser;
+ }
+
+ public Name composeName(Name name, Name prefix) throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public String composeName(String name, String prefix) throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public Object addToEnvironment(String propName, Object propVal) throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public Object removeFromEnvironment(String propName) throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public Hashtable getEnvironment() throws NamingException
+ {
+ Hashtable env = new Hashtable();
+ env.put("java.naming.factory.initial",
+ "org.jboss.test.messaging.tools.container.InVMInitialContextFactory");
+ env.put("java.naming.provider.url", "org.jboss.naming:org.jnp.interface");
+ return env;
+ }
+
+ public void close() throws NamingException
+ {
+ }
+
+ public String getNameInNamespace() throws NamingException
+ {
+ return nameInNamespace;
+ }
+
+ // Public --------------------------------------------------------
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ private String trimSlashes(String s)
+ {
+ int i = 0;
+ while(true)
+ {
+ if (i == s.length() || s.charAt(i) != '/')
+ {
+ break;
+ }
+ i++;
+ }
+ s = s.substring(i);
+ i = s.length() - 1;
+ while(true)
+ {
+ if (i == -1 || s.charAt(i) != '/')
+ {
+ break;
+ }
+ i--;
+ }
+ return s.substring(0, i + 1);
+ }
+
+ private void internalBind(String name, Object obj, boolean rebind) throws NamingException
+ {
+ log.debug("Binding " + name + " obj " + obj + " rebind " + rebind);
+ name = trimSlashes(name);
+ int i = name.lastIndexOf("/");
+ InVMContext c = this;
+ if (i != -1)
+ {
+ String path = name.substring(0, i);
+ c = (InVMContext)lookup(path);
+ }
+ name = name.substring(i + 1);
+ if (!rebind && c.map.get(name) != null)
+ {
+ throw new NameAlreadyBoundException(name);
+ }
+ c.map.put(name, obj);
+ }
+
+ // Inner classes -------------------------------------------------
+
+ private class NamingEnumerationImpl implements NamingEnumeration
+ {
+ private Iterator iterator;
+
+ NamingEnumerationImpl(Iterator bindingIterator)
+ {
+ this.iterator = bindingIterator;
+ }
+
+ public void close() throws NamingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean hasMore() throws NamingException
+ {
+ return iterator.hasNext();
+ }
+
+ public Object next() throws NamingException
+ {
+ return iterator.next();
+ }
+
+ public boolean hasMoreElements()
+ {
+ return iterator.hasNext();
+ }
+
+ public Object nextElement()
+ {
+ return iterator.next();
+ }
+ }
+}
+
Copied: trunk/tests/src/org/jboss/messaging/tests/util/InVMNameParser.java (from rev 4054, trunk/tests/src/org/jboss/test/util/InVMNameParser.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/util/InVMNameParser.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/util/InVMNameParser.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,81 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* 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.messaging.tests.util;
+
+import java.io.Serializable;
+import java.util.Properties;
+
+import javax.naming.CompoundName;
+import javax.naming.Name;
+import javax.naming.NameParser;
+import javax.naming.NamingException;
+
+/**
+ * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>
+ * @version <tt>$Revision: 2868 $</tt>
+ *
+ * $Id: InVMNameParser.java 2868 2007-07-10 20:22:16Z timfox $
+ */
+public class InVMNameParser implements NameParser, Serializable
+{
+ // Constants -----------------------------------------------------
+
+ private static final long serialVersionUID = 2925203703371001031L;
+
+ // Static --------------------------------------------------------
+
+ static Properties syntax;
+
+ static
+ {
+ syntax = new Properties();
+ syntax.put("jndi.syntax.direction", "left_to_right");
+ syntax.put("jndi.syntax.ignorecase", "false");
+ syntax.put("jndi.syntax.separator", "/");
+ }
+
+ // Attributes ----------------------------------------------------
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ public static Properties getSyntax()
+ {
+ return syntax;
+ }
+
+ public Name parse(String name) throws NamingException
+ {
+ return new CompoundName(name, syntax);
+ }
+
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/util/InVMSingleInitialContextFactory.java (from rev 4054, trunk/tests/src/org/jboss/test/util/InVMSingleInitialContextFactory.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/util/InVMSingleInitialContextFactory.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/util/InVMSingleInitialContextFactory.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,38 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.util;
+
+import javax.naming.spi.InitialContextFactory;
+import javax.naming.Context;
+import javax.naming.NamingException;
+import java.util.Hashtable;
+
+/**
+ * @author <a href="ataylor at redhat.com">Andy Taylor</a>
+ */
+public class InVMSingleInitialContextFactory implements InitialContextFactory
+{
+ public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException
+ {
+ return new InVMContext();
+ }
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/util/NonSerializableFactory.java (from rev 4054, trunk/tests/src/org/jboss/test/util/NonSerializableFactory.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/util/NonSerializableFactory.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/util/NonSerializableFactory.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,120 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.util;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Map;
+
+import javax.naming.Context;
+import javax.naming.Name;
+import javax.naming.NamingException;
+import javax.naming.RefAddr;
+import javax.naming.Reference;
+import javax.naming.StringRefAddr;
+import javax.naming.spi.ObjectFactory;
+
+import org.jboss.util.naming.Util;
+
+/**
+ * used by the default context when running in embedded local configuration
+ * @author <a href="ataylor at redhat.com">Andy Taylor</a>
+ */
+public class NonSerializableFactory implements ObjectFactory
+{
+
+ public NonSerializableFactory()
+ {
+ }
+
+ public static void unbind(Context ctx, String strName)
+ throws NamingException
+ {
+ Name name = ctx.getNameParser("").parse(strName);
+ int size = name.size();
+ String atom = name.get(size - 1);
+ Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1));
+ String key = (new StringBuilder()).append(parentCtx.getNameInNamespace()).append("/").append(atom).toString();
+ getWrapperMap().remove(key);
+ Util.unbind(ctx, strName);
+ }
+
+
+ public static void rebind(Context ctx, String strName, Object value)
+ throws NamingException
+ {
+ Name name = ctx.getNameParser("").parse(strName);
+ int size = name.size();
+ String atom = name.get(size - 1);
+ Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1));
+ String key = (new StringBuilder()).append(parentCtx.getNameInNamespace()).append("/").append(atom).toString();
+ getWrapperMap().put(key, value);
+ String className = value.getClass().getName();
+ String factory = NonSerializableFactory.class.getName();
+ StringRefAddr addr = new StringRefAddr("nns", key);
+ Reference memoryRef = new Reference(className, addr, factory, null);
+ parentCtx.rebind(atom, memoryRef);
+ }
+
+ public static void bind(Context ctx, String strName, Object value)
+ throws NamingException
+ {
+ Name name = ctx.getNameParser("").parse(strName);
+ int size = name.size();
+ String atom = name.get(size - 1);
+ Context parentCtx = Util.createSubcontext(ctx, name.getPrefix(size - 1));
+ String key = (new StringBuilder()).append(parentCtx.getNameInNamespace()).append("/").append(atom).toString();
+ getWrapperMap().put(key, value);
+ String className = value.getClass().getName();
+ String factory = NonSerializableFactory.class.getName();
+ StringRefAddr addr = new StringRefAddr("nns", key);
+ Reference memoryRef = new Reference(className, addr, factory, null);
+
+ parentCtx.bind(atom, memoryRef);
+ }
+
+ public static Object lookup(String name) throws NamingException
+ {
+ if(getWrapperMap().get(name) == null)
+ {
+ throw new NamingException(name + " not found");
+ }
+ return getWrapperMap().get(name);
+ }
+
+ public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable env)
+ throws Exception
+ {
+ Reference ref = (Reference) obj;
+ RefAddr addr = ref.get("nns");
+ String key = (String) addr.getContent();
+ return getWrapperMap().get(key);
+ }
+
+ public static Map getWrapperMap()
+ {
+ return wrapperMap;
+ }
+
+ private static Map wrapperMap = Collections.synchronizedMap(new HashMap());
+}
\ No newline at end of file
Copied: trunk/tests/src/org/jboss/messaging/tests/util/RandomUtil.java (from rev 4054, trunk/tests/src/org/jboss/messaging/test/unit/RandomUtil.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/util/RandomUtil.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/util/RandomUtil.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,65 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.messaging.tests.util;
+
+import static java.util.UUID.randomUUID;
+
+import java.util.Random;
+
+/**
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ *
+ * @version <tt>$Revision$</tt>
+ *
+ */
+public class RandomUtil
+{
+ // Constants -----------------------------------------------------
+
+ private static final Random random = new Random(System.currentTimeMillis());
+
+ // Attributes ----------------------------------------------------
+
+ // Static --------------------------------------------------------
+
+ public static String randomString()
+ {
+ return randomUUID().toString();
+ }
+
+ public static long randomLong()
+ {
+ return random.nextLong();
+ }
+
+ public static int randomInt()
+ {
+ return random.nextInt();
+ }
+
+ public static byte randomByte()
+ {
+ return Integer.valueOf(random.nextInt()).byteValue();
+ }
+
+ public static byte[] randomBytes()
+ {
+ return randomString().getBytes();
+ }
+
+ // Constructors --------------------------------------------------
+
+ // Public --------------------------------------------------------
+
+ // Package protected ---------------------------------------------
+
+ // Protected -----------------------------------------------------
+
+ // Private -------------------------------------------------------
+
+ // Inner classes -------------------------------------------------
+}
Copied: trunk/tests/src/org/jboss/messaging/tests/util/UnitTestCase.java (from rev 4054, trunk/tests/src/org/jboss/messaging/test/unit/UnitTestCase.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/util/UnitTestCase.java (rev 0)
+++ trunk/tests/src/org/jboss/messaging/tests/util/UnitTestCase.java 2008-04-15 09:24:10 UTC (rev 4055)
@@ -0,0 +1,282 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * 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.messaging.tests.util;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.core.message.MessageReference;
+import org.jboss.messaging.core.message.impl.MessageImpl;
+import org.jboss.messaging.core.server.Queue;
+import org.jboss.messaging.core.transaction.impl.XidImpl;
+
+/**
+ *
+ * Helper base class for our unit tests
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class UnitTestCase extends TestCase
+{
+ protected void assertByteArraysEquivalent(byte[] bytes1, byte[] bytes2)
+ {
+ if (bytes1.length != bytes2.length)
+ {
+ fail("Byte arrays different sizes bytes1: " + dumpBytes(bytes1) + " bytes2: " + dumpBytes(bytes2));
+ }
+
+ for (int i = 0; i < bytes1.length; i++)
+ {
+ if (bytes1[i] != bytes2[i])
+ {
+ fail("Byte arrays not equivalent: " + dumpBytes(bytes1) + " bytes2: " + dumpBytes(bytes2));
+ }
+ }
+ }
+
+ protected String dumpBytes(byte[] bytes)
+ {
+ StringBuffer buff = new StringBuffer();
+
+ buff.append(System.identityHashCode(bytes) + ", size: " + bytes.length + " [");
+
+ for (int i = 0; i < bytes.length; i++)
+ {
+ buff.append(bytes[i]);
+
+ if (i != bytes.length - 1)
+ {
+ buff.append(", ");
+ }
+ }
+
+ buff.append("]");
+
+ return buff.toString();
+ }
+
+ protected boolean deleteDirectory(File directory)
+ {
+ if (directory.isDirectory())
+ {
+ String[] files = directory.list();
+
+ for (int j = 0; j < files.length; j++)
+ {
+ if (!deleteDirectory(new File(directory, files[j])))
+ {
+ return false;
+ }
+ }
+ }
+
+ return directory.delete();
+ }
+
+ protected void copyRecursive(File from , File to) throws Exception
+ {
+ if (from.isDirectory())
+ {
+ if (!to.exists())
+ {
+ to.mkdir();
+ }
+
+ String[] subs = from.list();
+
+ for (int i = 0; i < subs.length; i++)
+ {
+ copyRecursive(new File(from, subs[i]),
+ new File(to, subs[i]));
+ }
+ }
+ else
+ {
+ InputStream in = null;
+
+ OutputStream out = null;
+
+ try
+ {
+ in = new BufferedInputStream(new FileInputStream(from));
+
+ out = new BufferedOutputStream(new FileOutputStream(to));
+
+ int b;
+
+ while ((b = in.read()) != -1)
+ {
+ out.write(b);
+ }
+ }
+ finally
+ {
+ if (in != null)
+ {
+ in.close();
+ }
+
+ if (out != null)
+ {
+ out.close();
+ }
+ }
+ }
+ }
+
+ protected void assertRefListsIdenticalRefs(List<MessageReference> l1, List<MessageReference> l2)
+ {
+ if (l1.size() != l2.size())
+ {
+ fail("Lists different sizes: " + l1.size() + ", " + l2.size());
+ }
+
+ Iterator<MessageReference> iter1 = l1.iterator();
+ Iterator<MessageReference> iter2 = l2.iterator();
+
+ while (iter1.hasNext())
+ {
+ MessageReference o1 = iter1.next();
+ MessageReference o2 = iter2.next();
+
+ assertTrue(o1 == o2);
+ }
+ }
+
+ protected void assertRefListsEquivalent(List<MessageReference> l1, List<MessageReference> l2)
+ {
+ if (l1.size() != l2.size())
+ {
+ fail("Lists different sizes: " + l1.size() + ", " + l2.size());
+ }
+
+ Iterator<MessageReference> iter1 = l1.iterator();
+ Iterator<MessageReference> iter2 = l2.iterator();
+
+ while (iter1.hasNext())
+ {
+ MessageReference o1 = iter1.next();
+ MessageReference o2 = iter2.next();
+
+ assertEquals(o1.getMessage().getMessageID(), o2.getMessage().getMessageID());
+
+ assertEquals(o1.getScheduledDeliveryTime(), o2.getScheduledDeliveryTime());
+
+ assertEquals(o1.getDeliveryCount(), o2.getDeliveryCount());
+ }
+ }
+
+ protected Message generateMessage(long id)
+ {
+ Message message = new MessageImpl(0, true, 0, System.currentTimeMillis(), (byte)4);
+
+ message.setMessageID(id);
+
+ byte[] bytes = new byte[1024];
+
+ for (int i = 0; i < 1024; i++)
+ {
+ bytes[i] = (byte)i;
+ }
+
+ message.setPayload(bytes);
+
+ return message;
+ }
+
+ protected MessageReference generateReference(Queue queue, long id)
+ {
+ Message message = generateMessage(id);
+
+ return message.createReference(queue);
+ }
+
+ protected void assertEquivalent(Message msg1, Message msg2)
+ {
+ assertEquivalent(msg1, msg2, true);
+ }
+
+ protected void assertEquivalent(Message msg1, Message msg2, boolean exactQueue)
+ {
+ assertEquals(msg1.getMessageID(), msg2.getMessageID());
+
+ assertEquals(msg1.isDurable(), msg2.isDurable());
+
+ assertEquals(msg1.getExpiration(), msg2.getExpiration());
+
+ assertEquals(msg1.getTimestamp(), msg2.getTimestamp());
+
+ assertEquals(msg1.getPriority(), msg2.getPriority());
+
+ assertEquals(msg1.getType(), msg2.getType());
+
+ if (msg1.getPayload() == null)
+ {
+ assertNull(msg2.getPayload());
+ }
+ else
+ {
+ assertByteArraysEquivalent(msg1.getPayload(), msg2.getPayload());
+ }
+
+ assertMapsEquivalent(msg1.getHeaders(), msg2.getHeaders());
+
+ assertEquals(msg1.getDurableRefCount(), msg2.getDurableRefCount());
+ }
+
+ protected void assertMapsEquivalent(Map<String, Object> headers1, Map<String, Object> headers2)
+ {
+ assertEquals(headers1.size(), headers2.size());
+
+ for (Map.Entry<String, Object> entry : headers1.entrySet())
+ {
+ assertEquals(entry.getValue(), headers2.get(entry.getKey()));
+ }
+ }
+
+ protected XidImpl generateXid()
+ {
+ String id1 = java.util.UUID.randomUUID().toString();
+
+ String id2 = java.util.UUID.randomUUID().toString();
+
+ int id = (int)(Math.random() * 100);
+
+ XidImpl xid = new XidImpl(id1.getBytes(), id, id2.getBytes());
+
+ return xid;
+ }
+
+
+}
More information about the jboss-cvs-commits
mailing list