moved the tests across from the assembly module that can be run inside the activemq-core module

git-svn-id: https://svn.apache.org/repos/asf/incubator/activemq/trunk@419843 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
James Strachan 2006-07-07 08:57:09 +00:00
parent c06ad31692
commit a677c21240
54 changed files with 6012 additions and 0 deletions

View File

@ -0,0 +1,59 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.config;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest;
import javax.naming.InitialContext;
import javax.naming.Context;
import java.io.File;
import java.util.Hashtable;
/**
* @version $Revision$
*/
public class BrokerXmlConfigFromJNDITest extends JmsTopicSendReceiveWithTwoConnectionsTest {
protected ActiveMQConnectionFactory createConnectionFactory() throws Exception {
// START SNIPPET: example
System.err.print(System.getProperties());
// we could put these properties into a jndi.properties
// on the classpath instead
Hashtable properties = new Hashtable();
properties.put("java.naming.factory.initial", "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
// configure the embedded broker using an XML config file
// which is either a URL or a resource on the classpath
File f = new File(System.getProperty("basedir", "."));
f = new File(f, "src/sample-conf/default.xml");
properties.put("brokerXmlConfig", "file:"+f.getPath());
properties.put(Context.PROVIDER_URL, "vm://localhost");
InitialContext context = new InitialContext(properties);
ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) context.lookup("ConnectionFactory");
// END SNIPPET: example
return connectionFactory;
}
}

View File

@ -0,0 +1,50 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.config;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest;
import java.net.URI;
/**
* @version $Revision$
*/
public class BrokerXmlConfigTest extends JmsTopicSendReceiveWithTwoConnectionsTest {
protected ActiveMQConnectionFactory createConnectionFactory() throws Exception {
// START SNIPPET: bean
// configure the connection factory using
// normal Java Bean property methods
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
// configure the embedded broker using an XML config file
// which is either a URL or a resource on the classpath
// TODO ...
//connectionFactory.setBrokerXmlConfig("file:src/sample-conf/default.xml");
// you only need to configure the broker URL if you wish to change the
// default connection mechanism, which in this test case we do
connectionFactory.setBrokerURL("vm://localhost");
// END SNIPPET: bean
return connectionFactory;
}
}

View File

@ -0,0 +1,380 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.config;
import java.io.File;
import java.util.List;
import junit.framework.TestCase;
import org.apache.activeio.command.DefaultWireFormat;
import org.apache.activeio.command.WireFormat;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.broker.region.policy.FixedSizedSubscriptionRecoveryPolicy;
import org.apache.activemq.broker.region.policy.LastImageSubscriptionRecoveryPolicy;
import org.apache.activemq.broker.region.policy.NoSubscriptionRecoveryPolicy;
import org.apache.activemq.broker.region.policy.RoundRobinDispatchPolicy;
import org.apache.activemq.broker.region.policy.SimpleDispatchPolicy;
import org.apache.activemq.broker.region.policy.StrictOrderDispatchPolicy;
import org.apache.activemq.broker.region.policy.SubscriptionRecoveryPolicy;
import org.apache.activemq.broker.region.policy.TimedSubscriptionRecoveryPolicy;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.memory.UsageManager;
import org.apache.activemq.openwire.OpenWireFormat;
import org.apache.activemq.store.PersistenceAdapter;
import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter;
import org.apache.activemq.store.journal.JournalPersistenceAdapter;
import org.apache.activemq.store.memory.MemoryPersistenceAdapter;
import org.apache.activemq.transport.activeio.ActiveIOTransportServer;
import org.apache.activemq.transport.tcp.TcpTransportServer;
import org.apache.activemq.xbean.BrokerFactoryBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.derby.jdbc.EmbeddedDataSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
/**
* @version $Revision$
*/
public class ConfigTest extends TestCase {
private static final Log log = LogFactory.getLog(ConfigTest.class);
protected static final String JOURNAL_ROOT = "target/test-data/";
protected static final String DERBY_ROOT = "target/test-data/";
protected static final String CONF_ROOT = "src/test/resources/org/apache/activemq/config/sample-conf/";
static {
System.setProperty("javax.net.ssl.trustStore", "src/test/resources/client.keystore");
System.setProperty("javax.net.ssl.trustStorePassword", "password");
System.setProperty("javax.net.ssl.trustStoreType", "jks");
System.setProperty("javax.net.ssl.keyStore", "src/test/resources/server.keystore");
System.setProperty("javax.net.ssl.keyStorePassword", "password");
System.setProperty("javax.net.ssl.keyStoreType", "jks");
}
/*
* IMPORTANT NOTE: Assertions checking for the existence of the derby directory will fail if the first derby
* directory is not created under target/test-data/. The test in unable to change the derby
* root directory for succeeding creation. It uses the first created directory as the root.
*/
/*
* This tests creating a journal persistence adapter using the persistence adapter factory bean
*/
public void testJournaledJDBCConfig() throws Exception {
System.out.print("Checking journaled JDBC persistence adapter configuration... ");
File journalFile = new File(JOURNAL_ROOT + "testJournaledJDBCConfig/journal");
recursiveDelete(journalFile);
File derbyFile = new File(DERBY_ROOT + "testJournaledJDBCConfig/derbydb"); // Default derby name
recursiveDelete(derbyFile);
BrokerService broker;
broker = createBroker(new FileSystemResource(CONF_ROOT + "journaledjdbc-example.xml"));
try {
assertEquals("Broker Config Error (brokerName)", "brokerJournaledJDBCConfigTest", broker.getBrokerName());
PersistenceAdapter adapter = broker.getPersistenceAdapter();
assertTrue("Should have created a journal persistence adapter", adapter instanceof JournalPersistenceAdapter);
assertTrue("Should have created a derby directory at " + derbyFile.getAbsolutePath(), derbyFile.exists());
assertTrue("Should have created a journal directory at " + journalFile.getAbsolutePath(), journalFile.exists());
// Check persistence factory configurations
System.out.print("Checking persistence adapter factory settings... ");
JournalPersistenceAdapter pa = (JournalPersistenceAdapter) broker.getPersistenceAdapter();
log.info("Success");
} finally {
if (broker != null) {
broker.stop();
}
}
}
/*
* This tests creating a jdbc persistence adapter using xbeans-spring
*/
public void testJdbcConfig() throws Exception {
System.out.print("Checking jdbc persistence adapter configuration... ");
BrokerService broker;
broker = createBroker(new FileSystemResource(CONF_ROOT + "jdbc-example.xml"));
try {
assertEquals("Broker Config Error (brokerName)", "brokerJdbcConfigTest", broker.getBrokerName());
PersistenceAdapter adapter = broker.getPersistenceAdapter();
assertTrue("Should have created a jdbc persistence adapter", adapter instanceof JDBCPersistenceAdapter);
assertEquals("JDBC Adapter Config Error (cleanupPeriod)", 60000,
((JDBCPersistenceAdapter)adapter).getCleanupPeriod());
assertTrue("Should have created an EmbeddedDataSource",
((JDBCPersistenceAdapter)adapter).getDataSource() instanceof EmbeddedDataSource);
assertTrue("Should have created a DefaultWireFormat",
((JDBCPersistenceAdapter)adapter).getWireFormat() instanceof DefaultWireFormat);
log.info("Success");
} finally {
if (broker != null) {
broker.stop();
}
}
}
/*
* This tests configuring the different broker properties using xbeans-spring
*/
public void testBrokerConfig() throws Exception {
ActiveMQTopic dest;
BrokerService broker;
File journalFile = new File(JOURNAL_ROOT);
recursiveDelete(journalFile);
// Create broker from resource
System.out.print("Creating broker... ");
broker = createBroker("org/apache/activemq/config/example.xml");
log.info("Success");
try {
// Check broker configuration
System.out.print("Checking broker configurations... ");
assertEquals("Broker Config Error (brokerName)", "brokerConfigTest", broker.getBrokerName());
assertEquals("Broker Config Error (populateJMSXUserID)", false, broker.isPopulateJMSXUserID());
assertEquals("Broker Config Error (useLoggingForShutdownErrors)", true, broker.isUseLoggingForShutdownErrors());
assertEquals("Broker Config Error (useJmx)", true, broker.isUseJmx());
assertEquals("Broker Config Error (persistent)", false, broker.isPersistent());
assertEquals("Broker Config Error (useShutdownHook)", false, broker.isUseShutdownHook());
assertEquals("Broker Config Error (deleteAllMessagesOnStartup)", true, broker.isDeleteAllMessagesOnStartup());
log.info("Success");
// Check specific vm transport
System.out.print("Checking vm connector... ");
assertEquals("Should have a specific VM Connector", "vm://javacoola", broker.getVmConnectorURI().toString());
log.info("Success");
// Check transport connectors list
System.out.print("Checking transport connectors... ");
List connectors = broker.getTransportConnectors();
assertTrue("Should have created at least 4 connectors", (connectors.size() >= 4));
assertTrue ("1st connector should be TcpTransportServer", ((TransportConnector)connectors.get(0)).getServer() instanceof TcpTransportServer);
assertTrue ("2nd connector should be TcpTransportServer", ((TransportConnector)connectors.get(1)).getServer() instanceof TcpTransportServer);
assertTrue ("3rd connector should be TcpTransportServer", ((TransportConnector)connectors.get(2)).getServer() instanceof TcpTransportServer);
assertTrue ("4th connector should be ActiveIOTransportServer", ((TransportConnector)connectors.get(3)).getServer() instanceof ActiveIOTransportServer);
// Check spring configured transport server (last transport connector only)
ActiveIOTransportServer myTransportServer = (ActiveIOTransportServer)((TransportConnector)connectors.get(3)).getServer();
assertEquals("URI should be ssl", "ssl://localhost:61634", myTransportServer.getConnectURI().toString());
assertEquals("Error transport server config (stopTimeout)", 5000, myTransportServer.getStopTimeout());
// Check spring configured wire format factory
WireFormat myWireFormat = myTransportServer.getWireFormatFactory().createWireFormat();
assertTrue("WireFormat should be OpenWireFormat", myWireFormat instanceof OpenWireFormat);
assertEquals("WireFormat Config Error (stackTraceEnabled)", false, ((OpenWireFormat)myWireFormat).getPreferedWireFormatInfo().isStackTraceEnabled());
assertEquals("WireFormat Config Error (tcpNoDelayEnabled)", true, ((OpenWireFormat)myWireFormat).getPreferedWireFormatInfo().isTcpNoDelayEnabled());
assertEquals("WireFormat Config Error (cacheEnabled)", false, ((OpenWireFormat)myWireFormat).getPreferedWireFormatInfo().isCacheEnabled());
log.info("Success");
// Check network connectors
System.out.print("Checking network connectors... ");
List networkConnectors = broker.getNetworkConnectors();
assertEquals("Should have a single network connector", 1, networkConnectors.size());
log.info("Success");
// Check dispatch policy configuration
System.out.print("Checking dispatch policies... ");
dest = new ActiveMQTopic("Topic.SimpleDispatch");
assertTrue("Should have a simple dispatch policy for " + dest.getTopicName(),
broker.getDestinationPolicy().getEntryFor(dest).getDispatchPolicy() instanceof SimpleDispatchPolicy);
dest = new ActiveMQTopic("Topic.RoundRobinDispatch");
assertTrue("Should have a round robin dispatch policy for " + dest.getTopicName(),
broker.getDestinationPolicy().getEntryFor(dest).getDispatchPolicy() instanceof RoundRobinDispatchPolicy);
dest = new ActiveMQTopic("Topic.StrictOrderDispatch");
assertTrue("Should have a strict order dispatch policy for " + dest.getTopicName(),
broker.getDestinationPolicy().getEntryFor(dest).getDispatchPolicy() instanceof StrictOrderDispatchPolicy);
log.info("Success");
// Check subscription policy configuration
System.out.print("Checking subscription recovery policies... ");
SubscriptionRecoveryPolicy subsPolicy;
dest = new ActiveMQTopic("Topic.FixedSizedSubs");
subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy();
assertTrue("Should have a fixed sized subscription recovery policy for " + dest.getTopicName(),
subsPolicy instanceof FixedSizedSubscriptionRecoveryPolicy);
assertEquals("FixedSizedSubsPolicy Config Error (maximumSize)", 2000000,
((FixedSizedSubscriptionRecoveryPolicy)subsPolicy).getMaximumSize());
assertEquals("FixedSizedSubsPolicy Config Error (useSharedBuffer)", false,
((FixedSizedSubscriptionRecoveryPolicy)subsPolicy).isUseSharedBuffer());
dest = new ActiveMQTopic("Topic.LastImageSubs");
subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy();
assertTrue("Should have a last image subscription recovery policy for " + dest.getTopicName(),
subsPolicy instanceof LastImageSubscriptionRecoveryPolicy);
dest = new ActiveMQTopic("Topic.NoSubs");
subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy();
assertTrue("Should have no subscription recovery policy for " + dest.getTopicName(),
subsPolicy instanceof NoSubscriptionRecoveryPolicy);
dest = new ActiveMQTopic("Topic.TimedSubs");
subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy();
assertTrue("Should have a timed subscription recovery policy for " + dest.getTopicName(),
subsPolicy instanceof TimedSubscriptionRecoveryPolicy);
assertEquals("TimedSubsPolicy Config Error (recoverDuration)", 25000,
((TimedSubscriptionRecoveryPolicy)subsPolicy).getRecoverDuration());
log.info("Success");
// Check usage manager
System.out.print("Checking memory manager configurations... ");
UsageManager memMgr = broker.getMemoryManager();
assertTrue("Should have a memory manager", memMgr != null);
assertEquals("UsageManager Config Error (limit)", 200000, memMgr.getLimit());
assertEquals("UsageManager Config Error (percentUsageMinDelta)", 20, memMgr.getPercentUsageMinDelta());
log.info("Success");
log.info("Success");
} finally {
if (broker != null) {
broker.stop();
}
}
}
/*
* This tests creating a journal persistence adapter using xbeans-spring
*/
public void testJournalConfig() throws Exception {
System.out.print("Checking journal persistence adapter configuration... ");
File journalFile = new File(JOURNAL_ROOT + "testJournalConfig/journal");
recursiveDelete(journalFile);
BrokerService broker;
broker = createBroker(new FileSystemResource(CONF_ROOT + "journal-example.xml"));
try {
assertEquals("Broker Config Error (brokerName)", "brokerJournalConfigTest", broker.getBrokerName());
PersistenceAdapter adapter = broker.getPersistenceAdapter();
assertTrue("Should have created a journal persistence adapter", adapter instanceof JournalPersistenceAdapter);
assertTrue("Should have created a journal directory at " + journalFile.getAbsolutePath(), journalFile.exists());
log.info("Success");
} finally {
if (broker != null) {
broker.stop();
}
}
}
/*
* This tests creating a memory persistence adapter using xbeans-spring
*/
public void testMemoryConfig() throws Exception {
System.out.print("Checking memory persistence adapter configuration... ");
File journalFile = new File(JOURNAL_ROOT + "testMemoryConfig");
recursiveDelete(journalFile);
File derbyFile = new File(DERBY_ROOT + "testMemoryConfig");
recursiveDelete(derbyFile);
BrokerService broker;
broker = createBroker(new FileSystemResource(CONF_ROOT + "memory-example.xml"));
try {
assertEquals("Broker Config Error (brokerName)", "brokerMemoryConfigTest", broker.getBrokerName());
PersistenceAdapter adapter = broker.getPersistenceAdapter();
assertTrue("Should have created a memory persistence adapter", adapter instanceof MemoryPersistenceAdapter);
assertTrue("Should have not created a derby directory at " + derbyFile.getAbsolutePath(), !derbyFile.exists());
assertTrue("Should have not created a journal directory at " + journalFile.getAbsolutePath(), !journalFile.exists());
log.info("Success");
} finally {
if (broker != null) {
broker.stop();
}
}
}
public void testXmlConfigHelper() throws Exception {
BrokerService broker;
broker = createBroker(new FileSystemResource(CONF_ROOT + "memory-example.xml"));
try {
assertEquals("Broker Config Error (brokerName)", "brokerMemoryConfigTest", broker.getBrokerName());
} finally {
if (broker != null) {
broker.stop();
}
}
broker = createBroker("org/apache/activemq/config/config.xml");
try {
assertEquals("Broker Config Error (brokerName)", "brokerXmlConfigHelper", broker.getBrokerName());
} finally {
if (broker != null) {
broker.stop();
}
}
}
/*
* TODO: Create additional tests for forwarding bridges
*/
protected static void recursiveDelete(File file) {
if( file.isDirectory() ) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
recursiveDelete(files[i]);
}
}
file.delete();
}
protected BrokerService createBroker(String resource) throws Exception {
return createBroker(new ClassPathResource(resource));
}
protected BrokerService createBroker(Resource resource) throws Exception {
BrokerFactoryBean factory = new BrokerFactoryBean(resource);
factory.afterPropertiesSet();
BrokerService broker = factory.getBroker();
assertTrue("Should have a broker!", broker != null);
//Broker is already started by default when using the XML file
// broker.start();
return broker;
}
}

