Clean up tests, remove hard coded ports, add test timeouts, move data
dirs into target so they get removed on clean.
This commit is contained in:
Timothy Bish 2015-07-09 17:35:32 -04:00
parent 257a79de07
commit ba1bd264d9
17 changed files with 587 additions and 461 deletions

View File

@ -16,6 +16,13 @@
*/ */
package org.apache.activemq.ra; package org.apache.activemq.ra;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.beans.IntrospectionException; import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor; import java.beans.PropertyDescriptor;
import java.util.Arrays; import java.util.Arrays;
@ -26,13 +33,11 @@ import javax.jms.Session;
import javax.jms.Topic; import javax.jms.Topic;
import javax.resource.spi.InvalidPropertyException; import javax.resource.spi.InvalidPropertyException;
import junit.framework.TestCase;
import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQDestination;
import org.junit.Before;
import org.junit.Test;
/** public class ActiveMQActivationSpecTest {
*
*/
public class ActiveMQActivationSpecTest extends TestCase {
private static final String DESTINATION = "defaultQueue"; private static final String DESTINATION = "defaultQueue";
private static final String DESTINATION_TYPE = Queue.class.getName(); private static final String DESTINATION_TYPE = Queue.class.getName();
@ -46,12 +51,8 @@ public class ActiveMQActivationSpecTest extends TestCase {
private PropertyDescriptor clientIdProperty; private PropertyDescriptor clientIdProperty;
private PropertyDescriptor subscriptionNameProperty; private PropertyDescriptor subscriptionNameProperty;
public ActiveMQActivationSpecTest(String name) { @Before
super(name); public void setUp() throws Exception {
}
protected void setUp() throws Exception {
super.setUp();
activationSpec = new ActiveMQActivationSpec(); activationSpec = new ActiveMQActivationSpec();
activationSpec.setDestination(DESTINATION); activationSpec.setDestination(DESTINATION);
@ -65,39 +66,46 @@ public class ActiveMQActivationSpecTest extends TestCase {
subscriptionNameProperty = new PropertyDescriptor("subscriptionName", ActiveMQActivationSpec.class); subscriptionNameProperty = new PropertyDescriptor("subscriptionName", ActiveMQActivationSpec.class);
} }
@Test(timeout = 60000)
public void testDefaultContructionValidation() throws IntrospectionException { public void testDefaultContructionValidation() throws IntrospectionException {
PropertyDescriptor[] expected = {destinationTypeProperty, destinationProperty}; PropertyDescriptor[] expected = {destinationTypeProperty, destinationProperty};
assertActivationSpecInvalid(new ActiveMQActivationSpec(), expected); assertActivationSpecInvalid(new ActiveMQActivationSpec(), expected);
} }
@Test(timeout = 60000)
public void testMinimalSettings() { public void testMinimalSettings() {
assertEquals(DESTINATION, activationSpec.getDestination()); assertEquals(DESTINATION, activationSpec.getDestination());
assertEquals(DESTINATION_TYPE, activationSpec.getDestinationType()); assertEquals(DESTINATION_TYPE, activationSpec.getDestinationType());
assertActivationSpecValid(); assertActivationSpecValid();
} }
@Test(timeout = 60000)
public void testNoDestinationTypeFailure() { public void testNoDestinationTypeFailure() {
activationSpec.setDestinationType(null); activationSpec.setDestinationType(null);
PropertyDescriptor[] expected = {destinationTypeProperty}; PropertyDescriptor[] expected = {destinationTypeProperty};
assertActivationSpecInvalid(expected); assertActivationSpecInvalid(expected);
} }
@Test(timeout = 60000)
public void testInvalidDestinationTypeFailure() { public void testInvalidDestinationTypeFailure() {
activationSpec.setDestinationType("foobar"); activationSpec.setDestinationType("foobar");
PropertyDescriptor[] expected = {destinationTypeProperty}; PropertyDescriptor[] expected = {destinationTypeProperty};
assertActivationSpecInvalid(expected); assertActivationSpecInvalid(expected);
} }
@Test(timeout = 60000)
public void testQueueDestinationType() { public void testQueueDestinationType() {
activationSpec.setDestinationType(Queue.class.getName()); activationSpec.setDestinationType(Queue.class.getName());
assertActivationSpecValid(); assertActivationSpecValid();
} }
@Test(timeout = 60000)
public void testTopicDestinationType() { public void testTopicDestinationType() {
activationSpec.setDestinationType(Topic.class.getName()); activationSpec.setDestinationType(Topic.class.getName());
assertActivationSpecValid(); assertActivationSpecValid();
} }
@Test(timeout = 60000)
public void testSuccessfulCreateQueueDestination() { public void testSuccessfulCreateQueueDestination() {
activationSpec.setDestinationType(Queue.class.getName()); activationSpec.setDestinationType(Queue.class.getName());
activationSpec.setDestination(DESTINATION); activationSpec.setDestination(DESTINATION);
@ -108,6 +116,7 @@ public class ActiveMQActivationSpecTest extends TestCase {
assertTrue("Destination is not a Queue", destination instanceof Queue); assertTrue("Destination is not a Queue", destination instanceof Queue);
} }
@Test(timeout = 60000)
public void testSuccessfulCreateTopicDestination() { public void testSuccessfulCreateTopicDestination() {
activationSpec.setDestinationType(Topic.class.getName()); activationSpec.setDestinationType(Topic.class.getName());
activationSpec.setDestination(DESTINATION); activationSpec.setDestination(DESTINATION);
@ -118,6 +127,7 @@ public class ActiveMQActivationSpecTest extends TestCase {
assertTrue("Destination is not a Topic", destination instanceof Topic); assertTrue("Destination is not a Topic", destination instanceof Topic);
} }
@Test(timeout = 60000)
public void testCreateDestinationIncorrectType() { public void testCreateDestinationIncorrectType() {
activationSpec.setDestinationType(null); activationSpec.setDestinationType(null);
activationSpec.setDestination(DESTINATION); activationSpec.setDestination(DESTINATION);
@ -125,6 +135,7 @@ public class ActiveMQActivationSpecTest extends TestCase {
assertNull("ActiveMQDestination should not have been created", destination); assertNull("ActiveMQDestination should not have been created", destination);
} }
@Test(timeout = 60000)
public void testCreateDestinationIncorrectDestinationName() { public void testCreateDestinationIncorrectDestinationName() {
activationSpec.setDestinationType(Topic.class.getName()); activationSpec.setDestinationType(Topic.class.getName());
activationSpec.setDestination(null); activationSpec.setDestination(null);
@ -132,7 +143,9 @@ public class ActiveMQActivationSpecTest extends TestCase {
assertNull("ActiveMQDestination should not have been created", destination); assertNull("ActiveMQDestination should not have been created", destination);
} }
//----------- acknowledgeMode tests //----------- acknowledgeMode tests
@Test(timeout = 60000)
public void testDefaultAcknowledgeModeSetCorrectly() { public void testDefaultAcknowledgeModeSetCorrectly() {
assertEquals("Incorrect default value", ActiveMQActivationSpec.AUTO_ACKNOWLEDGE_MODE, assertEquals("Incorrect default value", ActiveMQActivationSpec.AUTO_ACKNOWLEDGE_MODE,
activationSpec.getAcknowledgeMode()); activationSpec.getAcknowledgeMode());
@ -140,6 +153,7 @@ public class ActiveMQActivationSpecTest extends TestCase {
activationSpec.getAcknowledgeModeForSession()); activationSpec.getAcknowledgeModeForSession());
} }
@Test(timeout = 60000)
public void testInvalidAcknowledgeMode() { public void testInvalidAcknowledgeMode() {
activationSpec.setAcknowledgeMode("foobar"); activationSpec.setAcknowledgeMode("foobar");
PropertyDescriptor[] expected = {acknowledgeModeProperty}; PropertyDescriptor[] expected = {acknowledgeModeProperty};
@ -148,6 +162,7 @@ public class ActiveMQActivationSpecTest extends TestCase {
activationSpec.getAcknowledgeModeForSession()); activationSpec.getAcknowledgeModeForSession());
} }
@Test(timeout = 60000)
public void testNoAcknowledgeMode() { public void testNoAcknowledgeMode() {
activationSpec.setAcknowledgeMode(null); activationSpec.setAcknowledgeMode(null);
PropertyDescriptor[] expected = {acknowledgeModeProperty}; PropertyDescriptor[] expected = {acknowledgeModeProperty};
@ -156,6 +171,7 @@ public class ActiveMQActivationSpecTest extends TestCase {
activationSpec.getAcknowledgeModeForSession()); activationSpec.getAcknowledgeModeForSession());
} }
@Test(timeout = 60000)
public void testSettingAutoAcknowledgeMode() { public void testSettingAutoAcknowledgeMode() {
activationSpec.setAcknowledgeMode(ActiveMQActivationSpec.AUTO_ACKNOWLEDGE_MODE); activationSpec.setAcknowledgeMode(ActiveMQActivationSpec.AUTO_ACKNOWLEDGE_MODE);
assertActivationSpecValid(); assertActivationSpecValid();
@ -163,6 +179,7 @@ public class ActiveMQActivationSpecTest extends TestCase {
activationSpec.getAcknowledgeModeForSession()); activationSpec.getAcknowledgeModeForSession());
} }
@Test(timeout = 60000)
public void testSettingDupsOkAcknowledgeMode() { public void testSettingDupsOkAcknowledgeMode() {
activationSpec.setAcknowledgeMode(ActiveMQActivationSpec.DUPS_OK_ACKNOWLEDGE_MODE); activationSpec.setAcknowledgeMode(ActiveMQActivationSpec.DUPS_OK_ACKNOWLEDGE_MODE);
assertActivationSpecValid(); assertActivationSpecValid();
@ -170,30 +187,36 @@ public class ActiveMQActivationSpecTest extends TestCase {
activationSpec.getAcknowledgeModeForSession()); activationSpec.getAcknowledgeModeForSession());
} }
//----------- subscriptionDurability tests //----------- subscriptionDurability tests
@Test(timeout = 60000)
public void testDefaultSubscriptionDurabilitySetCorrectly() { public void testDefaultSubscriptionDurabilitySetCorrectly() {
assertEquals("Incorrect default value", ActiveMQActivationSpec.NON_DURABLE_SUBSCRIPTION, assertEquals("Incorrect default value", ActiveMQActivationSpec.NON_DURABLE_SUBSCRIPTION, activationSpec.getSubscriptionDurability());
activationSpec.getSubscriptionDurability());
} }
@Test(timeout = 60000)
public void testInvalidSubscriptionDurability() { public void testInvalidSubscriptionDurability() {
activationSpec.setSubscriptionDurability("foobar"); activationSpec.setSubscriptionDurability("foobar");
PropertyDescriptor[] expected = {subscriptionDurabilityProperty}; PropertyDescriptor[] expected = {subscriptionDurabilityProperty};
assertActivationSpecInvalid(expected); assertActivationSpecInvalid(expected);
} }
@Test(timeout = 60000)
public void testNullSubscriptionDurability() { public void testNullSubscriptionDurability() {
activationSpec.setSubscriptionDurability(null); activationSpec.setSubscriptionDurability(null);
PropertyDescriptor[] expected = {subscriptionDurabilityProperty}; PropertyDescriptor[] expected = {subscriptionDurabilityProperty};
assertActivationSpecInvalid(expected); assertActivationSpecInvalid(expected);
} }
@Test(timeout = 60000)
public void testSettingNonDurableSubscriptionDurability() { public void testSettingNonDurableSubscriptionDurability() {
activationSpec.setSubscriptionDurability(ActiveMQActivationSpec.NON_DURABLE_SUBSCRIPTION); activationSpec.setSubscriptionDurability(ActiveMQActivationSpec.NON_DURABLE_SUBSCRIPTION);
assertActivationSpecValid(); assertActivationSpecValid();
} }
//----------- durable subscriber tests //----------- durable subscriber tests
@Test(timeout = 60000)
public void testValidDurableSubscriber() { public void testValidDurableSubscriber() {
activationSpec.setDestinationType(Topic.class.getName()); activationSpec.setDestinationType(Topic.class.getName());
activationSpec.setSubscriptionDurability(ActiveMQActivationSpec.DURABLE_SUBSCRIPTION); activationSpec.setSubscriptionDurability(ActiveMQActivationSpec.DURABLE_SUBSCRIPTION);
@ -203,6 +226,7 @@ public class ActiveMQActivationSpecTest extends TestCase {
assertTrue(activationSpec.isDurableSubscription()); assertTrue(activationSpec.isDurableSubscription());
} }
@Test(timeout = 60000)
public void testDurableSubscriberWithQueueDestinationTypeFailure() { public void testDurableSubscriberWithQueueDestinationTypeFailure() {
activationSpec.setDestinationType(Queue.class.getName()); activationSpec.setDestinationType(Queue.class.getName());
activationSpec.setSubscriptionDurability(ActiveMQActivationSpec.DURABLE_SUBSCRIPTION); activationSpec.setSubscriptionDurability(ActiveMQActivationSpec.DURABLE_SUBSCRIPTION);
@ -212,6 +236,7 @@ public class ActiveMQActivationSpecTest extends TestCase {
assertActivationSpecInvalid(expected); assertActivationSpecInvalid(expected);
} }
@Test(timeout = 60000)
public void testDurableSubscriberNoClientIdNoSubscriptionNameFailure() { public void testDurableSubscriberNoClientIdNoSubscriptionNameFailure() {
activationSpec.setDestinationType(Topic.class.getName()); activationSpec.setDestinationType(Topic.class.getName());
activationSpec.setSubscriptionDurability(ActiveMQActivationSpec.DURABLE_SUBSCRIPTION); activationSpec.setSubscriptionDurability(ActiveMQActivationSpec.DURABLE_SUBSCRIPTION);
@ -223,6 +248,7 @@ public class ActiveMQActivationSpecTest extends TestCase {
assertActivationSpecInvalid(expected); assertActivationSpecInvalid(expected);
} }
@Test(timeout = 60000)
public void testDurableSubscriberEmptyClientIdEmptySubscriptionNameFailure() { public void testDurableSubscriberEmptyClientIdEmptySubscriptionNameFailure() {
activationSpec.setDestinationType(Topic.class.getName()); activationSpec.setDestinationType(Topic.class.getName());
activationSpec.setSubscriptionDurability(ActiveMQActivationSpec.DURABLE_SUBSCRIPTION); activationSpec.setSubscriptionDurability(ActiveMQActivationSpec.DURABLE_SUBSCRIPTION);
@ -234,6 +260,7 @@ public class ActiveMQActivationSpecTest extends TestCase {
assertActivationSpecInvalid(expected); assertActivationSpecInvalid(expected);
} }
@Test(timeout = 60000)
public void testSetEmptyStringButGetNullValue() { public void testSetEmptyStringButGetNullValue() {
ActiveMQActivationSpec activationSpec = new ActiveMQActivationSpec(); ActiveMQActivationSpec activationSpec = new ActiveMQActivationSpec();
@ -259,7 +286,8 @@ public class ActiveMQActivationSpecTest extends TestCase {
assertNull("Property not null", activationSpec.getSubscriptionName()); assertNull("Property not null", activationSpec.getSubscriptionName());
} }
//----------- helper methods //----------- helper methods
private void assertActivationSpecValid() { private void assertActivationSpecValid() {
try { try {
activationSpec.validate(); activationSpec.validate();
@ -278,11 +306,11 @@ public class ActiveMQActivationSpecTest extends TestCase {
fail("InvalidPropertyException should have been thrown"); fail("InvalidPropertyException should have been thrown");
} catch (InvalidPropertyException e) { } catch (InvalidPropertyException e) {
PropertyDescriptor[] actual = e.getInvalidPropertyDescriptors(); PropertyDescriptor[] actual = e.getInvalidPropertyDescriptors();
assertEquals(expected, actual); assertDescriptorsAreEqual(expected, actual);
} }
} }
private static void assertEquals(PropertyDescriptor[] expected, PropertyDescriptor[] actual) { private static void assertDescriptorsAreEqual(PropertyDescriptor[] expected, PropertyDescriptor[] actual) {
/* /*
* This is kind of ugly. I originally created two HashSets and did an assertEquals(set1, set2) * This is kind of ugly. I originally created two HashSets and did an assertEquals(set1, set2)
* but because of a bug in the PropertyDescriptor class, it incorrectly fails. The problem is that the * but because of a bug in the PropertyDescriptor class, it incorrectly fails. The problem is that the
@ -319,5 +347,4 @@ public class ActiveMQActivationSpecTest extends TestCase {
assertFalse("ActiveMQActivationSpecs are equal", rightSpec.equals(leftSpec)); assertFalse("ActiveMQActivationSpecs are equal", rightSpec.equals(leftSpec));
assertFalse("HashCodes are equal", leftSpec.hashCode() == rightSpec.hashCode()); assertFalse("HashCodes are equal", leftSpec.hashCode() == rightSpec.hashCode());
} }
} }

View File

@ -1,59 +1,51 @@
/* /**
* Copyright 2008 hak8fe. * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * http://www.apache.org/licenses/LICENSE-2.0
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* distributed under the License is distributed on an "AS IS" BASIS, * See the License for the specific language governing permissions and
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * limitations under the License.
* See the License for the specific language governing permissions and
* limitations under the License.
* under the License.
*/ */
package org.apache.activemq.ra; package org.apache.activemq.ra;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.util.Timer;
import javax.jms.Connection; import javax.jms.Connection;
import javax.jms.Session; import javax.jms.Session;
import javax.jms.TopicSubscriber; import javax.jms.TopicSubscriber;
import javax.resource.spi.BootstrapContext;
import javax.resource.spi.UnavailableException;
import javax.resource.spi.XATerminator;
import javax.resource.spi.work.WorkManager;
import javax.transaction.xa.XAResource; import javax.transaction.xa.XAResource;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQTopicSubscriber; import org.apache.activemq.ActiveMQTopicSubscriber;
import org.junit.Before;
import org.junit.Test;
/** public class ActiveMQConnectionFactoryTest {
*
* @author hak8fe
*/
public class ActiveMQConnectionFactoryTest extends TestCase {
ActiveMQManagedConnectionFactory mcf; private ActiveMQManagedConnectionFactory mcf;
ActiveMQConnectionRequestInfo info; private ActiveMQConnectionRequestInfo info;
String url = "vm://localhost"; private String url = "vm://localhost?broker.persistent=false";
String user = "defaultUser"; private String user = "defaultUser";
String pwd = "defaultPasswd"; private String pwd = "defaultPasswd";
public ActiveMQConnectionFactoryTest(String testName) { @Before
super(testName); public void setUp() throws Exception {
}
@Override
protected void setUp() throws Exception {
super.setUp();
mcf = new ActiveMQManagedConnectionFactory(); mcf = new ActiveMQManagedConnectionFactory();
info = new ActiveMQConnectionRequestInfo(); info = new ActiveMQConnectionRequestInfo();
info.setServerUrl(url); info.setServerUrl(url);
@ -62,13 +54,8 @@ public class ActiveMQConnectionFactoryTest extends TestCase {
info.setAllPrefetchValues(new Integer(100)); info.setAllPrefetchValues(new Integer(100));
} }
@Override @Test(timeout = 60000)
protected void tearDown() throws Exception { public void testSerializability() throws Exception {
super.tearDown();
}
public void testSerializability() throws Exception
{
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(mcf, new ConnectionManagerAdapter(), info); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(mcf, new ConnectionManagerAdapter(), info);
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
@ -82,11 +69,12 @@ public class ActiveMQConnectionFactoryTest extends TestCase {
ois.close(); ois.close();
Connection con = deserializedFactory.createConnection("defaultUser", "defaultPassword"); Connection con = deserializedFactory.createConnection("defaultUser", "defaultPassword");
ActiveMQConnection connection = ((ActiveMQConnection)((ManagedConnectionProxy)con).getManagedConnection().getPhysicalConnection()); ActiveMQConnection connection = ((ActiveMQConnection) ((ManagedConnectionProxy) con).getManagedConnection().getPhysicalConnection());
assertEquals(100, connection.getPrefetchPolicy().getQueuePrefetch()); assertEquals(100, connection.getPrefetchPolicy().getQueuePrefetch());
assertNotNull("Connection object returned by ActiveMQConnectionFactory.createConnection() is null", con); assertNotNull("Connection object returned by ActiveMQConnectionFactory.createConnection() is null", con);
} }
@Test(timeout = 60000)
public void testOptimizeDurablePrefetch() throws Exception { public void testOptimizeDurablePrefetch() throws Exception {
ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter();
ra.setServerUrl(url); ra.setServerUrl(url);
@ -103,11 +91,11 @@ public class ActiveMQConnectionFactoryTest extends TestCase {
TopicSubscriber sub = sess.createDurableSubscriber(sess.createTopic("TEST"), "x"); TopicSubscriber sub = sess.createDurableSubscriber(sess.createTopic("TEST"), "x");
con.start(); con.start();
assertEquals(0, ((ActiveMQTopicSubscriber)sub).getPrefetchNumber()); assertEquals(0, ((ActiveMQTopicSubscriber) sub).getPrefetchNumber());
} }
@Test(timeout = 60000)
public void testGetXAResource() throws Exception { public void testGetXAResource() throws Exception {
ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter();
ra.setServerUrl(url); ra.setServerUrl(url);
ra.setUserName(user); ra.setUserName(user);

View File

@ -16,86 +16,95 @@
*/ */
package org.apache.activemq.ra; package org.apache.activemq.ra;
import junit.framework.TestCase; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** import org.junit.Before;
* import org.junit.Test;
*/
public class ActiveMQResourceAdapterJavaBeanEqualityTest extends TestCase { public class ActiveMQResourceAdapterJavaBeanEqualityTest {
private ActiveMQResourceAdapter raOne; private ActiveMQResourceAdapter raOne;
private ActiveMQResourceAdapter raTwo; private ActiveMQResourceAdapter raTwo;
public ActiveMQResourceAdapterJavaBeanEqualityTest(String name) { @Before
super(name); public void setUp() throws Exception {
}
protected void setUp() throws Exception {
super.setUp();
raOne = new ActiveMQResourceAdapter(); raOne = new ActiveMQResourceAdapter();
raTwo = new ActiveMQResourceAdapter(); raTwo = new ActiveMQResourceAdapter();
} }
@Test(timeout = 60000)
public void testSelfEquality() { public void testSelfEquality() {
assertEquality(raOne, raOne); assertEquality(raOne, raOne);
} }
@Test(timeout = 60000)
public void testEmptyEquality() { public void testEmptyEquality() {
assertEquality(raOne, raTwo); assertEquality(raOne, raTwo);
} }
@Test(timeout = 60000)
public void testNullEqualityFailure() { public void testNullEqualityFailure() {
assertFalse(raOne.equals(null)); assertFalse(raOne.equals(null));
} }
@Test(timeout = 60000)
public void testServerUrlEquality() { public void testServerUrlEquality() {
raOne.setServerUrl("one"); raOne.setServerUrl("one");
raTwo.setServerUrl("one"); raTwo.setServerUrl("one");
assertEquality(raOne, raTwo); assertEquality(raOne, raTwo);
} }
@Test(timeout = 60000)
public void testServerUrlInequality() { public void testServerUrlInequality() {
raOne.setServerUrl("one"); raOne.setServerUrl("one");
raTwo.setServerUrl("two"); raTwo.setServerUrl("two");
assertNonEquality(raOne, raTwo); assertNonEquality(raOne, raTwo);
} }
@Test(timeout = 60000)
public void testServerUrlInequalityDifferentCase() { public void testServerUrlInequalityDifferentCase() {
raOne.setServerUrl("one"); raOne.setServerUrl("one");
raTwo.setServerUrl("ONE"); raTwo.setServerUrl("ONE");
assertNonEquality(raOne, raTwo); assertNonEquality(raOne, raTwo);
} }
@Test(timeout = 60000)
public void testNullServerUrlInequality() { public void testNullServerUrlInequality() {
raOne.setServerUrl("one"); raOne.setServerUrl("one");
raTwo.setServerUrl(null); raTwo.setServerUrl(null);
assertNonEquality(raOne, raTwo); assertNonEquality(raOne, raTwo);
} }
@Test(timeout = 60000)
public void testBrokerXMLConfigEquality() { public void testBrokerXMLConfigEquality() {
raOne.setBrokerXmlConfig("one"); raOne.setBrokerXmlConfig("one");
raTwo.setBrokerXmlConfig("one"); raTwo.setBrokerXmlConfig("one");
assertEquality(raOne, raTwo); assertEquality(raOne, raTwo);
} }
@Test(timeout = 60000)
public void testBrokerXMLConfigInequality() { public void testBrokerXMLConfigInequality() {
raOne.setBrokerXmlConfig("one"); raOne.setBrokerXmlConfig("one");
raTwo.setBrokerXmlConfig("two"); raTwo.setBrokerXmlConfig("two");
assertNonEquality(raOne, raTwo); assertNonEquality(raOne, raTwo);
} }
@Test(timeout = 60000)
public void testBrokerXMLConfigInequalityDifferentCase() { public void testBrokerXMLConfigInequalityDifferentCase() {
raOne.setBrokerXmlConfig("one"); raOne.setBrokerXmlConfig("one");
raTwo.setBrokerXmlConfig("ONE"); raTwo.setBrokerXmlConfig("ONE");
assertNonEquality(raOne, raTwo); assertNonEquality(raOne, raTwo);
} }
@Test(timeout = 60000)
public void testNullBrokerXMLConfigInequality() { public void testNullBrokerXMLConfigInequality() {
raOne.setBrokerXmlConfig("one"); raOne.setBrokerXmlConfig("one");
raTwo.setBrokerXmlConfig(null); raTwo.setBrokerXmlConfig(null);
assertNonEquality(raOne, raTwo); assertNonEquality(raOne, raTwo);
} }
@Test(timeout = 60000)
public void testPasswordNotPartOfEquality() { public void testPasswordNotPartOfEquality() {
raOne.setClientid("one"); raOne.setClientid("one");
raTwo.setClientid("one"); raTwo.setClientid("one");
@ -115,5 +124,4 @@ public class ActiveMQResourceAdapterJavaBeanEqualityTest extends TestCase {
assertFalse("ActiveMQResourceAdapters are equal", rightRa.equals(leftRa)); assertFalse("ActiveMQResourceAdapters are equal", rightRa.equals(leftRa));
assertFalse("HashCodes are equal", leftRa.hashCode() == rightRa.hashCode()); assertFalse("HashCodes are equal", leftRa.hashCode() == rightRa.hashCode());
} }
} }

View File

@ -19,39 +19,40 @@ package org.apache.activemq.ra;
import javax.resource.spi.ConnectionEvent; import javax.resource.spi.ConnectionEvent;
import javax.resource.spi.ConnectionEventListener; import javax.resource.spi.ConnectionEventListener;
/**
*
*/
public class ConnectionEventListenerAdapter implements ConnectionEventListener { public class ConnectionEventListenerAdapter implements ConnectionEventListener {
/** /**
* @see javax.resource.spi.ConnectionEventListener#connectionClosed(javax.resource.spi.ConnectionEvent) * @see javax.resource.spi.ConnectionEventListener#connectionClosed(javax.resource.spi.ConnectionEvent)
*/ */
@Override
public void connectionClosed(ConnectionEvent arg0) { public void connectionClosed(ConnectionEvent arg0) {
} }
/** /**
* @see javax.resource.spi.ConnectionEventListener#localTransactionStarted(javax.resource.spi.ConnectionEvent) * @see javax.resource.spi.ConnectionEventListener#localTransactionStarted(javax.resource.spi.ConnectionEvent)
*/ */
@Override
public void localTransactionStarted(ConnectionEvent arg0) { public void localTransactionStarted(ConnectionEvent arg0) {
} }
/** /**
* @see javax.resource.spi.ConnectionEventListener#localTransactionCommitted(javax.resource.spi.ConnectionEvent) * @see javax.resource.spi.ConnectionEventListener#localTransactionCommitted(javax.resource.spi.ConnectionEvent)
*/ */
@Override
public void localTransactionCommitted(ConnectionEvent arg0) { public void localTransactionCommitted(ConnectionEvent arg0) {
} }
/** /**
* @see javax.resource.spi.ConnectionEventListener#localTransactionRolledback(javax.resource.spi.ConnectionEvent) * @see javax.resource.spi.ConnectionEventListener#localTransactionRolledback(javax.resource.spi.ConnectionEvent)
*/ */
@Override
public void localTransactionRolledback(ConnectionEvent arg0) { public void localTransactionRolledback(ConnectionEvent arg0) {
} }
/** /**
* @see javax.resource.spi.ConnectionEventListener#connectionErrorOccurred(javax.resource.spi.ConnectionEvent) * @see javax.resource.spi.ConnectionEventListener#connectionErrorOccurred(javax.resource.spi.ConnectionEvent)
*/ */
@Override
public void connectionErrorOccurred(ConnectionEvent arg0) { public void connectionErrorOccurred(ConnectionEvent arg0) {
} }
} }

View File

@ -34,16 +34,14 @@ import org.slf4j.LoggerFactory;
/** /**
* A simple implementation of a ConnectionManager that can be extended so that * A simple implementation of a ConnectionManager that can be extended so that
* it can see how the RA connections are interacting with it. * it can see how the RA connections are interacting with it.
*
*
*/ */
public class ConnectionManagerAdapter implements ConnectionManager, ConnectionEventListener { public class ConnectionManagerAdapter implements ConnectionManager, ConnectionEventListener {
private static final long serialVersionUID = 5205646563916645831L; private static final long serialVersionUID = 5205646563916645831L;
private static final Logger LOG = LoggerFactory.getLogger(ConnectionManagerAdapter.class); private static final Logger LOG = LoggerFactory.getLogger(ConnectionManagerAdapter.class);
ArrayList<ConnectionEventListener> listners = new ArrayList<ConnectionEventListener>(); private ArrayList<ConnectionEventListener> listners = new ArrayList<ConnectionEventListener>();
ArrayList<ManagedConnection> connections = new ArrayList<ManagedConnection>(); private ArrayList<ManagedConnection> connections = new ArrayList<ManagedConnection>();
/** /**
* Adds a listener to all connections created by this connection manager. * Adds a listener to all connections created by this connection manager.
@ -63,6 +61,7 @@ public class ConnectionManagerAdapter implements ConnectionManager, ConnectionEv
* @see javax.resource.spi.ConnectionManager#allocateConnection(javax.resource.spi.ManagedConnectionFactory, * @see javax.resource.spi.ConnectionManager#allocateConnection(javax.resource.spi.ManagedConnectionFactory,
* javax.resource.spi.ConnectionRequestInfo) * javax.resource.spi.ConnectionRequestInfo)
*/ */
@Override
public Object allocateConnection(ManagedConnectionFactory connectionFactory, ConnectionRequestInfo info) throws ResourceException { public Object allocateConnection(ManagedConnectionFactory connectionFactory, ConnectionRequestInfo info) throws ResourceException {
Subject subject = null; Subject subject = null;
ManagedConnection connection = connectionFactory.createManagedConnection(subject, info); ManagedConnection connection = connectionFactory.createManagedConnection(subject, info);
@ -78,6 +77,7 @@ public class ConnectionManagerAdapter implements ConnectionManager, ConnectionEv
/** /**
* @see javax.resource.spi.ConnectionEventListener#connectionClosed(javax.resource.spi.ConnectionEvent) * @see javax.resource.spi.ConnectionEventListener#connectionClosed(javax.resource.spi.ConnectionEvent)
*/ */
@Override
public void connectionClosed(ConnectionEvent event) { public void connectionClosed(ConnectionEvent event) {
connections.remove(event.getSource()); connections.remove(event.getSource());
try { try {
@ -85,6 +85,7 @@ public class ConnectionManagerAdapter implements ConnectionManager, ConnectionEv
} catch (ResourceException e) { } catch (ResourceException e) {
LOG.warn("Error occured during the cleanup of a managed connection: ", e); LOG.warn("Error occured during the cleanup of a managed connection: ", e);
} }
try { try {
((ManagedConnection)event.getSource()).destroy(); ((ManagedConnection)event.getSource()).destroy();
} catch (ResourceException e) { } catch (ResourceException e) {
@ -95,24 +96,28 @@ public class ConnectionManagerAdapter implements ConnectionManager, ConnectionEv
/** /**
* @see javax.resource.spi.ConnectionEventListener#localTransactionStarted(javax.resource.spi.ConnectionEvent) * @see javax.resource.spi.ConnectionEventListener#localTransactionStarted(javax.resource.spi.ConnectionEvent)
*/ */
@Override
public void localTransactionStarted(ConnectionEvent event) { public void localTransactionStarted(ConnectionEvent event) {
} }
/** /**
* @see javax.resource.spi.ConnectionEventListener#localTransactionCommitted(javax.resource.spi.ConnectionEvent) * @see javax.resource.spi.ConnectionEventListener#localTransactionCommitted(javax.resource.spi.ConnectionEvent)
*/ */
@Override
public void localTransactionCommitted(ConnectionEvent event) { public void localTransactionCommitted(ConnectionEvent event) {
} }
/** /**
* @see javax.resource.spi.ConnectionEventListener#localTransactionRolledback(javax.resource.spi.ConnectionEvent) * @see javax.resource.spi.ConnectionEventListener#localTransactionRolledback(javax.resource.spi.ConnectionEvent)
*/ */
@Override
public void localTransactionRolledback(ConnectionEvent event) { public void localTransactionRolledback(ConnectionEvent event) {
} }
/** /**
* @see javax.resource.spi.ConnectionEventListener#connectionErrorOccurred(javax.resource.spi.ConnectionEvent) * @see javax.resource.spi.ConnectionEventListener#connectionErrorOccurred(javax.resource.spi.ConnectionEvent)
*/ */
@Override
public void connectionErrorOccurred(ConnectionEvent event) { public void connectionErrorOccurred(ConnectionEvent event) {
LOG.warn("Managed connection experiened an error: ", event.getException()); LOG.warn("Managed connection experiened an error: ", event.getException());
try { try {
@ -120,11 +125,11 @@ public class ConnectionManagerAdapter implements ConnectionManager, ConnectionEv
} catch (ResourceException e) { } catch (ResourceException e) {
LOG.warn("Error occured during the cleanup of a managed connection: ", e); LOG.warn("Error occured during the cleanup of a managed connection: ", e);
} }
try { try {
((ManagedConnection)event.getSource()).destroy(); ((ManagedConnection)event.getSource()).destroy();
} catch (ResourceException e) { } catch (ResourceException e) {
LOG.warn("Error occured during the destruction of a managed connection: ", e); LOG.warn("Error occured during the destruction of a managed connection: ", e);
} }
} }
} }

View File

@ -16,6 +16,8 @@
*/ */
package org.apache.activemq.ra; package org.apache.activemq.ra;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
@ -44,21 +46,24 @@ import javax.resource.spi.work.WorkManager;
import javax.transaction.xa.XAResource; import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid; import javax.transaction.xa.Xid;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQQueue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
public class FailoverManagedClusterTest extends TestCase { public class FailoverManagedClusterTest {
private static final Logger LOG = LoggerFactory.getLogger(FailoverManagedClusterTest.class); private static final Logger LOG = LoggerFactory.getLogger(FailoverManagedClusterTest.class);
long txGenerator = System.currentTimeMillis(); long txGenerator = System.currentTimeMillis();
private static final String MASTER_BIND_ADDRESS = "tcp://0.0.0.0:61616"; private static final String MASTER_BIND_ADDRESS = "tcp://localhost:0";
private static final String SLAVE_BIND_ADDRESS = "tcp://0.0.0.0:61617"; private static final String SLAVE_BIND_ADDRESS = "tcp://localhost:0";
private static final String KAHADB_DIRECTORY = "target/activemq-data/";
private String masterConnectionUri; private String masterConnectionUri;
private String slaveConnectionUri; private String slaveConnectionUri;
@ -69,16 +74,16 @@ public class FailoverManagedClusterTest extends TestCase {
private BrokerService slave; private BrokerService slave;
private final CountDownLatch slaveThreadStarted = new CountDownLatch(1); private final CountDownLatch slaveThreadStarted = new CountDownLatch(1);
@Override @Before
protected void setUp() throws Exception { public void setUp() throws Exception {
createAndStartMaster(); createAndStartMaster();
createAndStartSlave(); createAndStartSlave();
brokerUri = "failover://(" + masterConnectionUri + "," + slaveConnectionUri + ")?randomize=false"; brokerUri = "failover://(" + masterConnectionUri + "," + slaveConnectionUri + ")?randomize=false";
} }
@Override @After
protected void tearDown() throws Exception { public void tearDown() throws Exception {
if (slave != null) { if (slave != null) {
slave.stop(); slave.stop();
} }
@ -92,6 +97,7 @@ public class FailoverManagedClusterTest extends TestCase {
master = new BrokerService(); master = new BrokerService();
master.setDeleteAllMessagesOnStartup(true); master.setDeleteAllMessagesOnStartup(true);
master.setUseJmx(false); master.setUseJmx(false);
master.setDataDirectory(KAHADB_DIRECTORY);
master.setBrokerName("BROKER"); master.setBrokerName("BROKER");
masterConnectionUri = master.addConnector(MASTER_BIND_ADDRESS).getPublishableConnectString(); masterConnectionUri = master.addConnector(MASTER_BIND_ADDRESS).getPublishableConnectString();
master.start(); master.start();
@ -101,6 +107,7 @@ public class FailoverManagedClusterTest extends TestCase {
private void createAndStartSlave() throws Exception { private void createAndStartSlave() throws Exception {
slave = new BrokerService(); slave = new BrokerService();
slave.setUseJmx(false); slave.setUseJmx(false);
slave.setDataDirectory(KAHADB_DIRECTORY);
slave.setBrokerName("BROKER"); slave.setBrokerName("BROKER");
slaveConnectionUri = slave.addConnector(SLAVE_BIND_ADDRESS).getPublishableConnectString(); slaveConnectionUri = slave.addConnector(SLAVE_BIND_ADDRESS).getPublishableConnectString();
@ -120,6 +127,7 @@ public class FailoverManagedClusterTest extends TestCase {
}).start(); }).start();
} }
@Test(timeout = 60000)
public void testFailover() throws Exception { public void testFailover() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerUri); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerUri);
@ -184,7 +192,6 @@ public class FailoverManagedClusterTest extends TestCase {
assertTrue(messageDelivered.await(5000, TimeUnit.MILLISECONDS)); assertTrue(messageDelivered.await(5000, TimeUnit.MILLISECONDS));
} }
private static final class StubBootstrapContext implements BootstrapContext { private static final class StubBootstrapContext implements BootstrapContext {
@Override @Override
public WorkManager getWorkManager() { public WorkManager getWorkManager() {
@ -271,7 +278,6 @@ public class FailoverManagedClusterTest extends TestCase {
public void onMessage(Message message) { public void onMessage(Message message) {
messageCount++; messageCount++;
} }
} }
public Xid createXid() throws IOException { public Xid createXid() throws IOException {
@ -298,5 +304,4 @@ public class FailoverManagedClusterTest extends TestCase {
} }
}; };
} }
} }

View File

@ -20,16 +20,17 @@ import java.util.HashSet;
import javax.resource.spi.ManagedConnection; import javax.resource.spi.ManagedConnection;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class FailoverManagedConnectionTest {
public class FailoverManagedConnectionTest extends TestCase {
private static final String BROKER_TRANSPORT = "tcp://localhost:61616"; private static final String BROKER_TRANSPORT = "tcp://localhost:61616";
private static final String BROKER_URL = "failover://" + BROKER_TRANSPORT; private static final String BROKER_URL = "failover://" + BROKER_TRANSPORT;
private static final String KAHADB_DIRECTORY = "target/activemq-data/";
private ActiveMQManagedConnectionFactory managedConnectionFactory; private ActiveMQManagedConnectionFactory managedConnectionFactory;
private ManagedConnection managedConnection; private ManagedConnection managedConnection;
@ -38,7 +39,8 @@ public class FailoverManagedConnectionTest extends TestCase {
private HashSet<ManagedConnection> connections; private HashSet<ManagedConnection> connections;
private ActiveMQConnectionRequestInfo connectionInfo; private ActiveMQConnectionRequestInfo connectionInfo;
protected void setUp() throws Exception { @Before
public void setUp() throws Exception {
createAndStartBroker(); createAndStartBroker();
@ -54,14 +56,20 @@ public class FailoverManagedConnectionTest extends TestCase {
connections.add(managedConnection); connections.add(managedConnection);
} }
@After
public void tearDown() throws Exception {
stopBroker();
}
private void createAndStartBroker() throws Exception { private void createAndStartBroker() throws Exception {
broker = new BrokerService(); broker = new BrokerService();
broker.addConnector(BROKER_TRANSPORT); broker.addConnector(BROKER_TRANSPORT);
broker.setDataDirectory(KAHADB_DIRECTORY);
broker.start(); broker.start();
broker.waitUntilStarted(); broker.waitUntilStarted();
} }
@Test(timeout = 60000)
public void testFailoverBeforeClose() throws Exception { public void testFailoverBeforeClose() throws Exception {
createConnectionAndProxyAndSession(); createConnectionAndProxyAndSession();
@ -78,25 +86,21 @@ public class FailoverManagedConnectionTest extends TestCase {
} }
} }
private void cleanupConnectionAndProxyAndSession() throws Exception { private void cleanupConnectionAndProxyAndSession() throws Exception {
proxy.close(); proxy.close();
managedConnection.cleanup(); managedConnection.cleanup();
} }
private void createConnectionAndProxyAndSession() throws Exception { private void createConnectionAndProxyAndSession() throws Exception {
managedConnection = managedConnection = managedConnectionFactory.matchManagedConnections(connections, null, connectionInfo);
managedConnectionFactory.matchManagedConnections(connections, null, connectionInfo); proxy = (ManagedConnectionProxy) managedConnection.getConnection(null, null);
proxy =
(ManagedConnectionProxy) managedConnection.getConnection(null, null);
proxy.createSession(false, 0); proxy.createSession(false, 0);
} }
private void stopBroker() throws Exception { private void stopBroker() throws Exception {
broker.stop(); if (broker != null) {
broker.waitUntilStopped(); broker.stop();
broker.waitUntilStopped();
}
} }
} }

View File

@ -1,45 +1,40 @@
/* /**
* Licensed to the Apache Software Foundation (ASF) under one * Licensed to the Apache Software Foundation (ASF) under one or more
* or more contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file distributed with
* distributed with this work for additional information * this work for additional information regarding copyright ownership.
* regarding copyright ownership. The ASF licenses this file * The ASF licenses this file to You under the Apache License, Version 2.0
* to you under the Apache License, Version 2.0 (the * (the "License"); you may not use this file except in compliance with
* "License"); you may not use this file except in compliance * the License. You may obtain a copy of the License at
* with the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing, software
* software distributed under the License is distributed on an * distributed under the License is distributed on an "AS IS" BASIS,
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* KIND, either express or implied. See the License for the * See the License for the specific language governing permissions and
* specific language governing permissions and limitations * limitations under the License.
* under the License.
*/ */
package org.apache.activemq.ra; package org.apache.activemq.ra;
import java.io.IOException;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException;
import javax.jms.ConnectionFactory; import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Session; import javax.jms.Session;
import javax.resource.spi.ManagedConnection;
import javax.transaction.xa.XAResource; import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid; import javax.transaction.xa.Xid;
import javax.resource.spi.ManagedConnection;
import javax.resource.ResourceException;
import org.apache.activemq.*; import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQPrefetchPolicy;
import org.apache.activemq.JmsQueueTransactionTest;
/**
* @version $Rev$ $Date$
*/
public class JmsXAQueueTransactionTest extends JmsQueueTransactionTest { public class JmsXAQueueTransactionTest extends JmsQueueTransactionTest {
private static final String DEFAULT_HOST = "vm://localhost";
private static final String KAHADB_DIRECTORY = "target/activemq-data/";
private static final String DEFAULT_HOST = "vm://localhost?broker.dataDirectory=" + KAHADB_DIRECTORY;
private ConnectionManagerAdapter connectionManager = new ConnectionManagerAdapter(); private ConnectionManagerAdapter connectionManager = new ConnectionManagerAdapter();
private ActiveMQManagedConnectionFactory managedConnectionFactory; private ActiveMQManagedConnectionFactory managedConnectionFactory;
@ -63,7 +58,6 @@ public class JmsXAQueueTransactionTest extends JmsQueueTransactionTest {
return (ConnectionFactory)managedConnectionFactory.createConnectionFactory(connectionManager); return (ConnectionFactory)managedConnectionFactory.createConnectionFactory(connectionManager);
} }
/** /**
* Recreates the connection. * Recreates the connection.
* *
@ -134,19 +128,20 @@ public class JmsXAQueueTransactionTest extends JmsQueueTransactionTest {
final byte[] bs = baos.toByteArray(); final byte[] bs = baos.toByteArray();
return new Xid() { return new Xid() {
@Override
public int getFormatId() { public int getFormatId() {
return 86; return 86;
} }
@Override
public byte[] getGlobalTransactionId() { public byte[] getGlobalTransactionId() {
return bs; return bs;
} }
@Override
public byte[] getBranchQualifier() { public byte[] getBranchQualifier() {
return bs; return bs;
} }
}; };
} }
} }

View File

@ -1,47 +1,44 @@
/* /**
* Licensed to the Apache Software Foundation (ASF) under one * Licensed to the Apache Software Foundation (ASF) under one or more
* or more contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file distributed with
* distributed with this work for additional information * this work for additional information regarding copyright ownership.
* regarding copyright ownership. The ASF licenses this file * The ASF licenses this file to You under the Apache License, Version 2.0
* to you under the Apache License, Version 2.0 (the * (the "License"); you may not use this file except in compliance with
* "License"); you may not use this file except in compliance * the License. You may obtain a copy of the License at
* with the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing, software
* software distributed under the License is distributed on an * distributed under the License is distributed on an "AS IS" BASIS,
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* KIND, either express or implied. See the License for the * See the License for the specific language governing permissions and
* specific language governing permissions and limitations * limitations under the License.
* under the License.
*/ */
package org.apache.activemq.ra; package org.apache.activemq.ra;
import java.io.IOException;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException;
import javax.jms.Connection;
import javax.jms.ConnectionFactory; import javax.jms.ConnectionFactory;
import javax.jms.Session; import javax.jms.Session;
import javax.jms.Connection; import javax.resource.ResourceException;
import javax.resource.spi.ManagedConnection;
import javax.transaction.xa.XAResource; import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid; import javax.transaction.xa.Xid;
import javax.resource.spi.ManagedConnection;
import javax.resource.ResourceException;
import org.apache.activemq.*; import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQPrefetchPolicy;
import org.apache.activemq.JmsQueueTransactionTest;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/**
* @version $Rev$ $Date$
*/
public class JmsXARollback2CxTransactionTest extends JmsQueueTransactionTest { public class JmsXARollback2CxTransactionTest extends JmsQueueTransactionTest {
protected static final Logger LOG = LoggerFactory.getLogger(JmsXARollback2CxTransactionTest.class); protected static final Logger LOG = LoggerFactory.getLogger(JmsXARollback2CxTransactionTest.class);
private static final String DEFAULT_HOST = "vm://localhost?create=false"; private static final String DEFAULT_HOST = "vm://localhost?create=false";
private ConnectionManagerAdapter connectionManager = new ConnectionManagerAdapter(); private ConnectionManagerAdapter connectionManager = new ConnectionManagerAdapter();
@ -163,19 +160,20 @@ public class JmsXARollback2CxTransactionTest extends JmsQueueTransactionTest {
final byte[] bs = baos.toByteArray(); final byte[] bs = baos.toByteArray();
return new Xid() { return new Xid() {
@Override
public int getFormatId() { public int getFormatId() {
return 86; return 86;
} }
@Override
public byte[] getGlobalTransactionId() { public byte[] getGlobalTransactionId() {
return bs; return bs;
} }
@Override
public byte[] getBranchQualifier() { public byte[] getBranchQualifier() {
return bs; return bs;
} }
}; };
} }
} }

View File

@ -16,6 +16,12 @@
*/ */
package org.apache.activemq.ra; package org.apache.activemq.ra;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
@ -52,7 +58,6 @@ import javax.resource.spi.work.WorkManager;
import javax.transaction.xa.XAResource; import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid; import javax.transaction.xa.Xid;
import org.junit.Test;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.advisory.AdvisorySupport; import org.apache.activemq.advisory.AdvisorySupport;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
@ -69,53 +74,61 @@ import org.apache.log4j.LogManager;
import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.ErrorHandler;
import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LoggingEvent;
import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static org.junit.Assert.*;
public class MDBTest { public class MDBTest {
private static final Logger LOG = LoggerFactory.getLogger(MDBTest.class); private static final Logger LOG = LoggerFactory.getLogger(MDBTest.class);
long txGenerator = System.currentTimeMillis(); private long txGenerator = System.currentTimeMillis();
private AtomicInteger id = new AtomicInteger(0);
private static final class StubBootstrapContext implements BootstrapContext { private static final class StubBootstrapContext implements BootstrapContext {
@Override
public WorkManager getWorkManager() { public WorkManager getWorkManager() {
return new WorkManager() { return new WorkManager() {
@Override
public void doWork(Work work) throws WorkException { public void doWork(Work work) throws WorkException {
new Thread(work).start(); new Thread(work).start();
} }
@Override
public void doWork(Work work, long arg1, ExecutionContext arg2, WorkListener arg3) throws WorkException { public void doWork(Work work, long arg1, ExecutionContext arg2, WorkListener arg3) throws WorkException {
new Thread(work).start(); new Thread(work).start();
} }
@Override
public long startWork(Work work) throws WorkException { public long startWork(Work work) throws WorkException {
new Thread(work).start(); new Thread(work).start();
return 0; return 0;
} }
@Override
public long startWork(Work work, long arg1, ExecutionContext arg2, WorkListener arg3) throws WorkException { public long startWork(Work work, long arg1, ExecutionContext arg2, WorkListener arg3) throws WorkException {
new Thread(work).start(); new Thread(work).start();
return 0; return 0;
} }
@Override
public void scheduleWork(Work work) throws WorkException { public void scheduleWork(Work work) throws WorkException {
new Thread(work).start(); new Thread(work).start();
} }
@Override
public void scheduleWork(Work work, long arg1, ExecutionContext arg2, WorkListener arg3) throws WorkException { public void scheduleWork(Work work, long arg1, ExecutionContext arg2, WorkListener arg3) throws WorkException {
new Thread(work).start(); new Thread(work).start();
} }
}; };
} }
@Override
public XATerminator getXATerminator() { public XATerminator getXATerminator() {
return null; return null;
} }
@Override
public Timer createTimer() throws UnavailableException { public Timer createTimer() throws UnavailableException {
return null; return null;
} }
@ -126,6 +139,7 @@ public class MDBTest {
public XAResource xaresource; public XAResource xaresource;
public Xid xid; public Xid xid;
@Override
public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException { public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException {
try { try {
if (xid == null) { if (xid == null) {
@ -138,6 +152,7 @@ public class MDBTest {
} }
} }
@Override
public void afterDelivery() throws ResourceException { public void afterDelivery() throws ResourceException {
try { try {
xaresource.end(xid, 0); xaresource.end(xid, 0);
@ -150,17 +165,18 @@ public class MDBTest {
} }
} }
@Override
public void release() { public void release() {
LOG.info("In release, messageCount: " + messageCount + ", xid:" + xid); LOG.info("In release, messageCount: " + messageCount + ", xid:" + xid);
} }
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
messageCount++; messageCount++;
} }
} }
@Test @Test(timeout = 90000)
public void testDestinationInJndi() throws Exception{ public void testDestinationInJndi() throws Exception{
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
Connection connection = factory.createConnection(); Connection connection = factory.createConnection();
@ -177,6 +193,7 @@ public class MDBTest {
final CountDownLatch messageDelivered = new CountDownLatch(1); final CountDownLatch messageDelivered = new CountDownLatch(1);
final StubMessageEndpoint endpoint = new StubMessageEndpoint() { final StubMessageEndpoint endpoint = new StubMessageEndpoint() {
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
super.onMessage(message); super.onMessage(message);
messageDelivered.countDown(); messageDelivered.countDown();
@ -191,11 +208,13 @@ public class MDBTest {
activationSpec.validate(); activationSpec.validate();
MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() { MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() {
@Override
public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException { public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException {
endpoint.xaresource = resource; endpoint.xaresource = resource;
return endpoint; return endpoint;
} }
@Override
public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException { public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException {
return true; return true;
} }
@ -225,7 +244,7 @@ public class MDBTest {
adapter.stop(); adapter.stop();
} }
@Test @Test(timeout = 90000)
public void testMessageDelivery() throws Exception { public void testMessageDelivery() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
@ -243,6 +262,7 @@ public class MDBTest {
final CountDownLatch messageDelivered = new CountDownLatch(1); final CountDownLatch messageDelivered = new CountDownLatch(1);
final StubMessageEndpoint endpoint = new StubMessageEndpoint() { final StubMessageEndpoint endpoint = new StubMessageEndpoint() {
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
super.onMessage(message); super.onMessage(message);
messageDelivered.countDown(); messageDelivered.countDown();
@ -256,11 +276,13 @@ public class MDBTest {
activationSpec.validate(); activationSpec.validate();
MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() { MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() {
@Override
public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException { public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException {
endpoint.xaresource = resource; endpoint.xaresource = resource;
return endpoint; return endpoint;
} }
@Override
public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException { public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException {
return true; return true;
} }
@ -288,11 +310,10 @@ public class MDBTest {
// Shut the Endpoint down. // Shut the Endpoint down.
adapter.endpointDeactivation(messageEndpointFactory, activationSpec); adapter.endpointDeactivation(messageEndpointFactory, activationSpec);
adapter.stop(); adapter.stop();
} }
//https://issues.apache.org/jira/browse/AMQ-5811 //https://issues.apache.org/jira/browse/AMQ-5811
@Test @Test(timeout = 90000)
public void testAsyncStop() throws Exception { public void testAsyncStop() throws Exception {
for (int repeat = 0; repeat < 10; repeat++) { for (int repeat = 0; repeat < 10; repeat++) {
ActiveMQResourceAdapter adapter = new ActiveMQResourceAdapter(); ActiveMQResourceAdapter adapter = new ActiveMQResourceAdapter();
@ -308,6 +329,7 @@ public class MDBTest {
final StubMessageEndpoint endpoint = new StubMessageEndpoint() final StubMessageEndpoint endpoint = new StubMessageEndpoint()
{ {
@Override
public void onMessage(Message message) public void onMessage(Message message)
{ {
super.onMessage(message); super.onMessage(message);
@ -321,11 +343,13 @@ public class MDBTest {
activationSpecs[i].validate(); activationSpecs[i].validate();
endpointFactories[i] = new MessageEndpointFactory() { endpointFactories[i] = new MessageEndpointFactory() {
@Override
public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException { public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException {
endpoint.xaresource = resource; endpoint.xaresource = resource;
return endpoint; return endpoint;
} }
@Override
public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException { public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException {
return true; return true;
} }
@ -356,6 +380,7 @@ public class MDBTest {
final ActiveMQActivationSpec activationSpec = activationSpecs[i]; final ActiveMQActivationSpec activationSpec = activationSpecs[i];
threads[i] = new Thread() { threads[i] = new Thread() {
@Override
public void run() { public void run() {
adapter.endpointDeactivation(endpointFactory, activationSpec); adapter.endpointDeactivation(endpointFactory, activationSpec);
} }
@ -364,7 +389,7 @@ public class MDBTest {
return threads; return threads;
} }
@Test @Test(timeout = 90000)
public void testErrorOnNoMessageDeliveryBrokerZeroPrefetchConfig() throws Exception { public void testErrorOnNoMessageDeliveryBrokerZeroPrefetchConfig() throws Exception {
final BrokerService brokerService = new BrokerService(); final BrokerService brokerService = new BrokerService();
@ -438,8 +463,8 @@ public class MDBTest {
return false; return false;
} }
}; };
LogManager.getRootLogger().addAppender(testAppender);
LogManager.getRootLogger().addAppender(testAppender);
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerUrl); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerUrl);
Connection connection = factory.createConnection(); Connection connection = factory.createConnection();
@ -455,6 +480,7 @@ public class MDBTest {
final CountDownLatch messageDelivered = new CountDownLatch(1); final CountDownLatch messageDelivered = new CountDownLatch(1);
final StubMessageEndpoint endpoint = new StubMessageEndpoint() { final StubMessageEndpoint endpoint = new StubMessageEndpoint() {
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
super.onMessage(message); super.onMessage(message);
messageDelivered.countDown(); messageDelivered.countDown();
@ -468,11 +494,13 @@ public class MDBTest {
activationSpec.validate(); activationSpec.validate();
MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() { MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() {
@Override
public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException { public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException {
endpoint.xaresource = resource; endpoint.xaresource = resource;
return endpoint; return endpoint;
} }
@Override
public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException { public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException {
return true; return true;
} }
@ -524,6 +552,7 @@ public class MDBTest {
final AtomicBoolean failed = new AtomicBoolean(false); final AtomicBoolean failed = new AtomicBoolean(false);
final StubMessageEndpoint endpoint = new StubMessageEndpoint() { final StubMessageEndpoint endpoint = new StubMessageEndpoint() {
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
super.onMessage(message); super.onMessage(message);
try { try {
@ -545,6 +574,7 @@ public class MDBTest {
} }
}; };
@Override
public void afterDelivery() throws ResourceException { public void afterDelivery() throws ResourceException {
try { try {
if (!messageDelivered.await(1, TimeUnit.MILLISECONDS)) { if (!messageDelivered.await(1, TimeUnit.MILLISECONDS)) {
@ -569,11 +599,13 @@ public class MDBTest {
activationSpec.validate(); activationSpec.validate();
MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() { MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() {
@Override
public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException { public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException {
endpoint.xaresource = resource; endpoint.xaresource = resource;
return endpoint; return endpoint;
} }
@Override
public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException { public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException {
return true; return true;
} }
@ -601,10 +633,9 @@ public class MDBTest {
// Shut the Endpoint down. // Shut the Endpoint down.
adapter.endpointDeactivation(messageEndpointFactory, activationSpec); adapter.endpointDeactivation(messageEndpointFactory, activationSpec);
adapter.stop(); adapter.stop();
} }
@Test @Test(timeout = 90000)
public void testOrderOfMessageExceptionReDelivery() throws Exception { public void testOrderOfMessageExceptionReDelivery() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
@ -618,6 +649,7 @@ public class MDBTest {
final List<Integer> orderedReceipt = new ArrayList<Integer>(); final List<Integer> orderedReceipt = new ArrayList<Integer>();
final StubMessageEndpoint endpoint = new StubMessageEndpoint() { final StubMessageEndpoint endpoint = new StubMessageEndpoint() {
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
super.onMessage(message); super.onMessage(message);
if (messageCount == 2) { if (messageCount == 2) {
@ -630,6 +662,7 @@ public class MDBTest {
} }
}; };
@Override
public void afterDelivery() throws ResourceException { public void afterDelivery() throws ResourceException {
try { try {
if (messageCount == 2) { if (messageCount == 2) {
@ -658,11 +691,13 @@ public class MDBTest {
activationSpec.validate(); activationSpec.validate();
MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() { MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() {
@Override
public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException { public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException {
endpoint.xaresource = resource; endpoint.xaresource = resource;
return endpoint; return endpoint;
} }
@Override
public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException { public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException {
return true; return true;
} }
@ -701,10 +736,9 @@ public class MDBTest {
// Shut the Endpoint down. // Shut the Endpoint down.
adapter.endpointDeactivation(messageEndpointFactory, activationSpec); adapter.endpointDeactivation(messageEndpointFactory, activationSpec);
adapter.stop(); adapter.stop();
} }
@Test @Test(timeout = 90000)
public void testXaTimeoutRedelivery() throws Exception { public void testXaTimeoutRedelivery() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
@ -718,6 +752,7 @@ public class MDBTest {
final CountDownLatch messageDelivered = new CountDownLatch(2); final CountDownLatch messageDelivered = new CountDownLatch(2);
final StubMessageEndpoint endpoint = new StubMessageEndpoint() { final StubMessageEndpoint endpoint = new StubMessageEndpoint() {
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
super.onMessage(message); super.onMessage(message);
try { try {
@ -742,6 +777,7 @@ public class MDBTest {
} }
}; };
@Override
public void afterDelivery() throws ResourceException { public void afterDelivery() throws ResourceException {
try { try {
xaresource.end(xid, XAResource.TMSUCCESS); xaresource.end(xid, XAResource.TMSUCCESS);
@ -759,11 +795,13 @@ public class MDBTest {
activationSpec.validate(); activationSpec.validate();
MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() { MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() {
@Override
public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException { public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException {
endpoint.xaresource = resource; endpoint.xaresource = resource;
return endpoint; return endpoint;
} }
@Override
public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException { public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException {
return true; return true;
} }
@ -776,7 +814,6 @@ public class MDBTest {
try { try {
Thread.sleep(1000); Thread.sleep(1000);
} catch (Exception e) { } catch (Exception e) {
} }
// Send the broker a message to that endpoint // Send the broker a message to that endpoint
@ -790,10 +827,8 @@ public class MDBTest {
// Shut the Endpoint down. // Shut the Endpoint down.
adapter.endpointDeactivation(messageEndpointFactory, activationSpec); adapter.endpointDeactivation(messageEndpointFactory, activationSpec);
adapter.stop(); adapter.stop();
} }
AtomicInteger id = new AtomicInteger(0);
public Xid createXid() throws IOException { public Xid createXid() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream os = new DataOutputStream(baos); DataOutputStream os = new DataOutputStream(baos);
@ -804,23 +839,25 @@ public class MDBTest {
return new Xid() { return new Xid() {
final int lid = id.get(); final int lid = id.get();
@Override
public int getFormatId() { public int getFormatId() {
return 86; return 86;
} }
@Override
public byte[] getGlobalTransactionId() { public byte[] getGlobalTransactionId() {
return bs; return bs;
} }
@Override
public byte[] getBranchQualifier() { public byte[] getBranchQualifier() {
return bs; return bs;
} }
@Override
public String toString() { public String toString() {
return "DummyIdXID:" + lid; return "DummyIdXID:" + lid;
} }
}; };
} }
} }

View File

@ -16,6 +16,13 @@
*/ */
package org.apache.activemq.ra; package org.apache.activemq.ra;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
@ -36,23 +43,18 @@ import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.ManagedConnection; import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ManagedConnectionFactory; import javax.resource.spi.ManagedConnectionFactory;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Before;
import org.junit.Test;
/** public class ManagedConnectionFactoryTest {
*
*/
public class ManagedConnectionFactoryTest extends TestCase {
private static final String DEFAULT_HOST = "vm://localhost?broker.persistent=false&broker.schedulerSupport=false"; private static final String DEFAULT_HOST = "vm://localhost?broker.persistent=false&broker.schedulerSupport=false";
private static final String REMOTE_HOST = "vm://remotehost?broker.persistent=false&broker.schedulerSupport=false"; private static final String REMOTE_HOST = "vm://remotehost?broker.persistent=false&broker.schedulerSupport=false";
private ActiveMQManagedConnectionFactory managedConnectionFactory; private ActiveMQManagedConnectionFactory managedConnectionFactory;
/** @Before
* @see junit.framework.TestCase#setUp() public void setUp() throws Exception {
*/
protected void setUp() throws Exception {
managedConnectionFactory = new ActiveMQManagedConnectionFactory(); managedConnectionFactory = new ActiveMQManagedConnectionFactory();
managedConnectionFactory.setServerUrl(DEFAULT_HOST); managedConnectionFactory.setServerUrl(DEFAULT_HOST);
managedConnectionFactory.setUserName(ActiveMQConnectionFactory.DEFAULT_USER); managedConnectionFactory.setUserName(ActiveMQConnectionFactory.DEFAULT_USER);
@ -60,17 +62,19 @@ public class ManagedConnectionFactoryTest extends TestCase {
managedConnectionFactory.setUseSessionArgs(false); managedConnectionFactory.setUseSessionArgs(false);
} }
@Test(timeout = 60000)
public void testConnectionFactoryAllocation() throws ResourceException, JMSException { public void testConnectionFactoryAllocation() throws ResourceException, JMSException {
// Make sure that the ConnectionFactory is asking the connection manager // Make sure that the ConnectionFactory is asking the connection manager
// to // to allocate the connection.
// allocate the connection.
final boolean allocateRequested[] = new boolean[] { final boolean allocateRequested[] = new boolean[] {
false false
}; };
Object cf = managedConnectionFactory.createConnectionFactory(new ConnectionManagerAdapter() { Object cf = managedConnectionFactory.createConnectionFactory(new ConnectionManagerAdapter() {
private static final long serialVersionUID = 1699499816530099939L; private static final long serialVersionUID = 1699499816530099939L;
@Override
public Object allocateConnection(ManagedConnectionFactory connectionFactory, ConnectionRequestInfo info) throws ResourceException { public Object allocateConnection(ManagedConnectionFactory connectionFactory, ConnectionRequestInfo info) throws ResourceException {
allocateRequested[0] = true; allocateRequested[0] = true;
return super.allocateConnection(connectionFactory, info); return super.allocateConnection(connectionFactory, info);
@ -94,9 +98,9 @@ public class ManagedConnectionFactoryTest extends TestCase {
assertFalse("transacted attribute is ignored, only transacted with xa or local tx", session.getTransacted()); assertFalse("transacted attribute is ignored, only transacted with xa or local tx", session.getTransacted());
connection.close(); connection.close();
} }
@Test(timeout = 60000)
public void testConnectionSessionArgs() throws ResourceException, JMSException { public void testConnectionSessionArgs() throws ResourceException, JMSException {
ActiveMQConnectionRequestInfo connectionRequestInfo = new ActiveMQConnectionRequestInfo(); ActiveMQConnectionRequestInfo connectionRequestInfo = new ActiveMQConnectionRequestInfo();
connectionRequestInfo.setServerUrl(DEFAULT_HOST); connectionRequestInfo.setServerUrl(DEFAULT_HOST);
@ -112,6 +116,7 @@ public class ManagedConnectionFactoryTest extends TestCase {
connection.close(); connection.close();
} }
@Test(timeout = 60000)
public void testConnectionFactoryConnectionMatching() throws ResourceException, JMSException { public void testConnectionFactoryConnectionMatching() throws ResourceException, JMSException {
ActiveMQConnectionRequestInfo ri1 = new ActiveMQConnectionRequestInfo(); ActiveMQConnectionRequestInfo ri1 = new ActiveMQConnectionRequestInfo();
@ -150,6 +155,7 @@ public class ManagedConnectionFactoryTest extends TestCase {
} }
} }
@Test(timeout = 60000)
public void testConnectionFactoryIsSerializableAndReferenceable() throws ResourceException, JMSException { public void testConnectionFactoryIsSerializableAndReferenceable() throws ResourceException, JMSException {
Object cf = managedConnectionFactory.createConnectionFactory(new ConnectionManagerAdapter()); Object cf = managedConnectionFactory.createConnectionFactory(new ConnectionManagerAdapter());
assertTrue(cf != null); assertTrue(cf != null);
@ -157,12 +163,14 @@ public class ManagedConnectionFactoryTest extends TestCase {
assertTrue(cf instanceof Referenceable); assertTrue(cf instanceof Referenceable);
} }
@Test(timeout = 60000)
public void testImplementsQueueAndTopicConnectionFactory() throws Exception { public void testImplementsQueueAndTopicConnectionFactory() throws Exception {
Object cf = managedConnectionFactory.createConnectionFactory(new ConnectionManagerAdapter()); Object cf = managedConnectionFactory.createConnectionFactory(new ConnectionManagerAdapter());
assertTrue(cf instanceof QueueConnectionFactory); assertTrue(cf instanceof QueueConnectionFactory);
assertTrue(cf instanceof TopicConnectionFactory); assertTrue(cf instanceof TopicConnectionFactory);
} }
@Test(timeout = 60000)
public void testSerializability() throws Exception { public void testSerializability() throws Exception {
managedConnectionFactory.setLogWriter(new PrintWriter(new ByteArrayOutputStream())); managedConnectionFactory.setLogWriter(new PrintWriter(new ByteArrayOutputStream()));
@ -190,6 +198,5 @@ public class ManagedConnectionFactoryTest extends TestCase {
assertNotNull( assertNotNull(
"Log instance of deserialized ActiveMQManagedConnectionFactory is null", "Log instance of deserialized ActiveMQManagedConnectionFactory is null",
deserializedFactory.log); deserializedFactory.log);
} }
} }

View File

@ -16,6 +16,11 @@
*/ */
package org.apache.activemq.ra; package org.apache.activemq.ra;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import javax.jms.ConnectionFactory; import javax.jms.ConnectionFactory;
import javax.jms.JMSException; import javax.jms.JMSException;
import javax.jms.MessageProducer; import javax.jms.MessageProducer;
@ -28,13 +33,11 @@ import javax.jms.TopicConnectionFactory;
import javax.resource.ResourceException; import javax.resource.ResourceException;
import javax.resource.spi.ConnectionEvent; import javax.resource.spi.ConnectionEvent;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Before;
import org.junit.Test;
/** public class ManagedConnectionTest {
*
*/
public class ManagedConnectionTest extends TestCase {
private static final String DEFAULT_HOST = "vm://localhost?broker.persistent=false"; private static final String DEFAULT_HOST = "vm://localhost?broker.persistent=false";
@ -44,10 +47,8 @@ public class ManagedConnectionTest extends TestCase {
private ManagedConnectionProxy connection; private ManagedConnectionProxy connection;
private ActiveMQManagedConnection managedConnection; private ActiveMQManagedConnection managedConnection;
/** @Before
* @see junit.framework.TestCase#setUp() public void setUp() throws Exception {
*/
protected void setUp() throws Exception {
managedConnectionFactory = new ActiveMQManagedConnectionFactory(); managedConnectionFactory = new ActiveMQManagedConnectionFactory();
managedConnectionFactory.setServerUrl(DEFAULT_HOST); managedConnectionFactory.setServerUrl(DEFAULT_HOST);
@ -60,12 +61,14 @@ public class ManagedConnectionTest extends TestCase {
} }
@Test(timeout = 60000)
public void testConnectionCloseEvent() throws ResourceException, JMSException { public void testConnectionCloseEvent() throws ResourceException, JMSException {
final boolean test[] = new boolean[] { final boolean test[] = new boolean[] {
false false
}; };
connectionManager.addConnectionEventListener(new ConnectionEventListenerAdapter() { connectionManager.addConnectionEventListener(new ConnectionEventListenerAdapter() {
@Override
public void connectionClosed(ConnectionEvent arg0) { public void connectionClosed(ConnectionEvent arg0) {
test[0] = true; test[0] = true;
} }
@ -74,12 +77,14 @@ public class ManagedConnectionTest extends TestCase {
assertTrue(test[0]); assertTrue(test[0]);
} }
@Test(timeout = 60000)
public void testLocalTransactionCommittedEvent() throws ResourceException, JMSException { public void testLocalTransactionCommittedEvent() throws ResourceException, JMSException {
final boolean test[] = new boolean[] { final boolean test[] = new boolean[] {
false false
}; };
connectionManager.addConnectionEventListener(new ConnectionEventListenerAdapter() { connectionManager.addConnectionEventListener(new ConnectionEventListenerAdapter() {
@Override
public void localTransactionCommitted(ConnectionEvent arg0) { public void localTransactionCommitted(ConnectionEvent arg0) {
test[0] = true; test[0] = true;
} }
@ -95,12 +100,14 @@ public class ManagedConnectionTest extends TestCase {
} }
@Test(timeout = 60000)
public void testLocalTransactionRollbackEvent() throws ResourceException, JMSException { public void testLocalTransactionRollbackEvent() throws ResourceException, JMSException {
final boolean test[] = new boolean[] { final boolean test[] = new boolean[] {
false false
}; };
connectionManager.addConnectionEventListener(new ConnectionEventListenerAdapter() { connectionManager.addConnectionEventListener(new ConnectionEventListenerAdapter() {
@Override
public void localTransactionRolledback(ConnectionEvent arg0) { public void localTransactionRolledback(ConnectionEvent arg0) {
test[0] = true; test[0] = true;
} }
@ -113,12 +120,14 @@ public class ManagedConnectionTest extends TestCase {
assertTrue(test[0]); assertTrue(test[0]);
} }
@Test(timeout = 60000)
public void testLocalTransactionStartedEvent() throws ResourceException, JMSException { public void testLocalTransactionStartedEvent() throws ResourceException, JMSException {
final boolean test[] = new boolean[] { final boolean test[] = new boolean[] {
false false
}; };
connectionManager.addConnectionEventListener(new ConnectionEventListenerAdapter() { connectionManager.addConnectionEventListener(new ConnectionEventListenerAdapter() {
@Override
public void localTransactionStarted(ConnectionEvent arg0) { public void localTransactionStarted(ConnectionEvent arg0) {
test[0] = true; test[0] = true;
} }
@ -136,6 +145,7 @@ public class ManagedConnectionTest extends TestCase {
* A managed connection that has been clean up should throw exceptions when * A managed connection that has been clean up should throw exceptions when
* it used. * it used.
*/ */
@Test(timeout = 60000)
public void testCleanup() throws ResourceException, JMSException { public void testCleanup() throws ResourceException, JMSException {
// Do some work and close it... // Do some work and close it...
@ -143,13 +153,14 @@ public class ManagedConnectionTest extends TestCase {
doWork(session); doWork(session);
connection.close(); connection.close();
try { try {
// This should throw expection // This should throw exception
doWork(session); doWork(session);
fail("Using a session after the connection is closed should throw exception."); fail("Using a session after the connection is closed should throw exception.");
} catch (JMSException e) { } catch (JMSException e) {
} }
} }
@Test(timeout = 60000)
public void testSessionCloseIndependance() throws ResourceException, JMSException { public void testSessionCloseIndependance() throws ResourceException, JMSException {
Session session1 = connection.createSession(true, 0); Session session1 = connection.createSession(true, 0);
@ -159,7 +170,7 @@ public class ManagedConnectionTest extends TestCase {
doWork(session1); doWork(session1);
session1.close(); session1.close();
try { try {
// This should throw expection // This should throw exception
doWork(session1); doWork(session1);
fail("Using a session after the connection is closed should throw exception."); fail("Using a session after the connection is closed should throw exception.");
} catch (JMSException e) { } catch (JMSException e) {
@ -169,7 +180,7 @@ public class ManagedConnectionTest extends TestCase {
doWork(session2); doWork(session2);
session2.close(); session2.close();
try { try {
// This should throw expection // This should throw exception
doWork(session2); doWork(session2);
fail("Using a session after the connection is closed should throw exception."); fail("Using a session after the connection is closed should throw exception.");
} catch (JMSException e) { } catch (JMSException e) {
@ -187,6 +198,7 @@ public class ManagedConnectionTest extends TestCase {
producer.send(session.createTextMessage("test message.")); producer.send(session.createTextMessage("test message."));
} }
@Test(timeout = 60000)
public void testImplementsQueueAndTopicConnection() throws Exception { public void testImplementsQueueAndTopicConnection() throws Exception {
QueueConnection qc = ((QueueConnectionFactory)connectionFactory).createQueueConnection(); QueueConnection qc = ((QueueConnectionFactory)connectionFactory).createQueueConnection();
assertNotNull(qc); assertNotNull(qc);
@ -194,10 +206,12 @@ public class ManagedConnectionTest extends TestCase {
assertNotNull(tc); assertNotNull(tc);
} }
@Test(timeout = 60000)
public void testSelfEquality() { public void testSelfEquality() {
assertEquality(managedConnection, managedConnection); assertEquality(managedConnection, managedConnection);
} }
@Test(timeout = 60000)
public void testSamePropertiesButNotEqual() throws Exception { public void testSamePropertiesButNotEqual() throws Exception {
ManagedConnectionProxy newConnection = (ManagedConnectionProxy)connectionFactory.createConnection(); ManagedConnectionProxy newConnection = (ManagedConnectionProxy)connectionFactory.createConnection();
assertNonEquality(managedConnection, newConnection.getManagedConnection()); assertNonEquality(managedConnection, newConnection.getManagedConnection());
@ -214,5 +228,4 @@ public class ManagedConnectionTest extends TestCase {
assertFalse("ActiveMQManagedConnection are equal", rightCon.equals(leftCon)); assertFalse("ActiveMQManagedConnection are equal", rightCon.equals(leftCon));
assertFalse("HashCodes are equal", leftCon.hashCode() == rightCon.hashCode()); assertFalse("HashCodes are equal", leftCon.hashCode() == rightCon.hashCode());
} }
} }

View File

@ -16,6 +16,9 @@
*/ */
package org.apache.activemq.ra; package org.apache.activemq.ra;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import javax.jms.Message; import javax.jms.Message;
@ -30,13 +33,8 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import junit.framework.TestCase;
/**
* @author <a href="mailto:michael.gaffney@panacya.com">Michael Gaffney </a>
*/
@RunWith(JMock.class) @RunWith(JMock.class)
public class MessageEndpointProxyTest extends TestCase { public class MessageEndpointProxyTest {
private MessageEndpoint mockEndpoint; private MessageEndpoint mockEndpoint;
private EndpointAndListener mockEndpointAndListener; private EndpointAndListener mockEndpointAndListener;
@ -54,7 +52,7 @@ public class MessageEndpointProxyTest extends TestCase {
endpointProxy = new MessageEndpointProxy(mockEndpointAndListener); endpointProxy = new MessageEndpointProxy(mockEndpointAndListener);
} }
@Test @Test(timeout = 60000)
public void testInvalidConstruction() { public void testInvalidConstruction() {
try { try {
new MessageEndpointProxy(mockEndpoint); new MessageEndpointProxy(mockEndpoint);
@ -64,7 +62,7 @@ public class MessageEndpointProxyTest extends TestCase {
} }
} }
@Test @Test(timeout = 60000)
public void testSuccessfulCallSequence() throws Exception { public void testSuccessfulCallSequence() throws Exception {
setupBeforeDeliverySuccessful(); setupBeforeDeliverySuccessful();
setupOnMessageSuccessful(); setupOnMessageSuccessful();
@ -75,7 +73,7 @@ public class MessageEndpointProxyTest extends TestCase {
doAfterDeliveryExpectSuccess(); doAfterDeliveryExpectSuccess();
} }
@Test @Test(timeout = 60000)
public void testBeforeDeliveryFailure() throws Exception { public void testBeforeDeliveryFailure() throws Exception {
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf (mockEndpointAndListener).beforeDelivery(with(any(Method.class))); oneOf (mockEndpointAndListener).beforeDelivery(with(any(Method.class)));
@ -100,7 +98,7 @@ public class MessageEndpointProxyTest extends TestCase {
doFullyDeadCheck(); doFullyDeadCheck();
} }
@Test @Test(timeout = 60000)
public void testOnMessageFailure() throws Exception { public void testOnMessageFailure() throws Exception {
setupBeforeDeliverySuccessful(); setupBeforeDeliverySuccessful();
@ -122,7 +120,7 @@ public class MessageEndpointProxyTest extends TestCase {
} }
@Test @Test(timeout = 60000)
public void testAfterDeliveryFailure() throws Exception { public void testAfterDeliveryFailure() throws Exception {
setupBeforeDeliverySuccessful(); setupBeforeDeliverySuccessful();
setupOnMessageSuccessful(); setupOnMessageSuccessful();

View File

@ -16,13 +16,6 @@
*/ */
package org.apache.activemq.ra; package org.apache.activemq.ra;
import junit.framework.TestCase;
import org.apache.activemq.broker.SslBrokerService;
import org.apache.activemq.broker.SslContext;
import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.transport.TransportFactory;
import org.apache.activemq.transport.tcp.SslTransportFactory;
import javax.jms.ConnectionFactory; import javax.jms.ConnectionFactory;
import javax.jms.MessageProducer; import javax.jms.MessageProducer;
import javax.jms.Queue; import javax.jms.Queue;
@ -30,41 +23,50 @@ import javax.jms.Session;
import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManager;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
/** import org.apache.activemq.broker.SslBrokerService;
* @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a> import org.apache.activemq.broker.SslContext;
*/ import org.apache.activemq.broker.TransportConnector;
public class SSLMAnagedConnectionFactoryTest extends TestCase { import org.apache.activemq.transport.TransportFactory;
import org.apache.activemq.transport.tcp.SslTransportFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class SSLMAnagedConnectionFactoryTest {
private static final String KAHADB_DIRECTORY = "target/activemq-data/";
private static final String DEFAULT_HOST = "ssl://localhost:0";
private static final String DEFAULT_HOST = "ssl://0.0.0.0:61616";
private ConnectionManagerAdapter connectionManager = new ConnectionManagerAdapter(); private ConnectionManagerAdapter connectionManager = new ConnectionManagerAdapter();
private ActiveMQManagedConnectionFactory managedConnectionFactory; private ActiveMQManagedConnectionFactory managedConnectionFactory;
private ConnectionFactory connectionFactory; private ConnectionFactory connectionFactory;
private ManagedConnectionProxy connection; private ManagedConnectionProxy connection;
private ActiveMQManagedConnection managedConnection; private ActiveMQManagedConnection managedConnection;
private SslBrokerService broker; private SslBrokerService broker;
private TransportConnector connector; private String connectionURI;
@Before
public void setUp() throws Exception {
createAndStartBroker();
/**
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
managedConnectionFactory = new ActiveMQManagedConnectionFactory(); managedConnectionFactory = new ActiveMQManagedConnectionFactory();
managedConnectionFactory.setServerUrl(DEFAULT_HOST); managedConnectionFactory.setServerUrl(connectionURI);
managedConnectionFactory.setTrustStore("server.keystore"); managedConnectionFactory.setTrustStore("server.keystore");
managedConnectionFactory.setTrustStorePassword("password"); managedConnectionFactory.setTrustStorePassword("password");
managedConnectionFactory.setKeyStore("client.keystore"); managedConnectionFactory.setKeyStore("client.keystore");
managedConnectionFactory.setKeyStorePassword("password"); managedConnectionFactory.setKeyStorePassword("password");
connectionFactory = (ConnectionFactory)managedConnectionFactory.createConnectionFactory(connectionManager);createAndStartBroker(); connectionFactory = (ConnectionFactory)managedConnectionFactory.createConnectionFactory(connectionManager);
} }
@Override @After
protected void tearDown() throws Exception { public void tearDown() throws Exception {
if (broker != null) { if (broker != null) {
broker.stop(); broker.stop();
} }
} }
@Test(timeout = 60000)
public void testSSLManagedConnection() throws Exception { public void testSSLManagedConnection() throws Exception {
connection = (ManagedConnectionProxy)connectionFactory.createConnection(); connection = (ManagedConnectionProxy)connectionFactory.createConnection();
managedConnection = connection.getManagedConnection(); managedConnection = connection.getManagedConnection();
@ -82,11 +84,15 @@ public class SSLMAnagedConnectionFactoryTest extends TestCase {
broker.setDeleteAllMessagesOnStartup(true); broker.setDeleteAllMessagesOnStartup(true);
broker.setUseJmx(false); broker.setUseJmx(false);
broker.setBrokerName("BROKER"); broker.setBrokerName("BROKER");
broker.setDataDirectory(KAHADB_DIRECTORY);
KeyManager[] km = SSLTest.getKeyManager(); KeyManager[] km = SSLTest.getKeyManager();
TrustManager[] tm = SSLTest.getTrustManager(); TrustManager[] tm = SSLTest.getTrustManager();
connector = broker.addSslConnector(DEFAULT_HOST, km, tm, null); TransportConnector connector = broker.addSslConnector(DEFAULT_HOST, km, tm, null);
broker.start(); broker.start();
broker.waitUntilStarted(); // for client side broker.waitUntilStarted();
connectionURI = connector.getPublishableConnectString();
SslTransportFactory sslFactory = new SslTransportFactory(); SslTransportFactory sslFactory = new SslTransportFactory();
SslContext ctx = new SslContext(km, tm, null); SslContext ctx = new SslContext(km, tm, null);
SslContext.setCurrentSslContext(ctx); SslContext.setCurrentSslContext(ctx);

View File

@ -16,17 +16,20 @@
*/ */
package org.apache.activemq.ra; package org.apache.activemq.ra;
import junit.framework.TestCase; import static org.junit.Assert.assertEquals;
import org.apache.activemq.ActiveMQSslConnectionFactory; import static org.junit.Assert.assertTrue;
import org.apache.activemq.advisory.AdvisorySupport; import static org.junit.Assert.fail;
import org.apache.activemq.broker.SslBrokerService;
import org.apache.activemq.broker.SslContext; import java.io.ByteArrayInputStream;
import org.apache.activemq.broker.TransportConnector; import java.io.ByteArrayOutputStream;
import org.apache.activemq.command.ActiveMQMessage; import java.io.DataOutputStream;
import org.apache.activemq.command.ActiveMQQueue; import java.io.FileInputStream;
import org.apache.activemq.command.ConsumerInfo; import java.io.IOException;
import org.apache.activemq.transport.TransportFactory; import java.lang.reflect.Method;
import org.apache.activemq.transport.tcp.SslTransportFactory; import java.security.KeyStore;
import java.util.Timer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.jms.Connection; import javax.jms.Connection;
import javax.jms.Message; import javax.jms.Message;
@ -38,7 +41,6 @@ import javax.jms.Session;
import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.TrustManagerFactory;
@ -55,40 +57,43 @@ import javax.resource.spi.work.WorkListener;
import javax.resource.spi.work.WorkManager; import javax.resource.spi.work.WorkManager;
import javax.transaction.xa.XAResource; import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid; import javax.transaction.xa.Xid;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.util.Timer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class SSLTest extends TestCase { import org.apache.activemq.ActiveMQSslConnectionFactory;
public static final String KEYSTORE_TYPE = "jks"; import org.apache.activemq.advisory.AdvisorySupport;
public static final String PASSWORD = "password"; import org.apache.activemq.broker.SslBrokerService;
public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; import org.apache.activemq.broker.SslContext;
public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.transport.TransportFactory;
import org.apache.activemq.transport.tcp.SslTransportFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
long txGenerator = System.currentTimeMillis(); public class SSLTest {
private static final String KEYSTORE_TYPE = "jks";
private static final String PASSWORD = "password";
private static final String SERVER_KEYSTORE = "src/test/resources/server.keystore";
private static final String TRUST_KEYSTORE = "src/test/resources/client.keystore";
private static final String KAHADB_DIRECTORY = "target/activemq-data/";
private static final String BIND_ADDRESS = "ssl://0.0.0.0:61616"; private static final String BIND_ADDRESS = "ssl://0.0.0.0:61616";
private SslBrokerService broker; private long txGenerator = System.currentTimeMillis();
private SslBrokerService broker;
private TransportConnector connector; private TransportConnector connector;
@Override @Before
protected void setUp() throws Exception { public void setUp() throws Exception {
createAndStartBroker(); createAndStartBroker();
} }
@Override @After
protected void tearDown() throws Exception { public void tearDown() throws Exception {
if (broker != null) { if (broker != null) {
broker.stop(); broker.stop();
} }
@ -99,11 +104,13 @@ public class SSLTest extends TestCase {
broker.setDeleteAllMessagesOnStartup(true); broker.setDeleteAllMessagesOnStartup(true);
broker.setUseJmx(false); broker.setUseJmx(false);
broker.setBrokerName("BROKER"); broker.setBrokerName("BROKER");
broker.setDataDirectory(KAHADB_DIRECTORY);
KeyManager[] km = getKeyManager(); KeyManager[] km = getKeyManager();
TrustManager[] tm = getTrustManager(); TrustManager[] tm = getTrustManager();
connector = broker.addSslConnector(BIND_ADDRESS, km, tm, null); connector = broker.addSslConnector(BIND_ADDRESS, km, tm, null);
broker.start(); broker.start();
broker.waitUntilStarted(); // for client side broker.waitUntilStarted(); // for client side
SslTransportFactory sslFactory = new SslTransportFactory(); SslTransportFactory sslFactory = new SslTransportFactory();
SslContext ctx = new SslContext(km, tm, null); SslContext ctx = new SslContext(km, tm, null);
SslContext.setCurrentSslContext(ctx); SslContext.setCurrentSslContext(ctx);
@ -111,40 +118,49 @@ public class SSLTest extends TestCase {
} }
private static final class StubBootstrapContext implements BootstrapContext { private static final class StubBootstrapContext implements BootstrapContext {
@Override
public WorkManager getWorkManager() { public WorkManager getWorkManager() {
return new WorkManager() { return new WorkManager() {
@Override
public void doWork(Work work) throws WorkException { public void doWork(Work work) throws WorkException {
new Thread(work).start(); new Thread(work).start();
} }
@Override
public void doWork(Work work, long arg1, ExecutionContext arg2, WorkListener arg3) throws WorkException { public void doWork(Work work, long arg1, ExecutionContext arg2, WorkListener arg3) throws WorkException {
new Thread(work).start(); new Thread(work).start();
} }
@Override
public long startWork(Work work) throws WorkException { public long startWork(Work work) throws WorkException {
new Thread(work).start(); new Thread(work).start();
return 0; return 0;
} }
@Override
public long startWork(Work work, long arg1, ExecutionContext arg2, WorkListener arg3) throws WorkException { public long startWork(Work work, long arg1, ExecutionContext arg2, WorkListener arg3) throws WorkException {
new Thread(work).start(); new Thread(work).start();
return 0; return 0;
} }
@Override
public void scheduleWork(Work work) throws WorkException { public void scheduleWork(Work work) throws WorkException {
new Thread(work).start(); new Thread(work).start();
} }
@Override
public void scheduleWork(Work work, long arg1, ExecutionContext arg2, WorkListener arg3) throws WorkException { public void scheduleWork(Work work, long arg1, ExecutionContext arg2, WorkListener arg3) throws WorkException {
new Thread(work).start(); new Thread(work).start();
} }
}; };
} }
@Override
public XATerminator getXATerminator() { public XATerminator getXATerminator() {
return null; return null;
} }
@Override
public Timer createTimer() throws UnavailableException { public Timer createTimer() throws UnavailableException {
return null; return null;
} }
@ -155,6 +171,7 @@ public class SSLTest extends TestCase {
public XAResource xaresource; public XAResource xaresource;
public Xid xid; public Xid xid;
@Override
public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException { public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException {
try { try {
if (xid == null) { if (xid == null) {
@ -166,6 +183,7 @@ public class SSLTest extends TestCase {
} }
} }
@Override
public void afterDelivery() throws ResourceException { public void afterDelivery() throws ResourceException {
try { try {
xaresource.end(xid, 0); xaresource.end(xid, 0);
@ -176,15 +194,17 @@ public class SSLTest extends TestCase {
} }
} }
@Override
public void release() { public void release() {
} }
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
messageCount++; messageCount++;
} }
} }
@Test(timeout = 60000)
public void testMessageDeliveryUsingSSLTruststoreOnly() throws Exception { public void testMessageDeliveryUsingSSLTruststoreOnly() throws Exception {
SSLContext context = SSLContext.getInstance("TLS"); SSLContext context = SSLContext.getInstance("TLS");
context.init(getKeyManager(), getTrustManager(), null); context.init(getKeyManager(), getTrustManager(), null);
@ -208,12 +228,11 @@ public class SSLTest extends TestCase {
final CountDownLatch messageDelivered = new CountDownLatch(1); final CountDownLatch messageDelivered = new CountDownLatch(1);
final StubMessageEndpoint endpoint = new StubMessageEndpoint() { final StubMessageEndpoint endpoint = new StubMessageEndpoint() {
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
super.onMessage(message); super.onMessage(message);
messageDelivered.countDown(); messageDelivered.countDown();
} }
;
}; };
ActiveMQActivationSpec activationSpec = new ActiveMQActivationSpec(); ActiveMQActivationSpec activationSpec = new ActiveMQActivationSpec();
@ -223,11 +242,13 @@ public class SSLTest extends TestCase {
activationSpec.validate(); activationSpec.validate();
MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() { MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() {
@Override
public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException { public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException {
endpoint.xaresource = resource; endpoint.xaresource = resource;
return endpoint; return endpoint;
} }
@Override
public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException { public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException {
return true; return true;
} }
@ -255,9 +276,9 @@ public class SSLTest extends TestCase {
// Shut the Endpoint down. // Shut the Endpoint down.
adapter.endpointDeactivation(messageEndpointFactory, activationSpec); adapter.endpointDeactivation(messageEndpointFactory, activationSpec);
adapter.stop(); adapter.stop();
} }
@Test(timeout = 60000)
public void testMessageDeliveryUsingSSLTruststoreAndKeystore() throws Exception { public void testMessageDeliveryUsingSSLTruststoreAndKeystore() throws Exception {
SSLContext context = SSLContext.getInstance("TLS"); SSLContext context = SSLContext.getInstance("TLS");
context.init(getKeyManager(), getTrustManager(), null); context.init(getKeyManager(), getTrustManager(), null);
@ -285,12 +306,11 @@ public class SSLTest extends TestCase {
final CountDownLatch messageDelivered = new CountDownLatch(1); final CountDownLatch messageDelivered = new CountDownLatch(1);
final StubMessageEndpoint endpoint = new StubMessageEndpoint() { final StubMessageEndpoint endpoint = new StubMessageEndpoint() {
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
super.onMessage(message); super.onMessage(message);
messageDelivered.countDown(); messageDelivered.countDown();
} }
;
}; };
ActiveMQActivationSpec activationSpec = new ActiveMQActivationSpec(); ActiveMQActivationSpec activationSpec = new ActiveMQActivationSpec();
@ -300,11 +320,13 @@ public class SSLTest extends TestCase {
activationSpec.validate(); activationSpec.validate();
MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() { MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() {
@Override
public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException { public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException {
endpoint.xaresource = resource; endpoint.xaresource = resource;
return endpoint; return endpoint;
} }
@Override
public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException { public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException {
return true; return true;
} }
@ -332,9 +354,9 @@ public class SSLTest extends TestCase {
// Shut the Endpoint down. // Shut the Endpoint down.
adapter.endpointDeactivation(messageEndpointFactory, activationSpec); adapter.endpointDeactivation(messageEndpointFactory, activationSpec);
adapter.stop(); adapter.stop();
}
} @Test(timeout = 60000)
public void testMessageDeliveryUsingSSLTruststoreAndKeystoreOverrides() throws Exception { public void testMessageDeliveryUsingSSLTruststoreAndKeystoreOverrides() throws Exception {
SSLContext context = SSLContext.getInstance("TLS"); SSLContext context = SSLContext.getInstance("TLS");
context.init(getKeyManager(), getTrustManager(), null); context.init(getKeyManager(), getTrustManager(), null);
@ -358,12 +380,11 @@ public class SSLTest extends TestCase {
final CountDownLatch messageDelivered = new CountDownLatch(1); final CountDownLatch messageDelivered = new CountDownLatch(1);
final StubMessageEndpoint endpoint = new StubMessageEndpoint() { final StubMessageEndpoint endpoint = new StubMessageEndpoint() {
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
super.onMessage(message); super.onMessage(message);
messageDelivered.countDown(); messageDelivered.countDown();
} }
;
}; };
ActiveMQActivationSpec activationSpec = new ActiveMQActivationSpec(); ActiveMQActivationSpec activationSpec = new ActiveMQActivationSpec();
@ -377,11 +398,13 @@ public class SSLTest extends TestCase {
activationSpec.validate(); activationSpec.validate();
MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() { MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() {
@Override
public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException { public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException {
endpoint.xaresource = resource; endpoint.xaresource = resource;
return endpoint; return endpoint;
} }
@Override
public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException { public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException {
return true; return true;
} }
@ -409,10 +432,8 @@ public class SSLTest extends TestCase {
// Shut the Endpoint down. // Shut the Endpoint down.
adapter.endpointDeactivation(messageEndpointFactory, activationSpec); adapter.endpointDeactivation(messageEndpointFactory, activationSpec);
adapter.stop(); adapter.stop();
} }
public Xid createXid() throws IOException { public Xid createXid() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream os = new DataOutputStream(baos); DataOutputStream os = new DataOutputStream(baos);
@ -421,19 +442,21 @@ public class SSLTest extends TestCase {
final byte[] bs = baos.toByteArray(); final byte[] bs = baos.toByteArray();
return new Xid() { return new Xid() {
@Override
public int getFormatId() { public int getFormatId() {
return 86; return 86;
} }
@Override
public byte[] getGlobalTransactionId() { public byte[] getGlobalTransactionId() {
return bs; return bs;
} }
@Override
public byte[] getBranchQualifier() { public byte[] getBranchQualifier() {
return bs; return bs;
} }
}; };
} }
public static TrustManager[] getTrustManager() throws Exception { public static TrustManager[] getTrustManager() throws Exception {
@ -457,7 +480,6 @@ public class SSLTest extends TestCase {
byte[] sslCert = loadClientCredential(SERVER_KEYSTORE); byte[] sslCert = loadClientCredential(SERVER_KEYSTORE);
if (sslCert != null && sslCert.length > 0) { if (sslCert != null && sslCert.length > 0) {
ByteArrayInputStream bin = new ByteArrayInputStream(sslCert); ByteArrayInputStream bin = new ByteArrayInputStream(sslCert);
ks.load(bin, PASSWORD.toCharArray()); ks.load(bin, PASSWORD.toCharArray());
@ -471,28 +493,30 @@ public class SSLTest extends TestCase {
if (fileName == null) { if (fileName == null) {
return null; return null;
} }
FileInputStream in = new FileInputStream(fileName); FileInputStream in = new FileInputStream(fileName);
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[512]; byte[] buf = new byte[512];
int i = in.read(buf); int i = in.read(buf);
while (i > 0) { while (i > 0) {
out.write(buf, 0, i); out.write(buf, 0, i);
i = in.read(buf); i = in.read(buf);
} }
in.close(); in.close();
return out.toByteArray(); return out.toByteArray();
} }
private void makeSSLConnection(SSLContext context, String enabledSuites[], TransportConnector connector) throws Exception, private void makeSSLConnection(SSLContext context, String enabledSuites[], TransportConnector connector) throws Exception {
UnknownHostException, SocketException {
SSLSocket sslSocket = (SSLSocket) context.getSocketFactory().createSocket("localhost", connector.getUri().getPort()); SSLSocket sslSocket = (SSLSocket) context.getSocketFactory().createSocket("localhost", connector.getUri().getPort());
if (enabledSuites != null) { if (enabledSuites != null) {
sslSocket.setEnabledCipherSuites(enabledSuites); sslSocket.setEnabledCipherSuites(enabledSuites);
} }
sslSocket.setSoTimeout(5000);
SSLSession session = sslSocket.getSession(); sslSocket.setSoTimeout(5000);
sslSocket.getSession();
sslSocket.startHandshake(); sslSocket.startHandshake();
} }
} }

View File

@ -16,11 +16,14 @@
*/ */
package org.apache.activemq.ra; package org.apache.activemq.ra;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.jms.Session; import javax.jms.Session;
import javax.resource.spi.BootstrapContext; import javax.resource.spi.BootstrapContext;
import javax.resource.spi.endpoint.MessageEndpointFactory; import javax.resource.spi.endpoint.MessageEndpointFactory;
@ -28,9 +31,7 @@ import javax.resource.spi.work.ExecutionContext;
import javax.resource.spi.work.Work; import javax.resource.spi.work.Work;
import javax.resource.spi.work.WorkListener; import javax.resource.spi.work.WorkListener;
import javax.resource.spi.work.WorkManager; import javax.resource.spi.work.WorkManager;
import javax.transaction.xa.XAResource; import javax.transaction.xa.XAResource;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQSession; import org.apache.activemq.ActiveMQSession;
@ -54,31 +55,30 @@ import org.junit.runner.RunWith;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/**
*
*/
@RunWith(JMock.class) @RunWith(JMock.class)
public class ServerSessionImplTest extends TestCase { public class ServerSessionImplTest {
private static final Logger LOG = LoggerFactory.getLogger(ServerSessionImplTest.class); private static final Logger LOG = LoggerFactory.getLogger(ServerSessionImplTest.class);
private static final String BROKER_URL = "vm://localhost?broker.persistent=false"; private static final String BROKER_URL = "vm://localhost?broker.persistent=false";
private ServerSessionImpl serverSession; private ServerSessionImpl serverSession;
private ServerSessionPoolImpl pool; private ServerSessionPoolImpl pool;
private WorkManager workManager; private WorkManager workManager;
private MessageEndpointProxy messageEndpoint; private MessageEndpointProxy messageEndpoint;
private ActiveMQConnection con; private ActiveMQConnection con;
private ActiveMQSession session; private ActiveMQSession session;
ActiveMQEndpointWorker endpointWorker; private ActiveMQEndpointWorker endpointWorker;
private Mockery context; private Mockery context;
@Before
public void setUp() throws Exception
{
super.setUp();
context = new Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
org.apache.activemq.ActiveMQConnectionFactory factory = @Before
new org.apache.activemq.ActiveMQConnectionFactory(BROKER_URL); public void setUp() throws Exception {
context = new Mockery() {
{
setImposteriser(ClassImposteriser.INSTANCE);
}
};
org.apache.activemq.ActiveMQConnectionFactory factory = new org.apache.activemq.ActiveMQConnectionFactory(BROKER_URL);
con = (ActiveMQConnection) factory.createConnection(); con = (ActiveMQConnection) factory.createConnection();
con.start(); con.start();
session = (ActiveMQSession) con.createSession(false, Session.AUTO_ACKNOWLEDGE); session = (ActiveMQSession) con.createSession(false, Session.AUTO_ACKNOWLEDGE);
@ -98,18 +98,14 @@ public class ServerSessionImplTest extends TestCase {
workManager = context.mock(WorkManager.class); workManager = context.mock(WorkManager.class);
messageEndpoint = context.mock(MessageEndpointProxy.class); messageEndpoint = context.mock(MessageEndpointProxy.class);
serverSession = new ServerSessionImpl( serverSession = new ServerSessionImpl(pool, session, workManager, messageEndpoint, false, 10);
(ServerSessionPoolImpl) pool,
session,
(WorkManager) workManager,
messageEndpoint,
false,
10);
con.close(); con.close();
context.checking(new Expectations() {{ context.checking(new Expectations() {
oneOf (pool).removeFromPool(with(same(serverSession))); {
}}); oneOf(pool).removeFromPool(with(same(serverSession)));
}
});
serverSession.run(); serverSession.run();
} }
@ -126,53 +122,70 @@ public class ServerSessionImplTest extends TestCase {
workManager = context.mock(WorkManager.class); workManager = context.mock(WorkManager.class);
final MessageActivationSpec messageActivationSpec = context.mock(MessageActivationSpec.class); final MessageActivationSpec messageActivationSpec = context.mock(MessageActivationSpec.class);
final BootstrapContext boostrapContext = context.mock(BootstrapContext.class); final BootstrapContext boostrapContext = context.mock(BootstrapContext.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {
allowing(boostrapContext).getWorkManager(); will (returnValue(workManager)); {
allowing(resourceAdapter).getBootstrapContext(); will (returnValue(boostrapContext)); allowing(boostrapContext).getWorkManager();
allowing(messageEndpointFactory).isDeliveryTransacted(with (any(Method.class))); will(returnValue(Boolean.FALSE)); will(returnValue(workManager));
allowing(key).getMessageEndpointFactory(); will(returnValue(messageEndpointFactory)); allowing(resourceAdapter).getBootstrapContext();
allowing(key).getActivationSpec(); will (returnValue(messageActivationSpec)); will(returnValue(boostrapContext));
allowing(messageActivationSpec).isUseJndi(); will (returnValue(Boolean.FALSE)); allowing(messageEndpointFactory).isDeliveryTransacted(with(any(Method.class)));
allowing(messageActivationSpec).getDestinationType(); will (returnValue("javax.jms.Queue")); will(returnValue(Boolean.FALSE));
allowing(messageActivationSpec).getDestination(); will (returnValue("Queue")); allowing(key).getMessageEndpointFactory();
allowing(messageActivationSpec).getAcknowledgeModeForSession(); will (returnValue(1)); will(returnValue(messageEndpointFactory));
allowing(messageActivationSpec).getMaxSessionsIntValue(); will (returnValue(1)); allowing(key).getActivationSpec();
allowing(messageActivationSpec).getEnableBatchBooleanValue(); will (returnValue(Boolean.FALSE)); will(returnValue(messageActivationSpec));
allowing(messageActivationSpec).isUseRAManagedTransactionEnabled(); will (returnValue(Boolean.TRUE)); allowing(messageActivationSpec).isUseJndi();
allowing(messageEndpointFactory).createEndpoint(with (any(XAResource.class))); will (returnValue(messageEndpoint)); will(returnValue(Boolean.FALSE));
allowing(messageActivationSpec).getDestinationType();
will(returnValue("javax.jms.Queue"));
allowing(messageActivationSpec).getDestination();
will(returnValue("Queue"));
allowing(messageActivationSpec).getAcknowledgeModeForSession();
will(returnValue(1));
allowing(messageActivationSpec).getMaxSessionsIntValue();
will(returnValue(1));
allowing(messageActivationSpec).getEnableBatchBooleanValue();
will(returnValue(Boolean.FALSE));
allowing(messageActivationSpec).isUseRAManagedTransactionEnabled();
will(returnValue(Boolean.TRUE));
allowing(messageEndpointFactory).createEndpoint(with(any(XAResource.class)));
will(returnValue(messageEndpoint));
allowing(workManager).scheduleWork((Work) with(anything()), (long) with(any(long.class)), with(any(ExecutionContext.class)), with(any(WorkListener.class))); allowing(workManager).scheduleWork((Work) with(anything()), with(any(long.class)), with(any(ExecutionContext.class)),
will (new Action() { with(any(WorkListener.class)));
@Override will(new Action() {
public Object invoke(Invocation invocation) throws Throwable { @Override
return null; public Object invoke(Invocation invocation) throws Throwable {
} return null;
@Override
public void describeTo(Description description) {
}
});
allowing(messageEndpoint).beforeDelivery((Method) with(anything()));
allowing (messageEndpoint).onMessage(with (any(javax.jms.Message.class))); will(new Action(){
@Override
public Object invoke(Invocation invocation) throws Throwable {
messageCount.countDown();
if (messageCount.getCount() < maxMessages - 11) {
TimeUnit.MILLISECONDS.sleep(200);
} }
return null;
}
@Override @Override
public void describeTo(Description description) { public void describeTo(Description description) {
description.appendText("Keep message count"); }
} });
});
allowing(messageEndpoint).afterDelivery();
allowing(messageEndpoint).release();
}}); allowing(messageEndpoint).beforeDelivery((Method) with(anything()));
allowing(messageEndpoint).onMessage(with(any(javax.jms.Message.class)));
will(new Action() {
@Override
public Object invoke(Invocation invocation) throws Throwable {
messageCount.countDown();
if (messageCount.getCount() < maxMessages - 11) {
TimeUnit.MILLISECONDS.sleep(200);
}
return null;
}
@Override
public void describeTo(Description description) {
description.appendText("Keep message count");
}
});
allowing(messageEndpoint).afterDelivery();
allowing(messageEndpoint).release();
}
});
endpointWorker = new ActiveMQEndpointWorker(resourceAdapter, key); endpointWorker = new ActiveMQEndpointWorker(resourceAdapter, key);
endpointWorker.setConnection(con); endpointWorker.setConnection(con);
@ -183,8 +196,8 @@ public class ServerSessionImplTest extends TestCase {
// preload the session dispatch queue to keep the session active // preload the session dispatch queue to keep the session active
ActiveMQSession session1 = (ActiveMQSession) serverSession1.getSession(); ActiveMQSession session1 = (ActiveMQSession) serverSession1.getSession();
for (int i=0; i<maxMessages; i++) { for (int i = 0; i < maxMessages; i++) {
MessageDispatch messageDispatch = new MessageDispatch(); MessageDispatch messageDispatch = new MessageDispatch();
ActiveMQMessage message = new ActiveMQTextMessage(); ActiveMQMessage message = new ActiveMQTextMessage();
message.setMessageId(new MessageId("0:0:0:" + i)); message.setMessageId(new MessageId("0:0:0:" + i));
message.getMessageId().setBrokerSequenceId(i); message.getMessageId().setBrokerSequenceId(i);
@ -195,7 +208,7 @@ public class ServerSessionImplTest extends TestCase {
ExecutorService executorService = Executors.newCachedThreadPool(); ExecutorService executorService = Executors.newCachedThreadPool();
final CountDownLatch runState = new CountDownLatch(1); final CountDownLatch runState = new CountDownLatch(1);
executorService.execute(new Runnable(){ executorService.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {

View File

@ -16,6 +16,8 @@
*/ */
package org.apache.activemq.ra; package org.apache.activemq.ra;
import static org.junit.Assert.assertNotNull;
import javax.jms.ConnectionFactory; import javax.jms.ConnectionFactory;
import javax.jms.JMSException; import javax.jms.JMSException;
import javax.jms.Message; import javax.jms.Message;
@ -26,13 +28,11 @@ import javax.jms.TopicSubscriber;
import javax.resource.ResourceException; import javax.resource.ResourceException;
import javax.transaction.xa.XAException; import javax.transaction.xa.XAException;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Before;
import org.junit.Test;
/** public class UnsubscribeResubscribeTest {
*
*/
public class UnsubscribeResubscribeTest extends TestCase {
private static final String DEFAULT_HOST = "vm://localhost?broker.persistent=false"; private static final String DEFAULT_HOST = "vm://localhost?broker.persistent=false";
@ -42,17 +42,13 @@ public class UnsubscribeResubscribeTest extends TestCase {
private ManagedConnectionProxy connection; private ManagedConnectionProxy connection;
private ActiveMQManagedConnection managedConnection; private ActiveMQManagedConnection managedConnection;
/** @Before
* @see junit.framework.TestCase#setUp() public void setUp() throws Exception {
*/
protected void setUp() throws Exception {
managedConnectionFactory = new ActiveMQManagedConnectionFactory(); managedConnectionFactory = new ActiveMQManagedConnectionFactory();
managedConnectionFactory.setServerUrl(DEFAULT_HOST); managedConnectionFactory.setServerUrl(DEFAULT_HOST);
managedConnectionFactory.setUserName(ActiveMQConnectionFactory.DEFAULT_USER); managedConnectionFactory.setUserName(ActiveMQConnectionFactory.DEFAULT_USER);
managedConnectionFactory.setPassword(ActiveMQConnectionFactory.DEFAULT_PASSWORD); managedConnectionFactory.setPassword(ActiveMQConnectionFactory.DEFAULT_PASSWORD);
managedConnectionFactory.setClientid("clientId"); managedConnectionFactory.setClientid("clientId");
} }
private void getConnection() throws ResourceException, JMSException { private void getConnection() throws ResourceException, JMSException {
@ -61,8 +57,10 @@ public class UnsubscribeResubscribeTest extends TestCase {
managedConnection = connection.getManagedConnection(); managedConnection = connection.getManagedConnection();
} }
@Test(timeout = 60000)
public void testUnsubscribeResubscribe() throws ResourceException, JMSException, XAException { public void testUnsubscribeResubscribe() throws ResourceException, JMSException, XAException {
getConnection(); getConnection();
assertNotNull(managedConnection);
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("topic"); Topic topic = session.createTopic("topic");
TopicSubscriber sub = session.createDurableSubscriber(topic, "sub"); TopicSubscriber sub = session.createDurableSubscriber(topic, "sub");
@ -73,5 +71,4 @@ public class UnsubscribeResubscribeTest extends TestCase {
session.unsubscribe("sub"); session.unsubscribe("sub");
sub = session.createDurableSubscriber(topic, "sub"); sub = session.createDurableSubscriber(topic, "sub");
} }
} }