View File

@ -0,0 +1,36 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.transport;
/**
* @version $Revision$
*/
public class QueueClusterTest extends TopicClusterTest {
protected void setUp() throws Exception{
topic = false;
super.setUp();
}
protected int expectedReceiveCount(){
return MESSAGE_COUNT * NUMBER_IN_CLUSTER;
}
}

View File

@ -0,0 +1,179 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.transport;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.util.ServiceStopper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger;
/**
* @version $Revision$
*/
public class TopicClusterTest extends TestCase implements MessageListener {
protected final static Log log = LogFactory.getLog(TopicClusterTest.class);
protected Destination destination;
protected boolean topic = true;
protected AtomicInteger receivedMessageCount = new AtomicInteger(0);
protected static int MESSAGE_COUNT = 50;
protected static int NUMBER_IN_CLUSTER = 3;
protected int deliveryMode = DeliveryMode.NON_PERSISTENT;
protected MessageProducer[] producers;
protected Connection[] connections;
protected List services = new ArrayList();
protected void setUp() throws Exception {
connections = new Connection[NUMBER_IN_CLUSTER];
producers = new MessageProducer[NUMBER_IN_CLUSTER];
Destination destination = createDestination();
int portStart = 50000;
String root = System.getProperty("activemq.store.dir");
if (root == null) {
root = "target/store";
}
try {
for (int i = 0;i < NUMBER_IN_CLUSTER;i++) {
System.setProperty("activemq.store.dir", root + "_broker_" + i);
connections[i] = createConnection("broker-" + i);
connections[i].setClientID("ClusterTest" + i);
connections[i].start();
Session session = connections[i].createSession(false, Session.AUTO_ACKNOWLEDGE);
producers[i] = session.createProducer(destination);
producers[i].setDeliveryMode(deliveryMode);
MessageConsumer consumer = createMessageConsumer(session,destination);
consumer.setMessageListener(this);
}
log.info("Sleeping to ensure cluster is fully connected");
Thread.sleep(5000);
} finally {
System.setProperty("activemq.store.dir", root);
}
}
protected void tearDown() throws Exception {
if (connections != null) {
for (int i = 0;i < connections.length;i++) {
connections[i].close();
}
}
ServiceStopper stopper = new ServiceStopper();
stopper.stopServices(services);
}
protected MessageConsumer createMessageConsumer(Session session, Destination destination) throws JMSException{
return session.createConsumer(destination);
}
protected ActiveMQConnectionFactory createGenericClusterFactory(String brokerName) throws Exception {
BrokerService container = new BrokerService();
container.setBrokerName(brokerName);
String url = "tcp://localhost:0";
TransportConnector connector = container.addConnector(url);
connector.setDiscoveryUri(new URI("multicast://default"));
container.addNetworkConnector("multicast://default");
container.start();
services.add(container);
return new ActiveMQConnectionFactory("vm://"+brokerName);
}
protected int expectedReceiveCount() {
return MESSAGE_COUNT * NUMBER_IN_CLUSTER * NUMBER_IN_CLUSTER;
}
protected Connection createConnection(String name) throws Exception {
return createGenericClusterFactory(name).createConnection();
}
protected Destination createDestination() {
return createDestination(getClass().getName());
}
protected Destination createDestination(String name) {
if (topic) {
return new ActiveMQTopic(name);
}
else {
return new ActiveMQQueue(name);
}
}
/**
* @param msg
*/
public void onMessage(Message msg) {
//log.info("GOT: " + msg);
receivedMessageCount.incrementAndGet();
synchronized (receivedMessageCount) {
if (receivedMessageCount.get() >= expectedReceiveCount()) {
receivedMessageCount.notify();
}
}
}
/**
* @throws Exception
*/
public void testSendReceive() throws Exception {
for (int i = 0;i < MESSAGE_COUNT;i++) {
TextMessage textMessage = new ActiveMQTextMessage();
textMessage.setText("MSG-NO:" + i);
for (int x = 0;x < producers.length;x++) {
producers[x].send(textMessage);
}
}
synchronized (receivedMessageCount) {
if (receivedMessageCount.get() < expectedReceiveCount()) {
receivedMessageCount.wait(20000);
}
}
//sleep a little - to check we don't get too many messages
Thread.sleep(2000);
System.err.println("GOT: " + receivedMessageCount.get());
assertEquals("Expected message count not correct", expectedReceiveCount(), receivedMessageCount.get());
}
}

View File

@ -0,0 +1,63 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import java.util.HashMap;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import org.apache.activemq.test.TestSupport;
/**
* @version $Revision: 1.1.1.1 $
*/
public class ChangeSentMessageTest extends TestSupport {
private static final int COUNT = 200;
private static final String VALUE_NAME = "value";
/**
* test Object messages can be changed after sending with no side-affects
* @throws Exception
*/
public void testDoChangeSentMessage() throws Exception {
Destination destination = createDestination("test-"+ChangeSentMessageTest.class.getName());
Connection connection = createConnection();
connection.start();
Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = consumerSession.createConsumer(destination);
Session publisherSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = publisherSession.createProducer(destination);
HashMap map = new HashMap();
ObjectMessage message = publisherSession.createObjectMessage();
for (int i = 0;i < COUNT;i++) {
map.put(VALUE_NAME, new Integer(i));
message.setObject(map);
producer.send(message);
assertTrue(message.getObject()==map);
}
for (int i = 0;i < COUNT;i++) {
ObjectMessage msg = (ObjectMessage) consumer.receive();
HashMap receivedMap = (HashMap) msg.getObject();
Integer intValue = (Integer) receivedMap.get(VALUE_NAME);
assertTrue(intValue.intValue() == i);
}
}
}

View File

@ -0,0 +1,62 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.IllegalStateException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import org.apache.activemq.test.TestSupport;
/**
* @version $Revision: 1.1.1.1 $
*/
public class ChangeSessionDeliveryModeTest extends TestSupport implements MessageListener {
/**
* test following condition- which are defined by JMS Spec 1.1: MessageConsumers cannot use a MessageListener and
* receive() from the same session
*
* @throws Exception
*/
public void testDoChangeSessionDeliveryMode() throws Exception {
Destination destination = createDestination("foo.bar");
Connection connection = createConnection();
connection.start();
Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer1 = consumerSession.createConsumer(destination);
consumer1.setMessageListener(this);
JMSException jmsEx = null;
MessageConsumer consumer2 = consumerSession.createConsumer(destination);
try {
consumer2.receive(10);
fail("Did not receive expected exception.");
}
catch (JMSException e) {
assertTrue(e instanceof IllegalStateException);
}
}
public void onMessage(Message msg) {
}
}

View File

@ -0,0 +1,70 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest;
import javax.jms.Destination;
import javax.jms.Message;
/**
* @version $Revision: 1.1.1.1 $
*/
public class CompositeConsumeTest extends JmsTopicSendReceiveWithTwoConnectionsTest {
public void testSendReceive() throws Exception {
messages.clear();
Destination[] destinations = getDestinations();
int destIdx = 0;
for (int i = 0; i < data.length; i++) {
Message message = session.createTextMessage(data[i]);
if (verbose) {
log.info("About to send a message: " + message + " with text: " + data[i]);
}
producer.send(destinations[destIdx], message);
if (++destIdx >= destinations.length) {
destIdx = 0;
}
}
assertMessagesAreReceived();
}
/**
* Returns the subscription subject
*/
protected String getSubject() {
return getPrefix() + "FOO.BAR," + getPrefix() + "FOO.X.Y," + getPrefix() + "BAR.>";
}
/**
* Returns the destinations on which we publish
*/
protected Destination[] getDestinations() {
return new Destination[]{new ActiveMQTopic(getPrefix() + "FOO.BAR"), new ActiveMQTopic(getPrefix() + "BAR.WHATNOT.XYZ"), new ActiveMQTopic(getPrefix() + "FOO.X.Y")};
}
protected String getPrefix() {
return super.getSubject() + ".";
}
}

View File

@ -0,0 +1,142 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.test.JmsSendReceiveTestSupport;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import java.util.List;
/**
* @version $Revision: 1.1.1.1 $
*/
public class CompositePublishTest extends JmsSendReceiveTestSupport {
protected Connection sendConnection;
protected Connection receiveConnection;
protected Session receiveSession;
protected MessageConsumer[] consumers;
protected List[] messageLists;
protected void setUp() throws Exception {
super.setUp();
connectionFactory = createConnectionFactory();
sendConnection = createConnection();
sendConnection.start();
receiveConnection = createConnection();
receiveConnection.start();
log.info("Created sendConnection: " + sendConnection);
log.info("Created receiveConnection: " + receiveConnection);
session = sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
receiveSession = receiveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
log.info("Created sendSession: " + session);
log.info("Created receiveSession: " + receiveSession);
producer = session.createProducer(null);
log.info("Created producer: " + producer);
if (topic) {
consumerDestination = session.createTopic(getConsumerSubject());
producerDestination = session.createTopic(getProducerSubject());
}
else {
consumerDestination = session.createQueue(getConsumerSubject());
producerDestination = session.createQueue(getProducerSubject());
}
log.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass());
log.info("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass());
Destination[] destinations = getDestinations();
consumers = new MessageConsumer[destinations.length];
messageLists = new List[destinations.length];
for (int i = 0; i < destinations.length; i++) {
Destination dest = destinations[i];
messageLists[i] = createConcurrentList();
consumers[i] = receiveSession.createConsumer(dest);
consumers[i].setMessageListener(createMessageListener(i, messageLists[i]));
}
log.info("Started connections");
}
protected MessageListener createMessageListener(int i, final List messageList) {
return new MessageListener() {
public void onMessage(Message message) {
consumeMessage(message, messageList);
}
};
}
/**
* Returns the subject on which we publish
*/
protected String getSubject() {
return getPrefix() + "FOO.BAR," + getPrefix() + "FOO.X.Y";
}
/**
* Returns the destinations to which we consume
*/
protected Destination[] getDestinations() {
return new Destination[]{new ActiveMQTopic(getPrefix() + "FOO.BAR"), new ActiveMQTopic(getPrefix() + "FOO.*"), new ActiveMQTopic(getPrefix() + "FOO.X.Y")};
}
protected String getPrefix() {
return super.getSubject() + ".";
}
protected void assertMessagesAreReceived() throws JMSException {
waitForMessagesToBeDelivered();
for (int i = 0, size = messageLists.length; i < size; i++) {
log.info("Message list: " + i + " contains: " + messageLists[i].size() + " message(s)");
}
for (int i = 0, size = messageLists.length; i < size; i++) {
assertMessagesReceivedAreValid(messageLists[i]);
}
}
protected ActiveMQConnectionFactory createConnectionFactory() {
return new ActiveMQConnectionFactory("vm://localhost");
}
protected void tearDown() throws Exception {
session.close();
receiveSession.close();
sendConnection.close();
receiveConnection.close();
}
}

View File

@ -0,0 +1,42 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import javax.jms.JMSException;
/**
* @version $Revision: 1.1.1.1 $
*/
public class ConsumeQueuePrefetchTest extends ConsumeTopicPrefetchTest {
/**
* TODO disabled failing test cases until we fix queue dispatching
*/
public void testSendDoublePrefetchSize() throws JMSException {
}
/**
* TODO disabled failing test cases until we fix queue dispatching
*/
public void testSendPrefetchSizePlusOne() throws JMSException {
}
protected void setUp() throws Exception {
topic = false;
super.setUp();
}
}

View File

@ -0,0 +1,87 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
/**
* @version $Revision: 1.1.1.1 $
*/
public class ConsumeTopicPrefetchTest extends ProducerConsumerTestSupport {
protected int prefetchSize = 100;
protected String[] messageTexts;
protected long consumerTimeout = 10000L;
public void testSendPrefetchSize() throws JMSException {
testWithMessageCount(prefetchSize);
}
public void testSendDoublePrefetchSize() throws JMSException {
testWithMessageCount(prefetchSize * 2);
}
public void testSendPrefetchSizePlusOne() throws JMSException {
testWithMessageCount(prefetchSize + 1);
}
protected void testWithMessageCount(int messageCount) throws JMSException {
makeMessages(messageCount);
log.info("About to send and receive: " + messageCount + " on destination: " + destination
+ " of type: " + destination.getClass().getName());
for (int i = 0; i < messageCount; i++) {
Message message = session.createTextMessage(messageTexts[i]);
producer.send(message);
}
// lets consume them in two fetch batches
for (int i = 0; i < messageCount; i++) {
consumeMessge(i);
}
}
protected Connection createConnection() throws Exception {
ActiveMQConnection connection = (ActiveMQConnection) super.createConnection();
connection.getPrefetchPolicy().setQueuePrefetch(prefetchSize);
connection.getPrefetchPolicy().setTopicPrefetch(prefetchSize);
return connection;
}
protected void consumeMessge(int i) throws JMSException {
Message message = consumer.receive(consumerTimeout);
assertTrue("Should have received a message by now for message: " + i, message != null);
assertTrue("Should be a TextMessage: " + message, message instanceof TextMessage);
TextMessage textMessage = (TextMessage) message;
assertEquals("Message content", messageTexts[i], textMessage.getText());
}
protected void makeMessages(int messageCount) {
messageTexts = new String[messageCount];
for (int i = 0; i < messageCount; i++) {
messageTexts[i] = "Message for test: + " + getName() + " = " + i;
}
}
}

View File

@ -0,0 +1,71 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.EmbeddedBrokerTestSupport;
import javax.jms.Connection;
import javax.jms.Session;
import javax.jms.TemporaryQueue;
import junit.framework.Test;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
/**
*
* @version $Revision: 1.1 $
*/
public class CreateLotsOfTemporaryQueuesTest extends EmbeddedBrokerTestSupport {
private static int numberToCreate = 500;
private static long sleep = 20;
public static void main(String[] args) {
configure(args);
TestRunner.run(suite());
}
public static Test suite() {
return new TestSuite(CreateLotsOfTemporaryQueuesTest.class);
}
public void testCreateLotsOfTemporaryQueues() throws Exception {
log.info("Creating " + numberToCreate + " temporary queue(s)");
Connection connection = createConnection();
connection.start();
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
for (int i = 0; i < numberToCreate; i++) {
if (i % 1000 == 0) {
log.info("attempt " + i);
}
TemporaryQueue temporaryQueue = session.createTemporaryQueue();
temporaryQueue.delete();
Thread.sleep(sleep );
}
log.info("Created " + numberToCreate + " temporary queue(s)");
connection.close();
}
public static void configure(String[] args) {
if (args.length > 0) {
numberToCreate = Integer.parseInt(args[0]);
}
}
}

View File

@ -0,0 +1,132 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import javax.jms.Connection;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.Topic;
import junit.framework.TestCase;
/**
* @author Peter Henning
* @version $Revision: 1.1.1.1 $
*/
public class CreateTemporaryQueueBeforeStartTest extends TestCase {
protected String bindAddress = "tcp://localhost:61621";
private Connection connection;
private BrokerService broker = new BrokerService();
public void testCreateTemporaryQueue() throws Exception {
connection = createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createTemporaryQueue();
assertTrue("No queue created!", queue != null);
Topic topic = session.createTemporaryTopic();
assertTrue("No topic created!", topic != null);
}
public void testTryToReproduceNullPointerBug() throws Exception {
String url = bindAddress;
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);
QueueConnection queueConnection = factory.createQueueConnection();
this.connection = queueConnection;
QueueSession session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
QueueSender sender = session.createSender(null); //Unidentified
Queue receiverQueue = session.createTemporaryQueue();
QueueReceiver receiver = session.createReceiver(receiverQueue);
queueConnection.start();
}
public void testTemporaryQueueConsumer() throws Exception {
final int NUMBER = 20;
final AtomicInteger count = new AtomicInteger(0);
for (int i = 0;i < NUMBER;i++) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
QueueConnection connection = createConnection();
QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createTemporaryQueue();
QueueReceiver consumer = session.createReceiver(queue);
connection.start();
if (count.incrementAndGet() >= NUMBER){
synchronized(count){
count.notify();
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
thread.start();
}
int maxWaitTime = 20000;
synchronized (count) {
long waitTime = maxWaitTime;
long start = System.currentTimeMillis();
while (count.get() < NUMBER) {
if (waitTime <= 0) {
break;
}
else {
count.wait(waitTime);
waitTime = maxWaitTime - (System.currentTimeMillis() - start);
}
}
}
assertTrue("Unexpected count: " + count, count.get() == NUMBER);
}
protected QueueConnection createConnection() throws Exception {
ActiveMQConnectionFactory factory = createConnectionFactory();
return factory.createQueueConnection();
}
protected ActiveMQConnectionFactory createConnectionFactory() throws Exception {
return new ActiveMQConnectionFactory(bindAddress);
}
protected void setUp() throws Exception {
broker.setPersistent(false);
broker.addConnector(bindAddress);
broker.start();
super.setUp();
}
protected void tearDown() throws Exception {
if (connection != null) {
connection.close();
}
broker.stop();
super.tearDown();
}
}

View File

@ -0,0 +1,172 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.test.TestSupport;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;
/**
* @version $Revision: 1.1.1.1 $
*/
public class DurableConsumerCloseAndReconnectTest extends TestSupport {
protected static final long RECEIVE_TIMEOUT = 5000L;
private Connection connection;
private Session session;
private MessageConsumer consumer;
private MessageProducer producer;
private Destination destination;
protected ActiveMQConnectionFactory createConnectionFactory() throws Exception {
return new ActiveMQConnectionFactory("vm://localhost?broker.persistent=true");
}
public void testCreateDurableConsumerCloseThenReconnect() throws Exception {
// force the server to stay up across both connection tests
Connection dummyConnection = createConnection();
consumeMessagesDeliveredWhileConsumerClosed();
dummyConnection.close();
// now lets try again without one connection open
consumeMessagesDeliveredWhileConsumerClosed();
}
protected void consumeMessagesDeliveredWhileConsumerClosed() throws Exception {
makeConsumer();
closeConsumer();
publish();
// wait a few moments for the close to really occur
Thread.sleep(1000);
makeConsumer();
Message message = consumer.receive(RECEIVE_TIMEOUT);
assertTrue("Should have received a message!", message != null);
closeConsumer();
log.info("Now lets create the consumer again and because we didn't ack, we should get it again");
makeConsumer();
message = consumer.receive(RECEIVE_TIMEOUT);
assertTrue("Should have received a message!", message != null);
message.acknowledge();
closeConsumer();
log.info("Now lets create the consumer again and because we didn't ack, we should get it again");
makeConsumer();
message = consumer.receive(2000);
assertTrue("Should have no more messages left!", message == null);
closeConsumer();
log.info("Lets publish one more message now");
publish();
makeConsumer();
message = consumer.receive(RECEIVE_TIMEOUT);
assertTrue("Should have received a message!", message != null);
message.acknowledge();
closeConsumer();
}
protected void publish() throws Exception {
connection = createConnection();
connection.start();
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
destination = createDestination();
producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
producer.send(session.createTextMessage("This is a test"));
producer.close();
producer = null;
closeSession();
}
protected Destination createDestination() throws JMSException {
if (isTopic()) {
return session.createTopic(getSubject());
}
else {
return session.createQueue(getSubject());
}
}
protected boolean isTopic() {
return true;
}
protected void closeConsumer() throws JMSException {
consumer.close();
consumer = null;
closeSession();
}
protected void closeSession() throws JMSException {
session.close();
session = null;
connection.close();
connection = null;
}
protected void makeConsumer() throws Exception {
String durableName = getName();
String clientID = getSubject();
log.info("Creating a durable subscribe for clientID: " + clientID + " and durable name: " + durableName);
createSession(clientID);
consumer = createConsumer(durableName);
}
private MessageConsumer createConsumer(String durableName) throws JMSException {
if (destination instanceof Topic) {
return session.createDurableSubscriber((Topic) destination, durableName);
}
else {
return session.createConsumer(destination);
}
}
protected void createSession(String clientID) throws Exception {
connection = createConnection();
connection.setClientID(clientID);
connection.start();
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
destination = createDestination();
}
}

View File

@ -0,0 +1,375 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicSubscriber;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.TestSupport;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.store.PersistenceAdapter;
/**
* @version $Revision: 1.1.1.1 $
*/
abstract public class DurableSubscriptionTestSupport extends TestSupport {
private Connection connection;
private Session session;
private TopicSubscriber consumer;
private MessageProducer producer;
private BrokerService broker;
protected ActiveMQConnectionFactory createConnectionFactory() throws Exception {
return new ActiveMQConnectionFactory("vm://durable-broker");
}
protected Connection createConnection() throws Exception {
Connection rc = super.createConnection();
rc.setClientID(getName());
return rc;
}
protected void setUp() throws Exception {
createBroker();
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
destroyBroker();
}
protected void restartBroker() throws Exception {
destroyBroker();
createRestartedBroker(); // retain stored messages
}
private void createBroker() throws Exception {
try {
broker = new BrokerService();
broker.setBrokerName("durable-broker");
broker.setDeleteAllMessagesOnStartup(true);
broker.setPersistenceAdapter(createPersistenceAdapter());
broker.setPersistent(true);
broker.start();
} catch (Exception e) {
e.printStackTrace();
}
connection = createConnection();
}
private void createRestartedBroker() throws Exception {
try {
broker = new BrokerService();
broker.setBrokerName("durable-broker");
broker.setDeleteAllMessagesOnStartup(false);
broker.setPersistenceAdapter(createPersistenceAdapter());
broker.setPersistent(true);
broker.start();
} catch (Exception e) {
e.printStackTrace();
}
connection = createConnection();
}
private void destroyBroker() throws Exception {
if( connection != null )
connection.close();
if( broker!=null )
broker.stop();
}
abstract protected PersistenceAdapter createPersistenceAdapter() throws Exception;
public void testUnsubscribeSubscription() throws Exception {
session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("TestTopic");
consumer = session.createDurableSubscriber(topic, "sub1");
producer = session.createProducer(topic);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
connection.start();
// Make sure it works when the durable sub is active.
producer.send(session.createTextMessage("Msg:1"));
assertTextMessageEquals("Msg:1", consumer.receive(5000));
// Deactivate the sub.
consumer.close();
// Send a new message.
producer.send(session.createTextMessage("Msg:2"));
session.unsubscribe("sub1");
// Reopen the connection.
connection.close();
connection = createConnection();
session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(topic);
connection.start();
// Activate the sub.
consumer = session.createDurableSubscriber(topic, "sub1");
producer.send(session.createTextMessage("Msg:3"));
// Try to get the message.
assertTextMessageEquals("Msg:3", consumer.receive(5000));
}
public void testInactiveDurableSubscriptionTwoConnections() throws Exception {
session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("TestTopic");
consumer = session.createDurableSubscriber(topic, "sub1");
producer = session.createProducer(topic);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
connection.start();
// Make sure it works when the durable sub is active.
producer.send(session.createTextMessage("Msg:1"));
assertTextMessageEquals("Msg:1", consumer.receive(5000));
// Deactivate the sub.
consumer.close();
// Send a new message.
producer.send(session.createTextMessage("Msg:2"));
// Reopen the connection.
connection.close();
connection = createConnection();
session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
connection.start();
// Activate the sub.
consumer = session.createDurableSubscriber(topic, "sub1");
// Try to get the message.
assertTextMessageEquals("Msg:2", consumer.receive(5000));
}
public void testInactiveDurableSubscriptionBrokerRestart() throws Exception {
session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("TestTopic");
consumer = session.createDurableSubscriber(topic, "sub1");
producer = session.createProducer(topic);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
connection.start();
// Make sure it works when the durable sub is active.
producer.send(session.createTextMessage("Msg:1"));
assertTextMessageEquals("Msg:1", consumer.receive(5000));
// Deactivate the sub.
consumer.close();
// Send a new message.
producer.send(session.createTextMessage("Msg:2"));
// Reopen the connection.
restartBroker();
session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
connection.start();
// Activate the sub.
consumer = session.createDurableSubscriber(topic, "sub1");
// Try to get the message.
assertTextMessageEquals("Msg:2", consumer.receive(5000));
assertNull(consumer.receive(5000));
}
public void testDurableSubscriptionPersistsPastBrokerRestart() throws Exception {
// Create the durable sub.
connection.start();
session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
// Ensure that consumer will receive messages sent before it was created
Topic topic = session.createTopic("TestTopic?consumer.retroactive=true");
consumer = session.createDurableSubscriber(topic, "sub1");
// Restart the broker.
restartBroker();
// Reconnection
connection.start();
session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(topic);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
// Make sure it works when the durable sub is active.
producer.send(session.createTextMessage("Msg:1"));
// Activate the sub.
consumer = session.createDurableSubscriber(topic, "sub1");
// Send a new message.
producer.send(session.createTextMessage("Msg:2"));
// Try to get the message.
assertTextMessageEquals("Msg:1", consumer.receive(5000));
assertTextMessageEquals("Msg:2", consumer.receive(5000));
assertNull(consumer.receive(5000));
}
public void testInactiveDurableSubscriptionOneConnection() throws Exception {
session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("TestTopic");
consumer = session.createDurableSubscriber(topic, "sub1");
producer = session.createProducer(topic);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
connection.start();
// Make sure it works when the durable sub is active.
producer.send(session.createTextMessage("Msg:1"));
assertTextMessageEquals("Msg:1", consumer.receive(5000));
// Deactivate the sub.
consumer.close();
// Send a new message.
producer.send(session.createTextMessage("Msg:2"));
// Activate the sub.
consumer = session.createDurableSubscriber(topic, "sub1");
// Try to get the message.
assertTextMessageEquals("Msg:2", consumer.receive(5000));
}
public void xtestSelectorChange() throws Exception {
session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("TestTopic");
consumer = session.createDurableSubscriber(topic, "sub1", "color='red'", false);
producer = session.createProducer(topic);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
connection.start();
// Make sure it works when the durable sub is active.
TextMessage msg = session.createTextMessage();
msg.setText("Msg:1");
msg.setStringProperty("color", "blue");
producer.send(msg);
msg.setText("Msg:2");
msg.setStringProperty("color", "red");
producer.send(msg);
assertTextMessageEquals("Msg:2", consumer.receive(5000));
// Change the subscription
consumer.close();
consumer = session.createDurableSubscriber(topic, "sub1", "color='blue'", false);
// Send a new message.
msg.setText("Msg:3");
msg.setStringProperty("color", "red");
producer.send(msg);
msg.setText("Msg:4");
msg.setStringProperty("color", "blue");
producer.send(msg);
// Try to get the message.
assertTextMessageEquals("Msg:4", consumer.receive(5000));
}
public void testDurableSubWorksInNewSession() throws JMSException {
// Create the consumer.
connection.start();
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
Topic topic = session.createTopic("topic-"+getName());
MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1");
// Drain any messages that may allready be in the sub
while( consumer.receive(1000)!=null )
;
// See if the durable sub works in a new session.
session.close();
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
// Send a Message that should be added to the durable sub.
MessageProducer producer = createProducer(session, topic);
producer.send(session.createTextMessage("Message 1"));
// Activate the durable sub now. And receive the message.
consumer = session.createDurableSubscriber(topic, "sub1");
Message msg = consumer.receive(1000);
assertNotNull(msg);
assertEquals( "Message 1", ((TextMessage)msg).getText() );
}
public void testDurableSubWorksInNewConnection() throws Exception {
// Create the consumer.
connection.start();
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
Topic topic = session.createTopic("topic-"+getName());
MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1");
// Drain any messages that may allready be in the sub
while( consumer.receive(1000)!=null )
;
// See if the durable sub works in a new connection.
// The embeded broker shutsdown when his connections are closed.
// So we open the new connection before the old one is closed.
connection.close();
connection = createConnection();
connection.start();
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
// Send a Message that should be added to the durable sub.
MessageProducer producer = createProducer(session, topic);
producer.send(session.createTextMessage("Message 1"));
// Activate the durable sub now. And receive the message.
consumer = session.createDurableSubscriber(topic, "sub1");
Message msg = consumer.receive(1000);
assertNotNull(msg);
assertEquals( "Message 1", ((TextMessage)msg).getText() );
}
private MessageProducer createProducer(Session session, Destination queue) throws JMSException {
MessageProducer producer = session.createProducer(queue);
producer.setDeliveryMode(getDeliveryMode());
return producer;
}
protected int getDeliveryMode() {
return DeliveryMode.PERSISTENT;
}
private void assertTextMessageEquals(String string, Message message) throws JMSException {
assertNotNull("Message was null", message);
assertTrue("Message is not a TextMessage", message instanceof TextMessage);
assertEquals(string, ((TextMessage)message).getText());
}
}

View File

@ -0,0 +1,91 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import junit.framework.TestCase;
/**
* @author Oliver Belikan
* @version $Revision: 1.1.1.1 $
*/
public class ExceptionListenerTest extends TestCase implements ExceptionListener {
boolean isException = false;
public ExceptionListenerTest(String arg) {
super(arg);
}
public void testOnException() throws Exception {
/* TODO not sure yet if this is a valid test
System.setProperty("activemq.persistenceAdapter",
"org.apache.activemq.store.vm.VMPersistenceAdapter");
// configuration of container and all protocolls
BrokerContainerImpl container = new
BrokerContainerImpl("DefaultBroker");
BrokerConnectorImpl connector = new
BrokerConnectorImpl(container,
"vm://localhost", new DefaultWireFormat());
container.start();
ActiveMQConnectionFactory factory = new
ActiveMQConnectionFactory("vm://localhost");
factory.start();
Connection connection = factory.createConnection();
connection.setExceptionListener(this);
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createTopic(getClass().getName());
MessageProducer producer = session.createProducer(destination);
try {
Thread.currentThread().sleep(1000);
}
catch (Exception e) {
}
container.stop();
// now lets try send
try {
producer.send(session.createTextMessage("This will never get anywhere"));
}
catch (JMSException e) {
log.info("Caught: " + e);
}
try {
Thread.currentThread().sleep(1000);
}
catch (Exception e) {
}
assertTrue("Should have received an exception", isException);
*/
}
public void onException(JMSException e) {
isException = true;
}
}

View File

@ -0,0 +1,38 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import java.io.File;
import java.io.IOException;
import org.apache.activemq.store.DefaultPersistenceAdapterFactory;
import org.apache.activemq.store.PersistenceAdapter;
/**
* @version $Revision: 1.1.1.1 $
*/
public class JDBCDurableSubscriptionTest extends DurableSubscriptionTestSupport {
protected PersistenceAdapter createPersistenceAdapter() throws IOException {
File dataDir = new File("target/test-data/durableJDBC");
DefaultPersistenceAdapterFactory factory = new DefaultPersistenceAdapterFactory();
factory.setDataDirectory(dataDir);
factory.setUseJournal(false);
return factory.createPersistenceAdapter();
}
}

View File

@ -0,0 +1,38 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import java.io.File;
import java.io.IOException;
import org.apache.activemq.store.DefaultPersistenceAdapterFactory;
import org.apache.activemq.store.PersistenceAdapter;
/**
* @version $Revision: 1.1.1.1 $
*/
public class JournalDurableSubscriptionTest extends DurableSubscriptionTestSupport {
protected PersistenceAdapter createPersistenceAdapter() throws IOException {
File dataDir = new File("target/test-data/durableJournal");
DefaultPersistenceAdapterFactory factory = new DefaultPersistenceAdapterFactory();
factory.setDataDirectory(dataDir);
factory.setUseJournal(true);
factory.setJournalLogFileSize(1024*64);
return factory.createPersistenceAdapter();
}
}

View File

@ -0,0 +1,122 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.util.MessageIdList;
import org.apache.activemq.JmsMultipleBrokersTestSupport;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import java.util.Map;
import java.util.HashMap;
import java.net.URI;
/**
* @version $Revision: 1.1.1.1 $
*/
public class MultiBrokersMultiClientsTest extends JmsMultipleBrokersTestSupport {
public static final int BROKER_COUNT = 2; // number of brokers to network
public static final int CONSUMER_COUNT = 3; // consumers per broker
public static final int PRODUCER_COUNT = 3; // producers per broker
public static final int MESSAGE_COUNT = 10; // messages per producer
protected Map consumerMap;
public void testTopicAllConnected() throws Exception {
bridgeAllBrokers();
startAllBrokers();
// Setup topic destination
Destination dest = createDestination("TEST.FOO", true);
// Setup consumers
for (int i=1; i<=BROKER_COUNT; i++) {
for (int j=0; j<CONSUMER_COUNT; j++) {
consumerMap.put("Consumer:" + i + ":" + j, createConsumer("Broker" + i, dest));
}
}
//wait for consumers to get propagated
Thread.sleep(2000);
// Send messages
for (int i=1; i<=BROKER_COUNT; i++) {
for (int j=0; j<PRODUCER_COUNT; j++) {
sendMessages("Broker" + i, dest, MESSAGE_COUNT);
}
}
// Get message count
for (int i=1; i<=BROKER_COUNT; i++) {
for (int j=0; j<CONSUMER_COUNT; j++) {
MessageIdList msgs = getConsumerMessages("Broker" + i, (MessageConsumer)consumerMap.get("Consumer:" + i + ":" + j));
msgs.waitForMessagesToArrive(BROKER_COUNT * PRODUCER_COUNT * MESSAGE_COUNT);
assertEquals(BROKER_COUNT * PRODUCER_COUNT * MESSAGE_COUNT, msgs.getMessageCount());
}
}
}
public void testQueueAllConnected() throws Exception {
bridgeAllBrokers();
startAllBrokers();
// Setup topic destination
Destination dest = createDestination("TEST.FOO", false);
// Setup consumers
for (int i=1; i<=BROKER_COUNT; i++) {
for (int j=0; j<CONSUMER_COUNT; j++) {
consumerMap.put("Consumer:" + i + ":" + j, createConsumer("Broker" + i, dest));
}
}
Thread.sleep(2000);
// Send messages
for (int i=1; i<=BROKER_COUNT; i++) {
for (int j=0; j<PRODUCER_COUNT; j++) {
sendMessages("Broker" + i, dest, MESSAGE_COUNT);
}
}
// Wait for messages to be delivered
Thread.sleep(2000);
// Get message count
int totalMsg = 0;
for (int i=1; i<=BROKER_COUNT; i++) {
for (int j=0; j<CONSUMER_COUNT; j++) {
MessageIdList msgs = getConsumerMessages("Broker" + i, (MessageConsumer)consumerMap.get("Consumer:" + i + ":" + j));
totalMsg += msgs.getMessageCount();
}
}
assertEquals(BROKER_COUNT * PRODUCER_COUNT * MESSAGE_COUNT, totalMsg);
}
public void setUp() throws Exception {
super.setAutoFail(true);
super.setUp();
// Setup n brokers
for (int i=1; i<=BROKER_COUNT; i++) {
createBroker(new URI("broker:()/Broker" + i + "?persistent=false&useJmx=false"));
}
consumerMap = new HashMap();
}
}

View File

@ -0,0 +1,83 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.network.DemandForwardingBridge;
import org.apache.activemq.transport.TransportFactory;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
import java.net.URI;
/**
* @version $Revision: 1.1.1.1 $
*/
public class MultiBrokersMultiClientsUsingTcpTest extends MultiBrokersMultiClientsTest {
protected List bridges;
protected void bridgeAllBrokers(String groupName) throws Exception {
for (int i=1; i<=BROKER_COUNT; i++) {
for (int j=1; j<=BROKER_COUNT; j++) {
if (i != j) {
bridgeBrokers("Broker" + i, "Broker" + j);
}
}
}
MAX_SETUP_TIME = 5000;
}
protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception {
List remoteTransports = remoteBroker.getTransportConnectors();
List localTransports = localBroker.getTransportConnectors();
URI remoteURI, localURI;
if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) {
remoteURI = ((TransportConnector)remoteTransports.get(0)).getConnectUri();
localURI = ((TransportConnector)localTransports.get(0)).getConnectUri();
// Ensure that we are connecting using tcp
if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) {
DemandForwardingBridge bridge = new DemandForwardingBridge(TransportFactory.connect(localURI),
TransportFactory.connect(remoteURI));
bridge.setLocalBrokerName(localBroker.getBrokerName());
bridges.add(bridge);
bridge.start();
} else {
throw new Exception("Remote broker or local broker is not using tcp connectors");
}
} else {
throw new Exception("Remote broker or local broker has no registered connectors.");
}
}
public void setUp() throws Exception {
super.setUp();
// Assign a tcp connector to each broker
int j=0;
for (Iterator i=brokers.values().iterator(); i.hasNext();) {
((BrokerItem)i.next()).broker.addConnector("tcp://localhost:" + (61616 + j++));
}
bridges = new ArrayList();
}
}

View File

@ -0,0 +1,56 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
/**
* Base class for simple test cases using a single connection, session
* producer and consumer
*
* @version $Revision: 1.1.1.1 $
*/
public class ProducerConsumerTestSupport extends TestSupport {
protected Connection connection;
protected Session session;
protected MessageProducer producer;
protected MessageConsumer consumer;
protected Destination destination;
protected void setUp() throws Exception {
super.setUp();
connection = createConnection();
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
destination = this.createDestination(getSubject());
producer = session.createProducer(destination);
consumer = session.createConsumer(destination);
connection.start();
}
protected void tearDown() throws Exception {
consumer.close();
producer.close();
session.close();
connection.close();
super.tearDown();
}
}

View File

@ -0,0 +1,28 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
/**
* @version $Revision: 1.1.1.1 $
*/
public class PublishOnDurableTopicConsumedMessageTest extends PublishOnTopicConsumedMessageTest {
protected void setUp() throws Exception {
this.durable = true;
super.setUp();
}
}

View File

@ -0,0 +1,184 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.jms.*;
import java.util.List;
import java.util.Collections;
import java.util.ArrayList;
import java.io.File;
public final class PublishOnQueueConsumedMessageInTransactionTest extends TestCase implements MessageListener {
private static final Log log = LogFactory.getLog(PublishOnQueueConsumedMessageInTransactionTest.class);
private Session producerSession;
private Session consumerSession;
private Destination queue;
private ActiveMQConnectionFactory factory;
private MessageProducer producer;
private MessageConsumer consumer;
private Connection connection;
private ObjectMessage objectMessage = null;
private List messages = createConcurrentList();
private final Object lock = new Object();
private String[] data;
private String DATAFILE_ROOT = "activemq-data";
private int messageCount = 3;
private String url = "vm://localhost";
// Invalid acknowledgment warning can be viewed on the console of a remote broker
// The warning message is not thrown back to the client
//private String url = "tcp://localhost:61616";
protected void setUp() throws Exception {
File dataFile = new File(DATAFILE_ROOT);
recursiveDelete(dataFile);
try {
factory = new ActiveMQConnectionFactory(url);
connection = factory.createConnection();
producerSession = connection.createSession(true, Session.SESSION_TRANSACTED);
consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED);
queue = new ActiveMQQueue("FOO.BAR");
data = new String[messageCount];
for (int i = 0; i < messageCount; i++) {
data[i] = "Message : " + i;
}
} catch (JMSException je) {
fail("Error setting up connection : " + je.toString());
}
}
public void testSendReceive() throws Exception {
sendMessage();
connection.start();
consumer = consumerSession.createConsumer(queue);
consumer.setMessageListener(this);
waitForMessagesToBeDelivered();
assertEquals("Messages received doesn't equal messages sent", messages.size(),data.length);
}
protected void sendMessage() throws JMSException {
messages.clear();
try {
for (int i = 0; i < data.length; ++i) {
producer = producerSession.createProducer(queue);
objectMessage = producerSession.createObjectMessage(data[i]);
producer.send(objectMessage);
producerSession.commit();
log.info("sending message :" + objectMessage);
}
} catch (Exception e) {
if (producerSession != null) {
producerSession.rollback();
log.info("rollback");
producerSession.close();
}
e.printStackTrace();
}
}
public synchronized void onMessage(Message m) {
try {
objectMessage = (ObjectMessage) m;
consumeMessage(objectMessage,messages);
log.info("consumer received message :" + objectMessage);
consumerSession.commit();
} catch (Exception e) {
try {
consumerSession.rollback();
log.info("rolled back transaction");
} catch (JMSException e1) {
log.info(e1);
e1.printStackTrace();
}
log.info(e);
e.printStackTrace();
}
}
protected void consumeMessage(Message message, List messageList) {
messageList.add(message);
if (messageList.size() >= data.length) {
synchronized (lock) {
lock.notifyAll();
}
}
}
protected List createConcurrentList() {
return Collections.synchronizedList(new ArrayList());
}
protected void waitForMessagesToBeDelivered() {
long maxWaitTime = 5000;
long waitTime = maxWaitTime;
long start = (maxWaitTime <= 0) ? 0 : System.currentTimeMillis();
synchronized (lock) {
while (messages.size() <= data.length && waitTime >= 0) {
try {
lock.wait(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
waitTime = maxWaitTime - (System.currentTimeMillis() - start);
}
}
}
protected static void recursiveDelete(File file) {
if( file.isDirectory() ) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
recursiveDelete(files[i]);
}
}
file.delete();
}
protected void tearDown() throws Exception {
if (connection != null) {
connection.close();
}
super.tearDown();
}
}

View File

@ -0,0 +1,28 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
/**
* @version $Revision: 1.1.1.1 $
*/
public class PublishOnQueueConsumedMessageTest extends PublishOnTopicConsumedMessageTest {
protected void setUp() throws Exception {
topic = false;
super.setUp();
}
}

View File

@ -0,0 +1,113 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.xbean.BrokerFactoryBean;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.File;
/**
*
* Test Publish/Consume queue using the release activemq.xml configuration file
*
* @version $Revision: 1.2 $
*/
public class PublishOnQueueConsumedMessageUsingActivemqXMLTest extends PublishOnTopicConsumedMessageTest {
protected static final String JOURNAL_ROOT = "../data/";
BrokerService broker;
/**
* Use the transportConnector uri configured on the activemq.xml
*
* @return ActiveMQConnectionFactory
* @throws Exception
*/
protected ActiveMQConnectionFactory createConnectionFactory() throws Exception {
return new ActiveMQConnectionFactory("tcp://localhost:61616");
}
/**
* Sets up a test where the producer and consumer have their own connection.
*
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
;
File journalFile = new File(JOURNAL_ROOT);
recursiveDelete(journalFile);
// Create broker from resource
System.out.print("Creating broker... ");
broker = createBroker("org/apache/activemq/usecases/activemq.xml");
log.info("Success");
super.setUp();
}
/*
* Stops the Broker
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
log.info("Closing Broker");
if (broker != null) {
broker.stop();
}
log.info("Broker closed...");
}
/*
* clean up the journal
*/
protected static void recursiveDelete(File file) {
if( file.isDirectory() ) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
recursiveDelete(files[i]);
}
}
file.delete();
}
protected BrokerService createBroker(String resource) throws Exception {
return createBroker(new ClassPathResource(resource));
}
protected BrokerService createBroker(Resource resource) throws Exception {
BrokerFactoryBean factory = new BrokerFactoryBean(resource);
factory.afterPropertiesSet();
BrokerService broker = factory.getBroker();
//assertTrue("Should have a broker!", broker != null);
return broker;
}
}

View File

@ -0,0 +1,31 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import javax.jms.DeliveryMode;
/**
* @version $Revision: 1.1.1.1 $
*/
public class PublishOnTemporaryQueueConsumedMessageTest extends PublishOnTopicConsumedMessageTest {
protected void setUp() throws Exception {
topic = false;
deliveryMode = DeliveryMode.NON_PERSISTENT;
super.setUp();
}
}

View File

@ -0,0 +1,65 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
/**
* @version $Revision: 1.1.1.1 $
*/
public class PublishOnTopicConsumedMessageTest extends JmsTopicSendReceiveWithTwoConnectionsTest {
private MessageProducer replyProducer;
public synchronized void onMessage(Message message) {
// lets resend the message somewhere else
try {
Message msgCopy = (Message)((org.apache.activemq.command.Message)message).copy();
replyProducer.send(msgCopy);
//log.info("Sending reply: " + message);
super.onMessage(message);
}
catch (JMSException e) {
log.info("Failed to send message: " + e);
e.printStackTrace();
}
}
protected void setUp() throws Exception {
super.setUp();
Destination replyDestination = null;
if (topic) {
replyDestination = receiveSession.createTopic("REPLY." + getSubject());
}
else {
replyDestination = receiveSession.createQueue("REPLY." + getSubject());
}
replyProducer = receiveSession.createProducer(replyDestination);
log.info("Created replyProducer: " + replyProducer);
}
}

View File

@ -0,0 +1,115 @@
/**
*
* Copyright 2005 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.xbean.BrokerFactoryBean;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.File;
/**
*
* Test Publish/Consume topic using the release activemq.xml configuration file
*
* @version $Revision: 1.2 $
*/
public class PublishOnTopicConsumerMessageUsingActivemqXMLTest extends PublishOnTopicConsumedMessageTest {
protected static final String JOURNAL_ROOT = "../data/";
BrokerService broker;
/**
* Use the transportConnector uri configured on the activemq.xml
*
* @return ActiveMQConnectionFactory
* @throws Exception
*/
protected ActiveMQConnectionFactory createConnectionFactory() throws Exception {
return new ActiveMQConnectionFactory("tcp://localhost:61616");
}
/**
* Sets up a test where the producer and consumer have their own connection.
*
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
;
File journalFile = new File(JOURNAL_ROOT);
recursiveDelete(journalFile);
// Create broker from resource
System.out.print("Creating broker... ");
broker = createBroker("org/apache/activemq/usecases/activemq.xml");
log.info("Success");
super.setUp();
}
/*
* Stops the Broker
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
log.info("Closing Broker");
if (broker != null) {
broker.stop();
}
log.info("Broker closed...");
}
/*
* clean up the journal
*/
protected static void recursiveDelete(File file) {
if( file.isDirectory() ) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
recursiveDelete(files[i]);
}
}
file.delete();
}
protected BrokerService createBroker(String resource) throws Exception {
return createBroker(new ClassPathResource(resource));
}
protected BrokerService createBroker(Resource resource) throws Exception {
BrokerFactoryBean factory = new BrokerFactoryBean(resource);
factory.afterPropertiesSet();
BrokerService broker = factory.getBroker();
//assertTrue("Should have a broker!", broker != null);
return broker;
}
}

View File

@ -0,0 +1,26 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
/**
* @version $Revision: 1.1.1.1 $
*/
public class QueueConsumerCloseAndReconnectTest extends DurableConsumerCloseAndReconnectTest {
protected boolean isTopic() {
return false;
}
}

View File

@ -0,0 +1,160 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class QueueDuplicatesTest extends TestCase {
private static final Log log = LogFactory.getLog(QueueDuplicatesTest.class);
private static DateFormat formatter = new SimpleDateFormat("HH:mm:ss SSS");
private String brokerUrl;
private String subject;
private Connection brokerConnection;
public QueueDuplicatesTest(String name) {
super(name);
}
protected void setUp() throws Exception {
String peerUrl = "peer://localhost:6099";
subject = this.getClass().getName();
ActiveMQConnectionFactory fac = createFactory(peerUrl);
brokerConnection = fac.createConnection();
brokerConnection.start();
}
protected void tearDown() throws Exception {
if (brokerConnection != null) {
brokerConnection.close();
}
}
public void testDuplicates() {
try {
// Get Session
Session session = createSession(brokerConnection);
// create consumer
Destination dest = session.createQueue(subject);
MessageConsumer consumer = session.createConsumer(dest);
// subscribe to queue
consumer.setMessageListener(new SimpleConsumer());
// create producer
Thread sendingThread = new SendingThread(brokerUrl, subject);
// start producer
sendingThread.start();
// wait about 5 seconds
Thread.sleep(5000);
// unsubscribe consumer
consumer.close();
// wait another 5 seconds
Thread.sleep(5000);
// create new consumer
consumer = session.createConsumer(dest);
// subscribe to queue
consumer.setMessageListener(new SimpleConsumer());
// sleep a little while longer
Thread.sleep(15000);
session.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
Session createSession(Connection peerConnection) throws JMSException {
// Connect using peer to peer connection
Session session = peerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
return session;
}
private ActiveMQConnectionFactory createFactory(String brokerUrl) {
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory();
cf.setBrokerURL(brokerUrl);
return cf;
}
private class SendingThread extends Thread {
private String brokerUrl;
private String subject;
SendingThread(String brokerUrl, String subject) {
this.brokerUrl = brokerUrl;
this.subject = subject;
setDaemon(false);
}
public void run() {
try {
Session session = createSession(brokerConnection);
Destination dest = session.createQueue(subject);
MessageProducer producer = session.createProducer(dest);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
for (int i = 0;i < 20;i++) {
String txt = "Text Message: " + i;
TextMessage msg = session.createTextMessage(txt);
producer.send(msg);
log.info(formatter.format(new Date()) + " Sent ==> " + msg + " to " + subject);
Thread.sleep(1000);
}
session.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
private static class SimpleConsumer implements MessageListener {
private Map msgs = new HashMap();
public void onMessage(Message message) {
log.info(formatter.format(new Date()) + " SimpleConsumer Message Received: " + message);
try {
String id = message.getJMSMessageID();
assertNull("Message is duplicate: " + id, msgs.get(id));
msgs.put(id, message);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}

View File

@ -0,0 +1,30 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
/**
* @version $Revision: 1.1.1.1 $
*/
public class QueueRedeliverTest extends TopicRedeliverTest {
protected void setUp() throws Exception{
super.setUp();
topic = false;
}
}

View File

@ -0,0 +1,180 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import java.util.HashMap;
import java.net.URI;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.Broker;
import org.apache.activemq.test.TestSupport;
import org.apache.activemq.util.IdGenerator;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicBoolean;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger;
/**
* @version $Revision: 1.1.1.1 $
*/
public class ReliableReconnectTest extends TestSupport {
private static final int RECEIVE_TIMEOUT = 10000;
protected static final int MESSAGE_COUNT = 100;
protected static final String DEFAULT_BROKER_URL = "vm://localhost";
private IdGenerator idGen = new IdGenerator();
protected int deliveryMode = DeliveryMode.PERSISTENT;
protected String consumerClientId;
protected Destination destination;
protected AtomicBoolean closeBroker = new AtomicBoolean(false);
protected AtomicInteger messagesReceived = new AtomicInteger(0);
protected BrokerService broker;
protected int firstBatch = MESSAGE_COUNT/10;
public ReliableReconnectTest() {
}
public ReliableReconnectTest(String n) {
super(n);
}
protected void setUp() throws Exception {
consumerClientId = idGen.generateId();
super.setUp();
topic = true;
destination = createDestination(getClass().getName());
}
public ActiveMQConnectionFactory getConnectionFactory() throws Exception {
String url = "failover://" + DEFAULT_BROKER_URL;
return new ActiveMQConnectionFactory(url);
}
protected void startBroker() throws JMSException {
try {
broker = BrokerFactory.createBroker(new URI("broker://()/localhost"));
broker.addConnector(DEFAULT_BROKER_URL);
broker.start();
} catch (Exception e) {
e.printStackTrace();
}
}
protected Connection createConsumerConnection() throws Exception {
Connection consumerConnection = getConnectionFactory().createConnection();
consumerConnection.setClientID(consumerClientId);
consumerConnection.start();
return consumerConnection;
}
protected MessageConsumer createConsumer(Connection con) throws Exception {
Session s = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
return s.createDurableSubscriber((Topic) destination, "TestFred");
}
protected void spawnConsumer() {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
Connection consumerConnection = createConsumerConnection();
MessageConsumer consumer = createConsumer(consumerConnection);
//consume some messages
for (int i = 0;i < firstBatch;i++) {
Message msg = consumer.receive(RECEIVE_TIMEOUT);
if (msg != null) {
//log.info("GOT: " + msg);
messagesReceived.incrementAndGet();
}
}
synchronized (closeBroker) {
closeBroker.set(true);
closeBroker.notify();
}
Thread.sleep(2000);
for (int i = firstBatch;i < MESSAGE_COUNT;i++) {
Message msg = consumer.receive(RECEIVE_TIMEOUT);
//log.info("GOT: " + msg);
if (msg != null) {
messagesReceived.incrementAndGet();
}
}
consumerConnection.close();
synchronized (messagesReceived) {
messagesReceived.notify();
}
}
catch (Throwable e) {
e.printStackTrace();
}
}
});
thread.start();
}
public void testReconnect() throws Exception {
startBroker();
//register an interest as a durable subscriber
Connection consumerConnection = createConsumerConnection();
createConsumer(consumerConnection);
consumerConnection.close();
//send some messages ...
Connection connection = createConnection();
connection.setClientID(idGen.generateId());
connection.start();
Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = producerSession.createProducer(destination);
TextMessage msg = producerSession.createTextMessage();
for (int i = 0;i < MESSAGE_COUNT;i++) {
msg.setText("msg: " + i);
producer.send(msg);
}
connection.close();
spawnConsumer();
synchronized (closeBroker) {
if (!closeBroker.get()) {
closeBroker.wait();
}
}
System.err.println("Stopping broker");
broker.stop();
startBroker();
System.err.println("Started Broker again");
synchronized (messagesReceived) {
if (messagesReceived.get() < MESSAGE_COUNT) {
messagesReceived.wait(60000);
}
}
//assertTrue(messagesReceived.get() == MESSAGE_COUNT);
int count = messagesReceived.get();
assertTrue("Not enough messages received: " + count, count > firstBatch);
}
}

View File

@ -0,0 +1,78 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.TransportConnector;
import javax.jms.JMSException;
import java.net.URI;
/**
* @author Oliver Belikan
* @version $Revision: 1.1.1.1 $
*/
public class StartAndStopBrokerTest extends TestCase {
public void testStartupShutdown() throws Exception {
// This systemproperty is used if we dont want to
// have persistence messages as a default
System.setProperty("activemq.persistenceAdapter",
"org.apache.activemq.store.vm.VMPersistenceAdapter");
// configuration of container and all protocolls
BrokerService broker = createBroker();
// start a client
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:9100");
factory.createConnection();
// stop activemq broker
broker.stop();
// start activemq broker again
broker = createBroker();
// start a client again
factory = new ActiveMQConnectionFactory("tcp://localhost:9100");
factory.createConnection();
// stop activemq broker
broker.stop();
}
protected BrokerService createBroker() throws JMSException {
BrokerService broker = null;
try {
broker = BrokerFactory.createBroker(new URI("broker://()/localhost"));
broker.setBrokerName("DefaultBroker");
broker.addConnector("tcp://localhost:9100");
broker.setUseShutdownHook(false);
broker.start();
} catch (Exception e) {
e.printStackTrace();
}
return broker;
}
}

View File

@ -0,0 +1,105 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.test.TestSupport;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicSubscriber;
/**
* @author Paul Smith
* @version $Revision: 1.1.1.1 $
*/
public class SubscribeClosePublishThenConsumeTest extends TestSupport {
public void testDurableTopic() throws Exception {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://locahost");
String topicName = "TestTopic";
String clientID = getName();
String subscriberName = "MySubscriber:"+System.currentTimeMillis();
Connection connection = connectionFactory.createConnection();
connection.setClientID(clientID);
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic(topicName);
// this should register a durable subscriber, we then close it to
// test that we get messages from the producer later on
TopicSubscriber subscriber = session.createDurableSubscriber(topic, subscriberName);
connection.start();
topic = null;
subscriber.close();
subscriber = null;
session.close();
session = null;
// Create the new connection before closing to avoid the broker shutting down.
// now create a new Connection, Session & Producer, send some messages & then close
Connection t = connectionFactory.createConnection();
connection.close();
connection = t;
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
topic = session.createTopic(topicName);
MessageProducer producer = session.createProducer(topic);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
TextMessage textMessage = session.createTextMessage("Hello World");
producer.send(textMessage);
textMessage = null;
topic = null;
session.close();
session = null;
// Now (re)register the Durable subscriber, setup a listener and wait for messages that should
// have been published by the previous producer
t = connectionFactory.createConnection();
connection.close();
connection = t;
connection.setClientID(clientID);
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
topic = session.createTopic(topicName);
subscriber = session.createDurableSubscriber(topic, subscriberName);
connection.start();
log.info("Started connection - now about to try receive the textMessage");
long time = System.currentTimeMillis();
Message message = subscriber.receive(15000L);
long elapsed = System.currentTimeMillis() - time;
log.info("Waited for: " + elapsed + " millis");
assertNotNull("Should have received the message we published by now", message);
assertTrue("should be text textMessage", message instanceof TextMessage);
textMessage = (TextMessage) message;
assertEquals("Hello World", textMessage.getText());
}
}

View File

@ -0,0 +1,149 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;
import junit.framework.TestCase;
/**
* Useful base class for unit test cases
*
* @version $Revision: 1.1.1.1 $
*/
public class TestSupport extends TestCase {
protected Log log = LogFactory.getLog(getClass());
protected ActiveMQConnectionFactory connectionFactory;
protected boolean topic = true;
public TestSupport() {
super();
}
public TestSupport(String name) {
super(name);
}
protected ActiveMQMessage createMessage() {
return new ActiveMQMessage();
}
protected Destination createDestination(String subject) {
if (topic) {
return new ActiveMQTopic(subject);
}
else {
return new ActiveMQQueue(subject);
}
}
protected void assertTextMessagesEqual(Message[] firstSet, Message[] secondSet) throws JMSException {
assertTextMessagesEqual("", firstSet, secondSet);
}
/**
* @param messsage
* @param firstSet
* @param secondSet
*/
protected void assertTextMessagesEqual(String messsage, Message[] firstSet, Message[] secondSet) throws JMSException {
assertEquals("Message count does not match: " + messsage, firstSet.length, secondSet.length);
for (int i = 0; i < secondSet.length; i++) {
TextMessage m1 = (TextMessage) firstSet[i];
TextMessage m2 = (TextMessage) secondSet[i];
assertTextMessageEqual("Message " + (i + 1) + " did not match : ", m1,m2);
}
}
protected void assertEquals(TextMessage m1, TextMessage m2) throws JMSException {
assertEquals("", m1, m2);
}
/**
* @param message
* @param firstSet
* @param secondSet
*/
protected void assertTextMessageEqual(String message, TextMessage m1, TextMessage m2) throws JMSException {
assertFalse(message + ": expected {" + m1 + "}, but was {" + m2 + "}", m1 == null ^ m2 == null);
if( m1 == null )
return;
assertEquals(message, m1.getText(), m2.getText());
}
protected void assertEquals(Message m1, Message m2) throws JMSException {
assertEquals("", m1, m2);
}
/**
* @param message
* @param firstSet
* @param secondSet
*/
protected void assertEquals(String message, Message m1, Message m2) throws JMSException {
assertFalse(message + ": expected {" + m1 + "}, but was {" + m2 + "}", m1 == null ^ m2 == null);
if( m1 == null )
return;
assertTrue(message + ": expected {" + m1 + "}, but was {" + m2 + "}", m1.getClass()==m2.getClass());
if( m1 instanceof TextMessage ) {
assertTextMessageEqual(message, (TextMessage)m1, (TextMessage)m2);
} else {
assertEquals(message, m1, m2);
}
}
protected ActiveMQConnectionFactory createConnectionFactory() throws Exception {
return new ActiveMQConnectionFactory("vm://localhost");
}
/**
* Factory method to create a new connection
*/
protected Connection createConnection() throws Exception {
return getConnectionFactory().createConnection();
}
public ActiveMQConnectionFactory getConnectionFactory() throws Exception {
if (connectionFactory == null) {
connectionFactory = createConnectionFactory();
assertTrue("Should have created a connection factory!", connectionFactory != null);
}
return connectionFactory;
}
protected String getConsumerSubject() {
return getSubject();
}
protected String getProducerSubject() {
return getSubject();
}
protected String getSubject() {
return getClass().getName() + "." + getName();
}
}

View File

@ -0,0 +1,196 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.JmsMultipleBrokersTestSupport;
import org.apache.activemq.util.MessageIdList;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import java.net.URI;
/**
* @version $Revision: 1.1.1.1 $
*/
public class ThreeBrokerQueueNetworkTest extends JmsMultipleBrokersTestSupport {
protected static final int MESSAGE_COUNT = 100;
/**
* BrokerA -> BrokerB -> BrokerC
*/
public void test_AB_BC_BrokerNetwork() throws Exception {
// Setup broker networks
bridgeBrokers("BrokerA", "BrokerB");
bridgeBrokers("BrokerB", "BrokerC");
startAllBrokers();
// Setup destination
Destination dest = createDestination("TEST.FOO", false);
// Setup consumers
MessageConsumer clientC = createConsumer("BrokerC", dest);
// Send messages
sendMessages("BrokerA", dest, MESSAGE_COUNT);
// Let's try to wait for any messages. Should be none.
Thread.sleep(1000);
// Get message count
MessageIdList msgsC = getConsumerMessages("BrokerC", clientC);
assertEquals(0, msgsC.getMessageCount());
}
/**
* BrokerA <- BrokerB -> BrokerC
*/
public void test_BA_BC_BrokerNetwork() throws Exception {
// Setup broker networks
bridgeBrokers("BrokerB", "BrokerA");
bridgeBrokers("BrokerB", "BrokerC");
startAllBrokers();
// Setup destination
Destination dest = createDestination("TEST.FOO", false);
// Setup consumers
MessageConsumer clientA = createConsumer("BrokerA", dest);
MessageConsumer clientC = createConsumer("BrokerC", dest);
Thread.sleep(2000); //et subscriptions get propagated
// Send messages
sendMessages("BrokerB", dest, MESSAGE_COUNT);
// Let's try to wait for any messages.
Thread.sleep(1000);
// Get message count
MessageIdList msgsA = getConsumerMessages("BrokerA", clientA);
MessageIdList msgsC = getConsumerMessages("BrokerC", clientC);
// Total received should be 100
assertEquals(MESSAGE_COUNT, msgsA.getMessageCount() + msgsC.getMessageCount());
}
/**
* BrokerA -> BrokerB <- BrokerC
*/
public void test_AB_CB_BrokerNetwork() throws Exception {
// Setup broker networks
bridgeBrokers("BrokerA", "BrokerB");
bridgeBrokers("BrokerC", "BrokerB");
startAllBrokers();
// Setup destination
Destination dest = createDestination("TEST.FOO", false);
// Setup consumers
MessageConsumer clientB = createConsumer("BrokerB", dest);
// Send messages
sendMessages("BrokerA", dest, MESSAGE_COUNT);
sendMessages("BrokerC", dest, MESSAGE_COUNT);
// Get message count
MessageIdList msgsB = getConsumerMessages("BrokerB", clientB);
msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 2);
assertEquals(MESSAGE_COUNT * 2, msgsB.getMessageCount());
}
/**
* BrokerA <-> BrokerB <-> BrokerC
*/
public void testAllConnectedBrokerNetwork() throws Exception {
// Setup broker networks
bridgeBrokers("BrokerA", "BrokerB");
bridgeBrokers("BrokerB", "BrokerA");
bridgeBrokers("BrokerB", "BrokerC");
bridgeBrokers("BrokerC", "BrokerB");
bridgeBrokers("BrokerA", "BrokerC");
bridgeBrokers("BrokerC", "BrokerA");
startAllBrokers();
// Setup destination
Destination dest = createDestination("TEST.FOO", false);
// Setup consumers
MessageConsumer clientA = createConsumer("BrokerA", dest);
MessageConsumer clientB = createConsumer("BrokerB", dest);
MessageConsumer clientC = createConsumer("BrokerC", dest);
// Send messages
sendMessages("BrokerA", dest, MESSAGE_COUNT);
sendMessages("BrokerB", dest, MESSAGE_COUNT);
sendMessages("BrokerC", dest, MESSAGE_COUNT);
// Let's try to wait for any messages.
Thread.sleep(1000);
// Get message count
MessageIdList msgsA = getConsumerMessages("BrokerA", clientA);
MessageIdList msgsB = getConsumerMessages("BrokerB", clientB);
MessageIdList msgsC = getConsumerMessages("BrokerC", clientC);
assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount() + msgsB.getMessageCount() + msgsC.getMessageCount());
}
/**
* BrokerA <-> BrokerB <-> BrokerC
*/
public void testAllConnectedUsingMulticast() throws Exception {
// Setup broker networks
bridgeAllBrokers();
startAllBrokers();
// Setup destination
Destination dest = createDestination("TEST.FOO", false);
// Setup consumers
MessageConsumer clientA = createConsumer("BrokerA", dest);
MessageConsumer clientB = createConsumer("BrokerB", dest);
MessageConsumer clientC = createConsumer("BrokerC", dest);
// Send messages
sendMessages("BrokerA", dest, MESSAGE_COUNT);
sendMessages("BrokerB", dest, MESSAGE_COUNT);
sendMessages("BrokerC", dest, MESSAGE_COUNT);
// Let's try to wait for any messages.
Thread.sleep(1000);
// Get message count
MessageIdList msgsA = getConsumerMessages("BrokerA", clientA);
MessageIdList msgsB = getConsumerMessages("BrokerB", clientB);
MessageIdList msgsC = getConsumerMessages("BrokerC", clientC);
assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount() + msgsB.getMessageCount() + msgsC.getMessageCount());
}
public void setUp() throws Exception {
super.setAutoFail(true);
super.setUp();
createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false"));
createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false"));
createBroker(new URI("broker:(tcp://localhost:61618)/BrokerC?persistent=false&useJmx=false"));
}
}

View File

@ -0,0 +1,66 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.network.DemandForwardingBridge;
import org.apache.activemq.transport.TransportFactory;
import java.util.List;
import java.util.ArrayList;
import java.net.URI;
/**
* @version $Revision: 1.1.1.1 $
*/
public class ThreeBrokerQueueNetworkUsingTcpTest extends ThreeBrokerQueueNetworkTest {
protected List bridges;
protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception {
List remoteTransports = remoteBroker.getTransportConnectors();
List localTransports = localBroker.getTransportConnectors();
URI remoteURI, localURI;
if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) {
remoteURI = ((TransportConnector)remoteTransports.get(0)).getConnectUri();
localURI = ((TransportConnector)localTransports.get(0)).getConnectUri();
// Ensure that we are connecting using tcp
if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) {
DemandForwardingBridge bridge = new DemandForwardingBridge(TransportFactory.connect(localURI),
TransportFactory.connect(remoteURI));
bridge.setLocalBrokerName(localBroker.getBrokerName());
bridges.add(bridge);
bridge.start();
} else {
throw new Exception("Remote broker or local broker is not using tcp connectors");
}
} else {
throw new Exception("Remote broker or local broker has no registered connectors.");
}
MAX_SETUP_TIME = 2000;
}
public void setUp() throws Exception {
super.setUp();
bridges = new ArrayList();
}
}

View File

@ -0,0 +1,95 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.apache.activemq.usecases;
import java.net.URI;
import java.util.Iterator;
import javax.jms.Connection;
import javax.jms.Session;
import javax.jms.TemporaryQueue;
import org.apache.activemq.JmsMultipleBrokersTestSupport;
/**
* @version $Revision: 1.1.1.1 $
*/
public class ThreeBrokerTempQueueNetworkTest extends JmsMultipleBrokersTestSupport{
protected static final int MESSAGE_COUNT=100;
/**
* BrokerA -> BrokerB -> BrokerC
*/
public void testTempQueueCleanup() throws Exception{
// Setup broker networks
bridgeBrokers("BrokerA","BrokerB",false,2);
bridgeBrokers("BrokerB","BrokerC",false,2);
startAllBrokers();
BrokerItem brokerItem=(BrokerItem) brokers.get("BrokerC");
Connection conn=brokerItem.createConnection();
conn.start();
Session sess=conn.createSession(false,Session.AUTO_ACKNOWLEDGE);
TemporaryQueue tempQ=sess.createTemporaryQueue();
Thread.sleep(5000);
for(Iterator i=brokers.values().iterator();i.hasNext();){
BrokerItem bi=(BrokerItem) i.next();
assertEquals("No queues on broker "+bi.broker.getBrokerName(),1,bi.broker.getAdminView()
.getTemporaryQueues().length);
}
tempQ.delete();
Thread.sleep(2000);
for(Iterator i=brokers.values().iterator();i.hasNext();){
BrokerItem bi=(BrokerItem) i.next();
assertEquals("Temp queue left behind on broker "+bi.broker.getBrokerName(),0,bi.broker.getAdminView()
.getTemporaryQueues().length);
}
}
// this actually uses 4 brokers ...
public void testTempQueueRecovery() throws Exception{
// Setup broker networks
bridgeBrokers("BrokerA","BrokerB",false,3);
bridgeBrokers("BrokerB","BrokerC",false,3);
startAllBrokers();
BrokerItem brokerItem=(BrokerItem) brokers.get("BrokerC");
Connection conn=brokerItem.createConnection();
conn.start();
Session sess=conn.createSession(false,Session.AUTO_ACKNOWLEDGE);
TemporaryQueue tempQ=sess.createTemporaryQueue();
Thread.sleep(5000);
for(Iterator i=brokers.values().iterator();i.hasNext();){
BrokerItem bi=(BrokerItem) i.next();
assertEquals("No queues on broker "+bi.broker.getBrokerName(),1,bi.broker.getAdminView()
.getTemporaryQueues().length);
}
createBroker(new URI("broker:(tcp://localhost:61619)/BrokerD?persistent=false&useJmx=true"));
bridgeBrokers("BrokerD","BrokerA",false,3);
BrokerItem newBroker=(BrokerItem) brokers.get("BrokerD");
newBroker.broker.start();
Thread.sleep(1000);
assertEquals("No queues on broker D",1,newBroker.broker.getAdminView().getTemporaryQueues().length);
tempQ.delete();
Thread.sleep(2000);
for(Iterator i=brokers.values().iterator();i.hasNext();){
BrokerItem bi=(BrokerItem) i.next();
assertEquals("Temp queue left behind on broker "+bi.broker.getBrokerName(),0,bi.broker.getAdminView()
.getTemporaryQueues().length);
}
}
public void setUp() throws Exception{
super.setAutoFail(true);
super.setUp();
createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=true"));
createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=true"));
createBroker(new URI("broker:(tcp://localhost:61618)/BrokerC?persistent=false&useJmx=true"));
}
}

View File

@ -0,0 +1,239 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.util.MessageIdList;
import org.apache.activemq.JmsMultipleBrokersTestSupport;
import javax.jms.MessageConsumer;
import javax.jms.Destination;
import java.net.URI;
/**
* @version $Revision: 1.1.1.1 $
*/
public class ThreeBrokerTopicNetworkTest extends JmsMultipleBrokersTestSupport {
protected static final int MESSAGE_COUNT = 100;
/**
* BrokerA -> BrokerB -> BrokerC
*/
public void test_AB_BC_BrokerNetwork() throws Exception {
// Setup broker networks
bridgeBrokers("BrokerA", "BrokerB");
bridgeBrokers("BrokerB", "BrokerC");
startAllBrokers();
// Setup destination
Destination dest = createDestination("TEST.FOO", true);
// Setup consumers
MessageConsumer clientA = createConsumer("BrokerA", dest);
MessageConsumer clientB = createConsumer("BrokerB", dest);
MessageConsumer clientC = createConsumer("BrokerC", dest);
// let consumers propogate around the network
Thread.sleep(2000);
// Send messages
sendMessages("BrokerA", dest, MESSAGE_COUNT);
sendMessages("BrokerB", dest, MESSAGE_COUNT);
sendMessages("BrokerC", dest, MESSAGE_COUNT);
// Get message count
MessageIdList msgsA = getConsumerMessages("BrokerA", clientA);
MessageIdList msgsB = getConsumerMessages("BrokerB", clientB);
MessageIdList msgsC = getConsumerMessages("BrokerC", clientC);
msgsA.waitForMessagesToArrive(MESSAGE_COUNT);
msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 2);
msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 2);
assertEquals(MESSAGE_COUNT, msgsA.getMessageCount());
assertEquals(MESSAGE_COUNT * 2, msgsB.getMessageCount());
assertEquals(MESSAGE_COUNT * 2, msgsC.getMessageCount());
}
/**
* BrokerA <- BrokerB -> BrokerC
*/
public void test_BA_BC_BrokerNetwork() throws Exception {
// Setup broker networks
bridgeBrokers("BrokerB", "BrokerA");
bridgeBrokers("BrokerB", "BrokerC");
startAllBrokers();
// Setup destination
Destination dest = createDestination("TEST.FOO", true);
// Setup consumers
MessageConsumer clientA = createConsumer("BrokerA", dest);
MessageConsumer clientB = createConsumer("BrokerB", dest);
MessageConsumer clientC = createConsumer("BrokerC", dest);
// let consumers propogate around the network
Thread.sleep(2000);
// Send messages
sendMessages("BrokerA", dest, MESSAGE_COUNT);
sendMessages("BrokerB", dest, MESSAGE_COUNT);
sendMessages("BrokerC", dest, MESSAGE_COUNT);
// Get message count
MessageIdList msgsA = getConsumerMessages("BrokerA", clientA);
MessageIdList msgsB = getConsumerMessages("BrokerB", clientB);
MessageIdList msgsC = getConsumerMessages("BrokerC", clientC);
msgsA.waitForMessagesToArrive(MESSAGE_COUNT * 2);
msgsB.waitForMessagesToArrive(MESSAGE_COUNT);
msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 2);
assertEquals(MESSAGE_COUNT * 2, msgsA.getMessageCount());
assertEquals(MESSAGE_COUNT, msgsB.getMessageCount());
assertEquals(MESSAGE_COUNT * 2, msgsC.getMessageCount());
}
/**
* BrokerA -> BrokerB <- BrokerC
*/
public void test_AB_CB_BrokerNetwork() throws Exception {
// Setup broker networks
bridgeBrokers("BrokerA", "BrokerB");
bridgeBrokers("BrokerC", "BrokerB");
startAllBrokers();
// Setup destination
Destination dest = createDestination("TEST.FOO", true);
// Setup consumers
MessageConsumer clientA = createConsumer("BrokerA", dest);
MessageConsumer clientB = createConsumer("BrokerB", dest);
MessageConsumer clientC = createConsumer("BrokerC", dest);
// let consumers propogate around the network
Thread.sleep(2000);
// Send messages
sendMessages("BrokerA", dest, MESSAGE_COUNT);
sendMessages("BrokerB", dest, MESSAGE_COUNT);
sendMessages("BrokerC", dest, MESSAGE_COUNT);
// Get message count
MessageIdList msgsA = getConsumerMessages("BrokerA", clientA);
MessageIdList msgsB = getConsumerMessages("BrokerB", clientB);
MessageIdList msgsC = getConsumerMessages("BrokerC", clientC);
msgsA.waitForMessagesToArrive(MESSAGE_COUNT);
msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3);
msgsC.waitForMessagesToArrive(MESSAGE_COUNT);
assertEquals(MESSAGE_COUNT, msgsA.getMessageCount());
assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount());
assertEquals(MESSAGE_COUNT, msgsC.getMessageCount());
}
/**
* BrokerA <-> BrokerB <-> BrokerC
*/
public void testAllConnectedBrokerNetwork() throws Exception {
// Setup broker networks
bridgeBrokers("BrokerA", "BrokerB");
bridgeBrokers("BrokerB", "BrokerA");
bridgeBrokers("BrokerB", "BrokerC");
bridgeBrokers("BrokerC", "BrokerB");
bridgeBrokers("BrokerA", "BrokerC");
bridgeBrokers("BrokerC", "BrokerA");
startAllBrokers();
// Setup destination
Destination dest = createDestination("TEST.FOO", true);
// Setup consumers
MessageConsumer clientA = createConsumer("BrokerA", dest);
MessageConsumer clientB = createConsumer("BrokerB", dest);
MessageConsumer clientC = createConsumer("BrokerC", dest);
//let consumers propogate around the network
Thread.sleep(2000);
// Send messages
sendMessages("BrokerA", dest, MESSAGE_COUNT);
sendMessages("BrokerB", dest, MESSAGE_COUNT);
sendMessages("BrokerC", dest, MESSAGE_COUNT);
// Get message count
MessageIdList msgsA = getConsumerMessages("BrokerA", clientA);
MessageIdList msgsB = getConsumerMessages("BrokerB", clientB);
MessageIdList msgsC = getConsumerMessages("BrokerC", clientC);
msgsA.waitForMessagesToArrive(MESSAGE_COUNT * 3);
msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3);
msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 3);
assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount());
assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount());
assertEquals(MESSAGE_COUNT * 3, msgsC.getMessageCount());
}
/**
* BrokerA <-> BrokerB <-> BrokerC
*/
public void testAllConnectedUsingMulticast() throws Exception {
// Setup broker networks
bridgeAllBrokers();
startAllBrokers();
// Setup destination
Destination dest = createDestination("TEST.FOO", true);
// Setup consumers
MessageConsumer clientA = createConsumer("BrokerA", dest);
MessageConsumer clientB = createConsumer("BrokerB", dest);
MessageConsumer clientC = createConsumer("BrokerC", dest);
//let consumers propogate around the network
Thread.sleep(2000);
// Send messages
sendMessages("BrokerA", dest, MESSAGE_COUNT);
sendMessages("BrokerB", dest, MESSAGE_COUNT);
sendMessages("BrokerC", dest, MESSAGE_COUNT);
// Get message count
MessageIdList msgsA = getConsumerMessages("BrokerA", clientA);
MessageIdList msgsB = getConsumerMessages("BrokerB", clientB);
MessageIdList msgsC = getConsumerMessages("BrokerC", clientC);
msgsA.waitForMessagesToArrive(MESSAGE_COUNT * 3);
msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3);
msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 3);
assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount());
assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount());
assertEquals(MESSAGE_COUNT * 3, msgsC.getMessageCount());
}
public void setUp() throws Exception {
super.setAutoFail(true);
super.setUp();
createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false"));
createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false"));
createBroker(new URI("broker:(tcp://localhost:61618)/BrokerC?persistent=false&useJmx=false"));
}
}

View File

@ -0,0 +1,66 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.network.DemandForwardingBridge;
import org.apache.activemq.transport.TransportFactory;
import java.util.List;
import java.util.ArrayList;
import java.net.URI;
/**
* @version $Revision: 1.1.1.1 $
*/
public class ThreeBrokerTopicNetworkUsingTcpTest extends ThreeBrokerTopicNetworkTest {
protected List bridges;
protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception {
List remoteTransports = remoteBroker.getTransportConnectors();
List localTransports = localBroker.getTransportConnectors();
URI remoteURI, localURI;
if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) {
remoteURI = ((TransportConnector)remoteTransports.get(0)).getConnectUri();
localURI = ((TransportConnector)localTransports.get(0)).getConnectUri();
// Ensure that we are connecting using tcp
if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) {
DemandForwardingBridge bridge = new DemandForwardingBridge(TransportFactory.connect(localURI),
TransportFactory.connect(remoteURI));
bridge.setLocalBrokerName(localBroker.getBrokerName());
bridges.add(bridge);
bridge.start();
} else {
throw new Exception("Remote broker or local broker is not using tcp connectors");
}
} else {
throw new Exception("Remote broker or local broker has no registered connectors.");
}
MAX_SETUP_TIME = 2000;
}
public void setUp() throws Exception {
super.setUp();
bridges = new ArrayList();
}
}

View File

@ -0,0 +1,223 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import org.apache.activemq.test.TestSupport;
import org.apache.activemq.util.IdGenerator;
/**
* @version $Revision: 1.1.1.1 $
*/
public class TopicRedeliverTest extends TestSupport {
private static final int RECEIVE_TIMEOUT = 10000;
private IdGenerator idGen = new IdGenerator();
protected int deliveryMode = DeliveryMode.PERSISTENT;
public TopicRedeliverTest(){
}
public TopicRedeliverTest(String n){
super(n);
}
protected void setup() throws Exception{
super.setUp();
topic = true;
}
/**
* test messages are acknowledged and recovered properly
* @throws Exception
*/
public void testClientAcknowledge() throws Exception {
Destination destination = createDestination(getClass().getName());
Connection connection = createConnection();
connection.setClientID(idGen.generateId());
connection.start();
Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = consumerSession.createConsumer(destination);
Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = producerSession.createProducer(destination);
producer.setDeliveryMode(deliveryMode);
//send some messages
TextMessage sent1 = producerSession.createTextMessage();
sent1.setText("msg1");
producer.send(sent1);
TextMessage sent2 = producerSession.createTextMessage();
sent1.setText("msg2");
producer.send(sent2);
TextMessage sent3 = producerSession.createTextMessage();
sent1.setText("msg3");
producer.send(sent3);
Message rec1 = consumer.receive(RECEIVE_TIMEOUT);
Message rec2 = consumer.receive(RECEIVE_TIMEOUT);
Message rec3 = consumer.receive(RECEIVE_TIMEOUT);
//ack rec2
rec2.acknowledge();
TextMessage sent4 = producerSession.createTextMessage();
sent4.setText("msg4");
producer.send(sent4);
Message rec4 = consumer.receive(RECEIVE_TIMEOUT);
assertTrue(rec4.equals(sent4));
consumerSession.recover();
rec4 = consumer.receive(RECEIVE_TIMEOUT);
assertTrue(rec4.equals(sent4));
assertTrue(rec4.getJMSRedelivered());
rec4.acknowledge();
connection.close();
}
/**
* Test redelivered flag is set on rollbacked transactions
* @throws Exception
*/
public void testRedilveredFlagSetOnRollback() throws Exception {
Destination destination = createDestination(getClass().getName());
Connection connection = createConnection();
connection.setClientID(idGen.generateId());
connection.start();
Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = null;
if (topic){
consumer = consumerSession.createDurableSubscriber((Topic)destination, "TESTRED");
}else{
consumer = consumerSession.createConsumer(destination);
}
Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = producerSession.createProducer(destination);
producer.setDeliveryMode(deliveryMode);
TextMessage sentMsg = producerSession.createTextMessage();
sentMsg.setText("msg1");
producer.send(sentMsg);
producerSession.commit();
Message recMsg = consumer.receive(RECEIVE_TIMEOUT);
assertTrue(recMsg.getJMSRedelivered() == false);
recMsg = consumer.receive(RECEIVE_TIMEOUT);
consumerSession.rollback();
recMsg = consumer.receive(RECEIVE_TIMEOUT);
assertTrue(recMsg.getJMSRedelivered());
consumerSession.commit();
assertTrue(recMsg.equals(sentMsg));
assertTrue(recMsg.getJMSRedelivered());
connection.close();
}
/**
* Check a session is rollbacked on a Session close();
* @throws Exception
*/
public void XtestTransactionRollbackOnSessionClose() throws Exception {
Destination destination = createDestination(getClass().getName());
Connection connection = createConnection();
connection.setClientID(idGen.generateId());
connection.start();
Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = null;
if (topic){
consumer = consumerSession.createDurableSubscriber((Topic)destination, "TESTRED");
}else{
consumer = consumerSession.createConsumer(destination);
}
Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = producerSession.createProducer(destination);
producer.setDeliveryMode(deliveryMode);
TextMessage sentMsg = producerSession.createTextMessage();
sentMsg.setText("msg1");
producer.send(sentMsg);
producerSession.commit();
Message recMsg = consumer.receive(RECEIVE_TIMEOUT);
assertTrue(recMsg.getJMSRedelivered() == false);
consumerSession.close();
consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
consumer = consumerSession.createConsumer(destination);
recMsg = consumer.receive(RECEIVE_TIMEOUT);
consumerSession.commit();
assertTrue(recMsg.equals(sentMsg));
connection.close();
}
/**
* check messages are actuallly sent on a tx rollback
* @throws Exception
*/
public void testTransactionRollbackOnSend() throws Exception {
Destination destination = createDestination(getClass().getName());
Connection connection = createConnection();
connection.setClientID(idGen.generateId());
connection.start();
Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = consumerSession.createConsumer(destination);
Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = producerSession.createProducer(destination);
producer.setDeliveryMode(deliveryMode);
TextMessage sentMsg = producerSession.createTextMessage();
sentMsg.setText("msg1");
producer.send(sentMsg);
producerSession.commit();
Message recMsg = consumer.receive(RECEIVE_TIMEOUT);
consumerSession.commit();
assertTrue(recMsg.equals(sentMsg));
sentMsg = producerSession.createTextMessage();
sentMsg.setText("msg2");
producer.send(sentMsg);
producerSession.rollback();
sentMsg = producerSession.createTextMessage();
sentMsg.setText("msg3");
producer.send(sentMsg);
producerSession.commit();
recMsg = consumer.receive(RECEIVE_TIMEOUT);
assertTrue(recMsg.equals(sentMsg));
consumerSession.commit();
connection.close();
}
}

View File

@ -0,0 +1,166 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import java.util.ArrayList;
import java.util.List;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;
/**
* Test case for AMQ-268
*
* @author Paul Smith
* @version $Revision: 1.1 $
*/
public final class TransactionRollbackOrderTest extends TestCase {
private static final Log log = LogFactory.getLog(TransactionRollbackOrderTest.class);
private volatile String receivedText;
private Session producerSession;
private Session consumerSession;
private Destination queue;
private MessageProducer producer;
private MessageConsumer consumer;
private Connection connection;
private CountDownLatch latch = new CountDownLatch(1);
private int NUM_MESSAGES = 5;
private List msgSent = new ArrayList();
private List msgCommitted = new ArrayList();
private List msgRolledBack = new ArrayList();
private List msgRedelivered = new ArrayList();
public void testTransaction() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
connection = factory.createConnection();
queue = new ActiveMQQueue(getClass().getName() + "." + getName());
producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
consumerSession = connection.createSession(true, 0);
producer = producerSession.createProducer(queue);
consumer = consumerSession.createConsumer(queue);
consumer.setMessageListener(new MessageListener() {
int msgCount = 0;
int msgCommittedCount = 0;
public void onMessage(Message m) {
try {
msgCount++;
TextMessage tm = (TextMessage) m;
receivedText = tm.getText();
if (tm.getJMSRedelivered()) {
msgRedelivered.add(receivedText);
}
log.info("consumer received message: " + receivedText + (tm.getJMSRedelivered() ? " ** Redelivered **" : ""));
if (msgCount == 3) {
msgRolledBack.add(receivedText);
consumerSession.rollback();
log.info("[msg: " + receivedText + "] ** rolled back **");
}
else {
msgCommittedCount++;
msgCommitted.add(receivedText);
consumerSession.commit();
log.info("[msg: " + receivedText + "] committed transaction ");
}
if (msgCommittedCount == NUM_MESSAGES) {
latch.countDown();
}
}
catch (JMSException e) {
try {
consumerSession.rollback();
log.info("rolled back transaction");
}
catch (JMSException e1) {
log.info(e1);
e1.printStackTrace();
}
log.info(e);
e.printStackTrace();
}
}
});
connection.start();
TextMessage tm = null;
try {
for (int i = 1; i <= NUM_MESSAGES; i++) {
tm = producerSession.createTextMessage();
tm.setText("Hello " + i);
msgSent.add(tm.getText());
producer.send(tm);
log.info("producer sent message: " + tm.getText());
}
}
catch (JMSException e) {
e.printStackTrace();
}
log.info("Waiting for latch");
latch.await();
assertEquals(1, msgRolledBack.size());
assertEquals(1, msgRedelivered.size());
log.info("msg RolledBack = " + msgRolledBack.get(0));
log.info("msg Redelivered = " + msgRedelivered.get(0));
assertEquals(msgRolledBack.get(0), msgRedelivered.get(0));
assertEquals(NUM_MESSAGES, msgSent.size());
assertEquals(NUM_MESSAGES, msgCommitted.size());
assertEquals(msgSent, msgCommitted);
}
protected void tearDown() throws Exception {
if (connection != null) {
log.info("Closing the connection");
connection.close();
}
super.tearDown();
}
}

View File

@ -0,0 +1,123 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import java.util.Date;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;
/**
* @author pragmasoft
* @version $Revision: 1.1.1.1 $
*/
public final class TransactionTest extends TestCase {
private static final Log log = LogFactory.getLog(TransactionTest.class);
private volatile String receivedText;
private Session producerSession;
private Session consumerSession;
private Destination queue;
private MessageProducer producer;
private MessageConsumer consumer;
private Connection connection;
private CountDownLatch latch = new CountDownLatch(1);
public void testTransaction() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost");
connection = factory.createConnection();
queue = new ActiveMQQueue(getClass().getName() + "." + getName());
producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
consumerSession = connection.createSession(true, 0);
producer = producerSession.createProducer(queue);
consumer = consumerSession.createConsumer(queue);
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message m) {
try {
TextMessage tm = (TextMessage) m;
receivedText = tm.getText();
latch.countDown();
log.info("consumer received message :" + receivedText);
consumerSession.commit();
log.info("committed transaction");
}
catch (JMSException e) {
try {
consumerSession.rollback();
log.info("rolled back transaction");
}
catch (JMSException e1) {
log.info(e1);
e1.printStackTrace();
}
log.info(e);
e.printStackTrace();
}
}
});
connection.start();
TextMessage tm = null;
try {
tm = producerSession.createTextMessage();
tm.setText("Hello, " + new Date());
producer.send(tm);
log.info("producer sent message :" + tm.getText());
}
catch (JMSException e) {
e.printStackTrace();
}
log.info("Waiting for latch");
latch.await();
log.info("test completed, destination=" + receivedText);
}
protected void tearDown() throws Exception {
if (connection != null) {
connection.close();
}
super.tearDown();
}
}

View File

@ -0,0 +1,33 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import javax.jms.DeliveryMode;
/**
* @version $Revision: 1.1.1.1 $
*/
public class TransientQueueRedeliverTest extends TopicRedeliverTest {
protected void setUp() throws Exception{
super.setUp();
topic = false;
deliveryMode = DeliveryMode.NON_PERSISTENT;
}
}

View File

@ -0,0 +1,151 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.network.DemandForwardingBridge;
import org.apache.activemq.transport.TransportFactory;
import org.apache.activemq.JmsMultipleBrokersTestSupport;
import org.apache.activemq.command.Command;
import org.apache.activemq.util.MessageIdList;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import java.util.List;
import java.util.ArrayList;
import java.net.URI;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger;
/**
* @version $Revision: 1.1.1.1 $
*/
public class TwoBrokerMessageNotSentToRemoteWhenNoConsumerTest extends JmsMultipleBrokersTestSupport {
protected static final int MESSAGE_COUNT = 10;
protected List bridges;
protected AtomicInteger msgDispatchCount;
/**
* BrokerA -> BrokerB
*/
public void testRemoteBrokerHasConsumer() throws Exception {
// Setup broker networks
bridgeBrokers("BrokerA", "BrokerB");
startAllBrokers();
// Setup destination
Destination dest = createDestination("TEST.FOO", true);
// Setup consumers
MessageConsumer clientA = createConsumer("BrokerA", dest);
MessageConsumer clientB = createConsumer("BrokerB", dest);
// Send messages
sendMessages("BrokerA", dest, MESSAGE_COUNT);
// Get message count
MessageIdList msgsA = getConsumerMessages("BrokerA", clientA);
MessageIdList msgsB = getConsumerMessages("BrokerB", clientB);
msgsA.waitForMessagesToArrive(MESSAGE_COUNT);
msgsB.waitForMessagesToArrive(MESSAGE_COUNT);
assertEquals(MESSAGE_COUNT, msgsA.getMessageCount());
assertEquals(MESSAGE_COUNT, msgsB.getMessageCount());
// Check that 10 message dispatch commands are send over the network
assertEquals(MESSAGE_COUNT, msgDispatchCount.get());
}
/**
* BrokerA -> BrokerB
*/
public void testRemoteBrokerHasNoConsumer() throws Exception {
// Setup broker networks
bridgeBrokers("BrokerA", "BrokerB");
startAllBrokers();
// Setup destination
Destination dest = createDestination("TEST.FOO", true);
// Setup consumers
MessageConsumer clientA = createConsumer("BrokerA", dest);
// Send messages
sendMessages("BrokerA", dest, MESSAGE_COUNT);
// Get message count
MessageIdList msgsA = getConsumerMessages("BrokerA", clientA);
msgsA.waitForMessagesToArrive(MESSAGE_COUNT);
assertEquals(MESSAGE_COUNT, msgsA.getMessageCount());
// Check that no message dispatch commands are send over the network
assertEquals(0, msgDispatchCount.get());
}
protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception {
List remoteTransports = remoteBroker.getTransportConnectors();
List localTransports = localBroker.getTransportConnectors();
URI remoteURI, localURI;
if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) {
remoteURI = ((TransportConnector)remoteTransports.get(0)).getConnectUri();
localURI = ((TransportConnector)localTransports.get(0)).getConnectUri();
// Ensure that we are connecting using tcp
if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) {
DemandForwardingBridge bridge = new DemandForwardingBridge(TransportFactory.connect(localURI),
TransportFactory.connect(remoteURI)) {
protected void serviceLocalCommand(Command command) {
if (command.isMessageDispatch()) {
// Keep track of the number of message dispatches through the bridge
msgDispatchCount.incrementAndGet();
}
super.serviceLocalCommand(command);
}
};
bridge.setLocalBrokerName(localBroker.getBrokerName());
bridges.add(bridge);
bridge.start();
} else {
throw new Exception("Remote broker or local broker is not using tcp connectors");
}
} else {
throw new Exception("Remote broker or local broker has no registered connectors.");
}
MAX_SETUP_TIME = 2000;
}
public void setUp() throws Exception {
super.setAutoFail(true);
super.setUp();
createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false"));
createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false"));
bridges = new ArrayList();
msgDispatchCount = new AtomicInteger(0);
}
}

View File

@ -0,0 +1,269 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.CombinationTestSupport;
import org.apache.activemq.util.MessageIdList;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.xbean.XBeanBrokerFactory;
import java.net.URI;
import java.util.Arrays;
import junit.framework.Test;
import javax.jms.Destination;
import javax.jms.ConnectionFactory;
import javax.jms.Connection;
import javax.jms.Session;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.TextMessage;
public class TwoBrokerMulticastQueueTest extends CombinationTestSupport {
public static Test suite() {
return suite(TwoBrokerMulticastQueueTest.class);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static final int MESSAGE_COUNT = 100;
public static final int BROKER_COUNT = 2;
public static final int CONSUMER_COUNT = 20;
private BrokerService[] brokers;
public String sendUri, recvUri;
public void setUp() throws Exception {
super.setAutoFail(true);
super.setUp();
}
public void tearDown() throws Exception {
for (int i=0; i<BROKER_COUNT; i++) {
brokers[i].stop();
}
super.tearDown();
}
private void doSendReceiveTest() throws Exception {
Destination dest = new ActiveMQQueue("TEST.FOO");
ConnectionFactory sendFactory = createConnectionFactory(sendUri);
Connection conn = createConnection(sendFactory);
sendMessages(conn, dest, MESSAGE_COUNT);
Thread.sleep(500);
ConnectionFactory recvFactory = createConnectionFactory(recvUri);
assertEquals(MESSAGE_COUNT, receiveMessages(createConnection(recvFactory), dest, 0));
}
private void doMultipleConsumersConnectTest() throws Exception {
Destination dest = new ActiveMQQueue("TEST.FOO");
ConnectionFactory sendFactory = createConnectionFactory(sendUri);
Connection conn = createConnection(sendFactory);
sendMessages(conn, dest, MESSAGE_COUNT);
Thread.sleep(500);
ConnectionFactory recvFactory = createConnectionFactory(recvUri);
assertEquals(MESSAGE_COUNT, receiveMessages(createConnection(recvFactory), dest, 0));
for (int i=0; i<(CONSUMER_COUNT-1); i++) {
assertEquals(0, receiveMessages(createConnection(recvFactory), dest, 200));
}
}
public void initCombosForTestSendReceive() {
addCombinationValues("sendUri", new Object[] {
"tcp://localhost:61616", "tcp://localhost:61617"
});
addCombinationValues("recvUri", new Object[] {
"tcp://localhost:61616", "tcp://localhost:61617"
});
}
public void testSendReceive() throws Exception {
createMulticastBrokerNetwork();
doSendReceiveTest();
}
public void initCombosForTestMultipleConsumersConnect() {
addCombinationValues("sendUri", new Object[] {
"tcp://localhost:61616", "tcp://localhost:61617",
});
addCombinationValues("recvUri", new Object[] {
"tcp://localhost:61616", "tcp://localhost:61617"
});
}
public void testMultipleConsumersConnect() throws Exception {
createMulticastBrokerNetwork();
doMultipleConsumersConnectTest();
}
public void testSendReceiveUsingFailover() throws Exception {
sendUri = "failover:tcp://localhost:61616,tcp://localhost:61617";
recvUri = "failover:tcp://localhost:61616,tcp://localhost:61617";
createMulticastBrokerNetwork();
doSendReceiveTest();
}
public void testMultipleConsumersConnectUsingFailover() throws Exception {
sendUri = "failover:tcp://localhost:61616,tcp://localhost:61617";
recvUri = "failover:tcp://localhost:61616,tcp://localhost:61617";
createMulticastBrokerNetwork();
doMultipleConsumersConnectTest();
}
public void testSendReceiveUsingDiscovery() throws Exception {
sendUri = "discovery:multicast://default";
recvUri = "discovery:multicast://default";
createMulticastBrokerNetwork();
doSendReceiveTest();
}
public void testMultipleConsumersConnectUsingDiscovery() throws Exception {
sendUri = "discovery:multicast://default";
recvUri = "discovery:multicast://default";
createMulticastBrokerNetwork();
doMultipleConsumersConnectTest();
}
public void testSendReceiveUsingAutoAssignFailover() throws Exception {
sendUri = "failover:multicast://default";
recvUri = "failover:multicast://default";
createAutoAssignMulticastBrokerNetwork();
doSendReceiveTest();
}
public void testMultipleConsumersConnectUsingAutoAssignFailover() throws Exception {
sendUri = "failover:multicast://default";
recvUri = "failover:multicast://default";
createAutoAssignMulticastBrokerNetwork();
doMultipleConsumersConnectTest();
}
public void testSendReceiveUsingAutoAssignDiscovery() throws Exception {
sendUri = "discovery:multicast://default";
recvUri = "discovery:multicast://default";
createAutoAssignMulticastBrokerNetwork();
doSendReceiveTest();
}
public void testMultipleConsumersConnectUsingAutoAssignDiscovery() throws Exception {
sendUri = "discovery:multicast://default";
recvUri = "discovery:multicast://default";
createAutoAssignMulticastBrokerNetwork();
doMultipleConsumersConnectTest();
}
protected void createMulticastBrokerNetwork() throws Exception {
brokers = new BrokerService[BROKER_COUNT];
for (int i=0; i<BROKER_COUNT; i++) {
brokers[i] = createBroker("xbean:multicast-broker-" + (i+1)+ ".xml");
brokers[i].start();
}
// Let the brokers discover each other first
Thread.sleep(1000);
}
protected void createAutoAssignMulticastBrokerNetwork() throws Exception {
brokers = new BrokerService[BROKER_COUNT];
for (int i=0; i<BROKER_COUNT; i++) {
brokers[i] = createBroker("xbean:multicast-broker-auto.xml");
brokers[i].start();
}
// Let the brokers discover each other first
Thread.sleep(1000);
}
protected BrokerService createBroker(String uri) throws Exception {
return (new XBeanBrokerFactory()).createBroker(new URI(uri));
}
protected ConnectionFactory createConnectionFactory(String uri) {
return new ActiveMQConnectionFactory(uri);
}
protected Connection createConnection(ConnectionFactory factory) throws JMSException {
Connection conn = factory.createConnection();
return conn;
}
protected int receiveMessages(Connection conn, Destination dest, int waitTime) throws JMSException, InterruptedException {
conn.start();
MessageIdList list = new MessageIdList();
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = sess.createConsumer(dest);
consumer.setMessageListener(list);
if (waitTime > 0) {
Thread.sleep(waitTime);
} else {
list.waitForMessagesToArrive(MESSAGE_COUNT);
}
conn.close();
return list.getMessageCount();
}
protected void sendMessages(Connection conn, Destination dest, int count) throws JMSException {
conn.start();
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer prod = sess.createProducer(dest);
for (int i=0; i<count; i++) {
prod.send(createTextMessage(sess, "Message " + i, 1024));
}
conn.close();
}
protected TextMessage createTextMessage(Session session, String initText, int messageSize) throws JMSException {
TextMessage msg = session.createTextMessage();
// Pad message text
if (initText.length() < messageSize) {
char[] data = new char[messageSize - initText.length()];
Arrays.fill(data, '*');
String str = new String(data);
msg.setText(initText + str);
// Do not pad message text
} else {
msg.setText(initText);
}
return msg;
}
}

View File

@ -0,0 +1,365 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.JmsMultipleBrokersTestSupport;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQPrefetchPolicy;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.Connection;
import javax.jms.Session;
import javax.jms.MessageConsumer;
import java.net.URI;
/**
* @version $Revision: 1.1.1.1 $
*/
public class TwoBrokerQueueClientsReconnectTest extends JmsMultipleBrokersTestSupport {
protected static final int MESSAGE_COUNT = 100; // Best if a factor of 100
protected static final int PREFETCH_COUNT = 1;
protected int msgsClient1, msgsClient2;
protected String broker1, broker2;
public void testClientAReceivesOnly() throws Exception {
broker1 = "BrokerA";
broker2 = "BrokerB";
doOneClientReceivesOnly();
}
public void testClientBReceivesOnly() throws Exception {
broker1 = "BrokerB";
broker2 = "BrokerA";
doOneClientReceivesOnly();
}
public void doOneClientReceivesOnly() throws Exception {
// Bridge brokers
bridgeBrokers(broker1, broker2);
bridgeBrokers(broker2, broker1);
// Run brokers
startAllBrokers();
// Create queue
Destination dest = createDestination("TEST.FOO", false);
// Create consumers
MessageConsumer client1 = createConsumer(broker1, dest);
MessageConsumer client2 = createConsumer(broker2, dest);
// Give clients time to register with broker
Thread.sleep(500);
// Always send messages to broker A
sendMessages("BrokerA", dest, MESSAGE_COUNT);
// Close the second client, messages should be sent to the first client
client2.close();
// Let the first client receive all messages
msgsClient1 += receiveAllMessages(client1);
client1.close();
// First client should have received 100 messages
assertEquals("Client for " + broker1 + " should have receive all messages.", MESSAGE_COUNT, msgsClient1);
}
public void testClientAReceivesOnlyAfterReconnect() throws Exception {
broker1 = "BrokerA";
broker2 = "BrokerB";
doOneClientReceivesOnlyAfterReconnect();
}
public void testClientBReceivesOnlyAfterReconnect() throws Exception {
broker1 = "BrokerB";
broker2 = "BrokerA";
doOneClientReceivesOnlyAfterReconnect();
}
public void doOneClientReceivesOnlyAfterReconnect() throws Exception {
// Bridge brokers
bridgeBrokers(broker1, broker2);
bridgeBrokers(broker2, broker1);
// Run brokers
startAllBrokers();
// Create queue
Destination dest = createDestination("TEST.FOO", false);
// Create first consumer
MessageConsumer client1 = createConsumer(broker1, dest);
MessageConsumer client2 = createConsumer(broker2, dest);
// Give clients time to register with broker
Thread.sleep(500);
// Always send message to broker A
sendMessages("BrokerA", dest, MESSAGE_COUNT);
// Let the first client receive the first 20% of messages
msgsClient1 += receiveExactMessages(client1, (int)(MESSAGE_COUNT * 0.20));
// Disconnect the first client
client1.close();
// Create another client for the first broker
client1 = createConsumer(broker1, dest);
Thread.sleep(500);
// Close the second client, messages should be sent to the first client
client2.close();
// Receive the rest of the messages
msgsClient1 += receiveAllMessages(client1);
client1.close();
// The first client should have received 100 messages
assertEquals("Client for " + broker1 + " should have received all messages.", MESSAGE_COUNT, msgsClient1);
}
public void testTwoClientsReceiveClientADisconnects() throws Exception {
broker1 = "BrokerA";
broker2 = "BrokerB";
doTwoClientsReceiveOneClientDisconnects();
}
public void testTwoClientsReceiveClientBDisconnects() throws Exception {
broker1 = "BrokerB";
broker2 = "BrokerA";
doTwoClientsReceiveOneClientDisconnects();
}
public void doTwoClientsReceiveOneClientDisconnects() throws Exception {
// Bridge brokers
bridgeBrokers(broker1, broker2);
bridgeBrokers(broker2, broker1);
// Run brokers
startAllBrokers();
// Create queue
Destination dest = createDestination("TEST.FOO", false);
// Create first client
MessageConsumer client1 = createConsumer(broker1, dest);
MessageConsumer client2 = createConsumer(broker2, dest);
// Give clients time to register with broker
Thread.sleep(500);
// Always send messages to broker A
sendMessages("BrokerA", dest, MESSAGE_COUNT);
// Let each client receive 20% of the messages - 40% total
msgsClient1 += receiveExactMessages(client1, (int)(MESSAGE_COUNT * 0.20));
msgsClient2 += receiveExactMessages(client2, (int)(MESSAGE_COUNT * 0.20));
// Disconnect the first client
client1.close();
// Let the second client receive the rest of the messages
msgsClient2 += receiveAllMessages(client2);
client2.close();
// First client should have received 20% of the messages
assertEquals("Client for " + broker1 + " should have received 20% of the messages.", (int)(MESSAGE_COUNT * 0.20), msgsClient1);
// Second client should have received 80% of the messages
assertEquals("Client for " + broker2 + " should have received 80% of the messages.", (int)(MESSAGE_COUNT * 0.80), msgsClient2);
}
public void testTwoClientsReceiveClientAReconnects() throws Exception {
broker1 = "BrokerA";
broker2 = "BrokerB";
doTwoClientsReceiveOneClientReconnects();
}
public void testTwoClientsReceiveClientBReconnects() throws Exception {
broker1 = "BrokerB";
broker2 = "BrokerA";
doTwoClientsReceiveOneClientReconnects();
}
public void doTwoClientsReceiveOneClientReconnects() throws Exception {
// Bridge brokers
bridgeBrokers(broker1, broker2);
bridgeBrokers(broker2, broker1);
// Run brokers
startAllBrokers();
// Create queue
Destination dest = createDestination("TEST.FOO", false);
// Create the first client
MessageConsumer client1 = createConsumer(broker1, dest);
MessageConsumer client2 = createConsumer(broker2, dest);
// Give clients time to register with broker
Thread.sleep(500);
// Always send messages to broker A
sendMessages("BrokerA", dest, MESSAGE_COUNT);
// Let each client receive 20% of the messages - 40% total
msgsClient1 += receiveExactMessages(client1, (int)(MESSAGE_COUNT * 0.20));
msgsClient2 += receiveExactMessages(client2, (int)(MESSAGE_COUNT * 0.20));
// Disconnect the first client
client1.close();
// Let the second client receive 20% more of the total messages
msgsClient2 += receiveExactMessages(client2, (int)(MESSAGE_COUNT * 0.20));
// Create another client for broker 1
client1 = createConsumer(broker1, dest);
Thread.sleep(500);
// Let each client receive 20% of the messages - 40% total
msgsClient1 += receiveExactMessages(client1, (int)(MESSAGE_COUNT * 0.20));
client1.close();
msgsClient2 += receiveExactMessages(client2, (int)(MESSAGE_COUNT * 0.20));
client2.close();
// First client should have received 40 messages
assertEquals("Client for " + broker1 + " should have received 40% of the messages.", (int)(MESSAGE_COUNT * 0.40), msgsClient1);
// Second client should have received 60 messages
assertEquals("Client for " + broker2 + " should have received 60% of the messages.", (int)(MESSAGE_COUNT * 0.60), msgsClient2);
}
public void testTwoClientsReceiveTwoClientReconnects() throws Exception {
broker1 = "BrokerA";
broker2 = "BrokerB";
// Bridge brokers
bridgeBrokers(broker1, broker2);
bridgeBrokers(broker2, broker1);
// Run brokers
startAllBrokers();
// Create queue
Destination dest = createDestination("TEST.FOO", false);
// Create the first client
MessageConsumer client1 = createConsumer(broker1, dest);
MessageConsumer client2 = createConsumer(broker2, dest);
// Give clients time to register with broker
Thread.sleep(500);
// Always send messages to broker A
sendMessages("BrokerA", dest, MESSAGE_COUNT);
// Let each client receive 20% of the messages - 40% total
msgsClient1 += receiveExactMessages(client1, (int)(MESSAGE_COUNT * 0.20));
msgsClient2 += receiveExactMessages(client2, (int)(MESSAGE_COUNT * 0.20));
// Disconnect both clients
client1.close();
client2.close();
// Create another two clients for each broker
client1 = createConsumer(broker1, dest);
client2 = createConsumer(broker2, dest);
Thread.sleep(500);
// Let each client receive 30% more of the total messages - 60% total
msgsClient1 += receiveExactMessages(client1, (int)(MESSAGE_COUNT * 0.30));
client1.close();
msgsClient2 += receiveExactMessages(client2, (int)(MESSAGE_COUNT * 0.30));
client2.close();
// First client should have received 50% of the messages
assertEquals("Client for " + broker1 + " should have received 50% of the messages.", (int)(MESSAGE_COUNT * 0.50), msgsClient1);
// Second client should have received 50% of the messages
assertEquals("Client for " + broker2 + " should have received 50% of the messages.", (int)(MESSAGE_COUNT * 0.50), msgsClient2);
}
protected int receiveExactMessages(MessageConsumer consumer, int msgCount) throws Exception {
Message msg;
int i;
for (i=0; i<msgCount; i++) {
msg = consumer.receive(1000);
if (msg == null) {
System.err.println("Consumer failed to receive exactly " + msgCount + " messages. Actual messages received is: " + i);
break;
}
}
return i;
}
protected int receiveAllMessages(MessageConsumer consumer) throws Exception {
int msgsReceived = 0;
Message msg;
do {
msg = consumer.receive(1000);
if (msg != null) {
msgsReceived++;
}
} while (msg != null);
return msgsReceived;
}
protected MessageConsumer createConsumer(String brokerName, Destination dest) throws Exception {
Connection conn = createConnection(brokerName);
conn.start();
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
return sess.createConsumer(dest);
}
public void setUp() throws Exception {
super.setAutoFail(true);
super.setUp();
createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false"));
createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false"));
// Configure broker connection factory
ActiveMQConnectionFactory factoryA, factoryB;
factoryA = (ActiveMQConnectionFactory)getConnectionFactory("BrokerA");
factoryB = (ActiveMQConnectionFactory)getConnectionFactory("BrokerB");
// Set prefetch policy
ActiveMQPrefetchPolicy policy = new ActiveMQPrefetchPolicy();
policy.setAll(PREFETCH_COUNT);
factoryA.setPrefetchPolicy(policy);
factoryB.setPrefetchPolicy(policy);
msgsClient1 = 0;
msgsClient2 = 0;
}
}

View File

@ -0,0 +1,35 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
* @version $Revision: 1.1.1.1 $
*/
public class TwoBrokerQueueSendReceiveTest extends TwoBrokerTopicSendReceiveTest {
protected ActiveMQConnectionFactory sendFactory;
protected ActiveMQConnectionFactory receiveFactory;
protected void setUp() throws Exception {
topic = false;
super.setUp();
}
}

View File

@ -0,0 +1,30 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
/**
* @version $Revision$
*/
public class TwoBrokerTopicSendReceiveLotsOfMessagesUsingTcpTest extends TwoBrokerTopicSendReceiveUsingTcpTest {
protected void setUp() throws Exception {
this.messageCount = 5000;
super.setUp();
}
}

View File

@ -0,0 +1,78 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import javax.jms.Connection;
import javax.jms.JMSException;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.xbean.BrokerFactoryBean;
import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest;
import org.springframework.core.io.ClassPathResource;
/**
* @version $Revision: 1.1.1.1 $
*/
public class TwoBrokerTopicSendReceiveTest extends JmsTopicSendReceiveWithTwoConnectionsTest {
protected ActiveMQConnectionFactory sendFactory;
protected ActiveMQConnectionFactory receiveFactory;
protected void setUp() throws Exception {
sendFactory = createSenderConnectionFactory();
receiveFactory = createReceiverConnectionFactory();
super.setUp();
}
protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException {
return createConnectionFactory("org/apache/activemq/usecases/receiver.xml", "receiver", "vm://receiver");
}
protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException {
return createConnectionFactory("org/apache/activemq/usecases/sender.xml", "sender", "vm://sender");
}
protected void tearDown() throws Exception {
super.tearDown();
}
protected Connection createReceiveConnection() throws JMSException {
return receiveFactory.createConnection();
}
protected Connection createSendConnection() throws JMSException {
return sendFactory.createConnection();
}
protected ActiveMQConnectionFactory createConnectionFactory(String config, String brokerName, String connectUrl) throws JMSException {
try {
BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(config));
brokerFactory.afterPropertiesSet();
BrokerService broker = brokerFactory.getBroker();
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(((TransportConnector)broker.getTransportConnectors().get(0)).getConnectUri());
return factory;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -0,0 +1,43 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.JMSException;
/**
* @version $Revision: 1.1.1.1 $
*/
public class TwoBrokerTopicSendReceiveUsingHttpTest extends TwoBrokerTopicSendReceiveTest {
protected void setUp() throws Exception {
super.setUp();
// Give jetty server enough time to setup,
// so we don't lose messages when connection fails
Thread.sleep(5000);
}
protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException {
return createConnectionFactory("org/apache/activemq/usecases/receiver-http.xml", "receiver", "vm://receiver");
}
protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException {
return createConnectionFactory("org/apache/activemq/usecases/sender-http.xml", "sender", "vm://sender");
}
}

View File

@ -0,0 +1,75 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import javax.jms.JMSException;
/**
* @version $Revision: 1.1.1.1 $
*/
public class TwoBrokerTopicSendReceiveUsingJavaConfigurationTest extends TwoBrokerTopicSendReceiveTest {
BrokerService receiveBroker;
BrokerService sendBroker;
protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException {
try {
receiveBroker = new BrokerService();
receiveBroker.setUseJmx(false);
receiveBroker.setPersistent(false);
receiveBroker.addConnector("tcp://localhost:62002");
receiveBroker.addNetworkConnector("static:failover:tcp://localhost:62001");
receiveBroker.start();
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:62002");
return factory;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException {
try {
sendBroker = new BrokerService();
sendBroker.setUseJmx(false);
sendBroker.setPersistent(false);
sendBroker.addConnector("tcp://localhost:62001");
sendBroker.addNetworkConnector("static:failover:tcp://localhost:62002");
sendBroker.start();
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:62001");
return factory;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected void tearDown() throws Exception {
super.tearDown();
if (sendBroker != null) {
sendBroker.stop();
}
if (receiveBroker != null) {
receiveBroker.stop();
}
}
}

View File

@ -0,0 +1,84 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import javax.jms.JMSException;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.xbean.BrokerFactoryBean;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
import java.net.URISyntaxException;
/**
* @version $Revision: 1.1.1.1 $
*/
public class TwoBrokerTopicSendReceiveUsingTcpTest extends TwoBrokerTopicSendReceiveTest {
private BrokerService receiverBroker;
private BrokerService senderBroker;
protected void setUp() throws Exception {
BrokerFactoryBean brokerFactory;
brokerFactory = new BrokerFactoryBean(new ClassPathResource("org/apache/activemq/usecases/receiver.xml"));
brokerFactory.afterPropertiesSet();
receiverBroker = brokerFactory.getBroker();
brokerFactory = new BrokerFactoryBean(new ClassPathResource("org/apache/activemq/usecases/sender.xml"));
brokerFactory.afterPropertiesSet();
senderBroker = brokerFactory.getBroker();
super.setUp();
Thread.sleep(2000);
}
protected void tearDown() throws Exception {
super.tearDown();
if (receiverBroker != null) {
receiverBroker.stop();
}
if (senderBroker != null) {
senderBroker.stop();
}
}
protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException {
try {
ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(((TransportConnector)receiverBroker.getTransportConnectors().get(0)).getConnectUri());
return fac;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException {
try {
ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(((TransportConnector)senderBroker.getTransportConnectors().get(0)).getConnectUri());
return fac;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -0,0 +1,35 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed 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
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.JMSException;
/**
* @version $Revision: 1.1.1.1 $
*/
public class TwoMulticastDiscoveryBrokerTopicSendReceiveTest extends TwoBrokerTopicSendReceiveTest {
protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException {
return createConnectionFactory("org/apache/activemq/usecases/receiver-discovery.xml", "receiver", "vm://receiver");
}
protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException {
return createConnectionFactory("org/apache/activemq/usecases/sender-discovery.xml", "sender", "vm://sender");
}
}