Fix a bunch of warnings covering deprecated asserts and such.

git-svn-id: https://svn.apache.org/repos/asf/activemq/trunk@1443600 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Timothy A. Bish 2013-02-07 16:43:15 +00:00
parent c7d559fbcd
commit 4743a20be3
83 changed files with 1535 additions and 1506 deletions

View File

@ -18,10 +18,13 @@ package org.apache.activemq.perf;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.jms.Connection; import javax.jms.Connection;
import javax.jms.ConnectionFactory; import javax.jms.ConnectionFactory;
import javax.jms.JMSException; import javax.jms.JMSException;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
@ -41,7 +44,7 @@ public class ConnectionChurnTest extends TestCase {
public void testPerformance() throws Exception { public void testPerformance() throws Exception {
ConnectionFactory factory = createConnectionFactory(); ConnectionFactory factory = createConnectionFactory();
List<Connection> list = new ArrayList(); List<Connection> list = new ArrayList<Connection>();
for (int i = 0; i < CONNECTION_COUNT; i++) { for (int i = 0; i < CONNECTION_COUNT; i++) {
Connection connection = factory.createConnection(); Connection connection = factory.createConnection();
connection.start(); connection.start();
@ -64,6 +67,7 @@ public class ConnectionChurnTest extends TestCase {
list.clear(); list.clear();
} }
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
if (broker == null) { if (broker == null) {
broker = createBroker(); broker = createBroker();
@ -71,6 +75,7 @@ public class ConnectionChurnTest extends TestCase {
super.setUp(); super.setUp();
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
super.tearDown(); super.tearDown();
if (broker != null) { if (broker != null) {

View File

@ -24,9 +24,10 @@ import javax.jms.MessageProducer;
import javax.jms.Session; import javax.jms.Session;
import javax.jms.Topic; import javax.jms.Topic;
import javax.jms.TopicSubscriber; import javax.jms.TopicSubscriber;
import junit.framework.Assert;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -137,7 +138,7 @@ public class InactiveDurableTopicTest extends TestCase {
LOG.info("Sent " + loop + " messages"); LOG.info("Sent " + loop + " messages");
} }
} }
Assert.assertEquals(loop, MESSAGE_COUNT); assertEquals(loop, MESSAGE_COUNT);
publisher.close(); publisher.close();
session.close(); session.close();
connection.stop(); connection.stop();
@ -169,12 +170,12 @@ public class InactiveDurableTopicTest extends TestCase {
assertNotNull(subscriber); assertNotNull(subscriber);
int loop; int loop;
for (loop = 0; loop < MESSAGE_COUNT; loop++) { for (loop = 0; loop < MESSAGE_COUNT; loop++) {
Message msg = subscriber.receive(); subscriber.receive();
if (loop % 500 == 0) { if (loop % 500 == 0) {
LOG.debug("Received " + loop + " messages"); LOG.debug("Received " + loop + " messages");
} }
} }
this.assertEquals(loop, MESSAGE_COUNT); assertEquals(loop, MESSAGE_COUNT);
subscriber.close(); subscriber.close();
session.close(); session.close();
connection.close(); connection.close();

View File

@ -22,9 +22,9 @@ import javax.jms.MapMessage;
import javax.jms.Message; import javax.jms.Message;
import javax.jms.MessageProducer; import javax.jms.MessageProducer;
import javax.jms.Session; import javax.jms.Session;
import javax.jms.TopicSubscriber;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -39,7 +39,6 @@ public class InactiveQueueTest extends TestCase {
private static final int MESSAGE_COUNT = 0; private static final int MESSAGE_COUNT = 0;
private static final String DEFAULT_PASSWORD = ""; private static final String DEFAULT_PASSWORD = "";
private static final String USERNAME = "testuser"; private static final String USERNAME = "testuser";
private static final String CLIENTID = "mytestclient";
private static final String QUEUE_NAME = "testevent"; private static final String QUEUE_NAME = "testevent";
private static final int DELIVERY_MODE = javax.jms.DeliveryMode.PERSISTENT; private static final int DELIVERY_MODE = javax.jms.DeliveryMode.PERSISTENT;
private static final int DELIVERY_PRIORITY = javax.jms.Message.DEFAULT_PRIORITY; private static final int DELIVERY_PRIORITY = javax.jms.Message.DEFAULT_PRIORITY;
@ -49,10 +48,10 @@ public class InactiveQueueTest extends TestCase {
private Connection connection; private Connection connection;
private MessageProducer publisher; private MessageProducer publisher;
private TopicSubscriber subscriber;
private Destination destination; private Destination destination;
private Session session; private Session session;
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
super.setUp(); super.setUp();
broker = new BrokerService(); broker = new BrokerService();
@ -77,6 +76,7 @@ public class InactiveQueueTest extends TestCase {
connectionFactory.setUseAsyncSend(true); connectionFactory.setUseAsyncSend(true);
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
super.tearDown(); super.tearDown();
broker.stop(); broker.stop();
@ -104,7 +104,7 @@ public class InactiveQueueTest extends TestCase {
} }
} }
Thread.sleep(1000000); Thread.sleep(1000000);
this.assertEquals(loop, MESSAGE_COUNT); assertEquals(loop, MESSAGE_COUNT);
publisher.close(); publisher.close();
session.close(); session.close();
connection.stop(); connection.stop();

View File

@ -21,7 +21,6 @@ import javax.jms.ConnectionFactory;
import javax.jms.Destination; import javax.jms.Destination;
import javax.jms.JMSException; import javax.jms.JMSException;
import javax.jms.Message; import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer; import javax.jms.MessageProducer;
import javax.jms.Session; import javax.jms.Session;
import javax.jms.TemporaryQueue; import javax.jms.TemporaryQueue;
@ -81,6 +80,7 @@ public class MemoryAllocationTest extends TestCase {
} }
} }
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
if (broker == null) { if (broker == null) {
broker = createBroker(); broker = createBroker();
@ -88,6 +88,7 @@ public class MemoryAllocationTest extends TestCase {
super.setUp(); super.setUp();
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
super.tearDown(); super.tearDown();

View File

@ -33,9 +33,9 @@ import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.network.NetworkConnector; import org.apache.activemq.network.NetworkConnector;
import org.apache.activemq.xbean.BrokerFactoryBean; import org.apache.activemq.xbean.BrokerFactoryBean;
import org.apache.xbean.spring.context.ClassPathXmlApplicationContext;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.apache.xbean.spring.context.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
@ -67,10 +67,12 @@ public class NetworkedSyncTest extends TestCase {
/** /**
* @throws java.lang.Exception * @throws java.lang.Exception
*/ */
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
LOG.info("setUp() called."); LOG.info("setUp() called.");
ClassPathXmlApplicationContext context1 = null; ClassPathXmlApplicationContext context1 = null;
BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(config)); BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(config));
assertNotNull(brokerFactory);
/* start up first broker instance */ /* start up first broker instance */
try { try {
@ -125,6 +127,7 @@ public class NetworkedSyncTest extends TestCase {
/** /**
* @throws java.lang.Exception * @throws java.lang.Exception
*/ */
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
LOG.info("tearDown() called."); LOG.info("tearDown() called.");
@ -180,6 +183,7 @@ class Producer implements Runnable {
/** /**
* connect to broker and constantly send messages * connect to broker and constantly send messages
*/ */
@Override
public void run() { public void run() {
Connection connection = null; Connection connection = null;
@ -192,6 +196,7 @@ class Producer implements Runnable {
connection = amq.createConnection(); connection = amq.createConnection();
connection.setExceptionListener(new javax.jms.ExceptionListener() { connection.setExceptionListener(new javax.jms.ExceptionListener() {
@Override
public void onException(javax.jms.JMSException e) { public void onException(javax.jms.JMSException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -251,6 +256,7 @@ class Consumer implements Runnable {
/** /**
* connect to broker and receive messages * connect to broker and receive messages
*/ */
@Override
public void run() { public void run() {
Connection connection = null; Connection connection = null;
Session session = null; Session session = null;
@ -264,6 +270,7 @@ class Consumer implements Runnable {
connection.setClientID("tmielke"); connection.setClientID("tmielke");
connection.setExceptionListener(new javax.jms.ExceptionListener() { connection.setExceptionListener(new javax.jms.ExceptionListener() {
@Override
public void onException(javax.jms.JMSException e) { public void onException(javax.jms.JMSException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -280,7 +287,7 @@ class Consumer implements Runnable {
Message message2 = consumer.receive(); Message message2 = consumer.receive();
if (message2 instanceof TextMessage) { if (message2 instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message2; TextMessage textMessage = (TextMessage) message2;
String text = textMessage.getText(); textMessage.getText();
// logger.info("Received: " + text); // logger.info("Received: " + text);
} else { } else {
LOG.error("Received message of unsupported type. Expecting TextMessage. "+ message2); LOG.error("Received message of unsupported type. Expecting TextMessage. "+ message2);

View File

@ -19,8 +19,8 @@ package org.apache.activemq.perf;
import javax.jms.Connection; import javax.jms.Connection;
import javax.jms.Destination; import javax.jms.Destination;
import javax.jms.JMSException; import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session; import javax.jms.Session;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.store.kahadaptor.KahaPersistenceAdapter; import org.apache.activemq.store.kahadaptor.KahaPersistenceAdapter;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -32,21 +32,26 @@ import org.slf4j.LoggerFactory;
public class QueueConnectionMemoryTest extends SimpleQueueTest { public class QueueConnectionMemoryTest extends SimpleQueueTest {
private static final transient Logger LOG = LoggerFactory.getLogger(QueueConnectionMemoryTest.class); private static final transient Logger LOG = LoggerFactory.getLogger(QueueConnectionMemoryTest.class);
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
} }
@Override
protected Destination createDestination(Session s, String destinationName) throws JMSException { protected Destination createDestination(Session s, String destinationName) throws JMSException {
return s.createTemporaryQueue(); return s.createTemporaryQueue();
} }
@Override
public void testPerformance() throws JMSException { public void testPerformance() throws JMSException {
// just cancel super class test // just cancel super class test
} }
@Override
protected void configureBroker(BrokerService answer,String uri) throws Exception { protected void configureBroker(BrokerService answer,String uri) throws Exception {
KahaPersistenceAdapter adaptor = new KahaPersistenceAdapter(); KahaPersistenceAdapter adaptor = new KahaPersistenceAdapter();
answer.setPersistenceAdapter(adaptor); answer.setPersistenceAdapter(adaptor);
@ -61,14 +66,14 @@ public class QueueConnectionMemoryTest extends SimpleQueueTest {
factory = createConnectionFactory(bindAddress); factory = createConnectionFactory(bindAddress);
Connection con = factory.createConnection(); Connection con = factory.createConnection();
Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = createDestination(session, destinationName); createDestination(session, destinationName);
con.close(); con.close();
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
Connection connection = factory.createConnection(); Connection connection = factory.createConnection();
connection.start(); connection.start();
Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination dest = s.createTemporaryQueue(); Destination dest = s.createTemporaryQueue();
MessageConsumer consumer = s.createConsumer(dest); s.createConsumer(dest);
LOG.debug("Created connnection: " + i); LOG.debug("Created connnection: " + i);
Thread.sleep(1000); Thread.sleep(1000);
} }

View File

@ -17,6 +17,7 @@
package org.apache.activemq.perf; package org.apache.activemq.perf;
import java.io.File; import java.io.File;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter;
import org.apache.activemq.util.IOHelper; import org.apache.activemq.util.IOHelper;
@ -29,7 +30,6 @@ public class RunBroker {
KahaDBPersistenceAdapter kahaDB = new KahaDBPersistenceAdapter(); KahaDBPersistenceAdapter kahaDB = new KahaDBPersistenceAdapter();
File dataFileDir = new File("target/test-amq-data/perfTest/kahadb"); File dataFileDir = new File("target/test-amq-data/perfTest/kahadb");
IOHelper.deleteChildren(dataFileDir); IOHelper.deleteChildren(dataFileDir);
File archiveDir = new File(dataFileDir, "archive");
kahaDB.setDirectory(dataFileDir); kahaDB.setDirectory(dataFileDir);
// The setEnableJournalDiskSyncs(false) setting is a little // The setEnableJournalDiskSyncs(false) setting is a little

View File

@ -21,7 +21,9 @@ import javax.jms.ConnectionFactory;
import javax.jms.Destination; import javax.jms.Destination;
import javax.jms.JMSException; import javax.jms.JMSException;
import javax.jms.Session; import javax.jms.Session;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -60,6 +62,7 @@ public class SimpleTopicTest extends TestCase {
* *
* @see junit.framework.TestCase#setUp() * @see junit.framework.TestCase#setUp()
*/ */
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
if (broker == null) { if (broker == null) {
broker = createBroker(bindAddress); broker = createBroker(bindAddress);
@ -68,7 +71,6 @@ public class SimpleTopicTest extends TestCase {
Connection con = factory.createConnection(); Connection con = factory.createConnection();
Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
LOG.info("Running " + numberofProducers + " producer(s) and " + numberOfConsumers + " consumer(s) per " + numberOfDestinations + " Destination(s)"); LOG.info("Running " + numberofProducers + " producer(s) and " + numberOfConsumers + " consumer(s) per " + numberOfDestinations + " Destination(s)");
totalNumberOfConsumers = numberOfConsumers * numberOfDestinations; totalNumberOfConsumers = numberOfConsumers * numberOfDestinations;
@ -97,6 +99,7 @@ public class SimpleTopicTest extends TestCase {
super.setUp(); super.setUp();
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
super.tearDown(); super.tearDown();
for (int i = 0; i < numberOfConsumers; i++) { for (int i = 0; i < numberOfConsumers; i++) {
@ -135,7 +138,6 @@ public class SimpleTopicTest extends TestCase {
return new PerfConsumer(fac, dest); return new PerfConsumer(fac, dest);
} }
protected void configureBroker(BrokerService answer, String uri) throws Exception { protected void configureBroker(BrokerService answer, String uri) throws Exception {
answer.setDeleteAllMessagesOnStartup(true); answer.setDeleteAllMessagesOnStartup(true);
answer.addConnector(uri); answer.addConnector(uri);
@ -167,6 +169,7 @@ public class SimpleTopicTest extends TestCase {
} }
} }
@SuppressWarnings("unused")
protected void dumpProducerRate() { protected void dumpProducerRate() {
int totalRate = 0; int totalRate = 0;
int totalCount = 0; int totalCount = 0;
@ -179,9 +182,7 @@ public class SimpleTopicTest extends TestCase {
} }
if (producers != null && producers.length > 0) { if (producers != null && producers.length > 0) {
int avgRate = totalRate / producers.length; int avgRate = totalRate / producers.length;
System.out.println("Avg producer rate = " + avgRate System.out.println("Avg producer rate = " + avgRate + " msg/sec | Total rate = " + totalRate + ", sent = " + totalCount);
+ " msg/sec | Total rate = " + totalRate + ", sent = "
+ totalCount);
// System.out.println(producerString); // System.out.println(producerString);
} }
} }

View File

@ -16,21 +16,9 @@
*/ */
package org.apache.activemq.security; package org.apache.activemq.security;
import org.apache.activemq.command.ActiveMQQueue; import static org.junit.Assert.assertEquals;
import org.apache.activemq.command.ActiveMQTopic; import static org.junit.Assert.assertNull;
import org.apache.activemq.jaas.GroupPrincipal; import static org.junit.Assert.assertTrue;
import org.apache.activemq.util.Wait;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
import org.apache.directory.shared.ldap.model.ldif.LdifEntry;
import org.apache.directory.shared.ldap.model.ldif.LdifReader;
import org.apache.directory.shared.ldap.model.message.ModifyRequest;
import org.apache.directory.shared.ldap.model.message.ModifyRequestImpl;
import org.apache.directory.shared.ldap.model.name.Dn;
import org.apache.directory.shared.ldap.model.name.Rdn;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -46,9 +34,21 @@ import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration; import javax.naming.NamingEnumeration;
import javax.naming.directory.DirContext; import javax.naming.directory.DirContext;
import static org.junit.Assert.assertEquals; import org.apache.activemq.command.ActiveMQQueue;
import static org.junit.Assert.assertNull; import org.apache.activemq.command.ActiveMQTopic;
import static org.junit.Assert.assertTrue; import org.apache.activemq.jaas.GroupPrincipal;
import org.apache.activemq.util.Wait;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
import org.apache.directory.shared.ldap.model.ldif.LdifEntry;
import org.apache.directory.shared.ldap.model.ldif.LdifReader;
import org.apache.directory.shared.ldap.model.message.ModifyRequest;
import org.apache.directory.shared.ldap.model.message.ModifyRequestImpl;
import org.apache.directory.shared.ldap.model.name.Dn;
import org.apache.directory.shared.ldap.model.name.Rdn;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public abstract class AbstractCachedLDAPAuthorizationMapLegacyTest extends AbstractLdapTestUnit { public abstract class AbstractCachedLDAPAuthorizationMapLegacyTest extends AbstractLdapTestUnit {
@ -110,6 +110,8 @@ public abstract class AbstractCachedLDAPAuthorizationMapLegacyTest extends Abstr
connection.delete(entry.getDn()); connection.delete(entry.getDn());
} }
reader.close();
failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO"));
assertEquals("set size: " + failedACLs, 0, failedACLs.size()); assertEquals("set size: " + failedACLs, 0, failedACLs.size());
@ -165,6 +167,8 @@ public abstract class AbstractCachedLDAPAuthorizationMapLegacyTest extends Abstr
connection.add(entry.getEntry()); connection.add(entry.getEntry());
} }
reader.close();
Thread.sleep(2000); Thread.sleep(2000);
failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED"));
@ -184,6 +188,7 @@ public abstract class AbstractCachedLDAPAuthorizationMapLegacyTest extends Abstr
connection.delete(entry.getDn()); connection.delete(entry.getDn());
} }
reader.close();
Thread.sleep(2000); Thread.sleep(2000);
failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO"));
@ -304,6 +309,7 @@ public abstract class AbstractCachedLDAPAuthorizationMapLegacyTest extends Abstr
// wait for the context to be closed // wait for the context to be closed
// as we can't rely on ldar server isStarted() // as we can't rely on ldar server isStarted()
Wait.waitFor(new Wait.Condition() { Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
if (sync) { if (sync) {
return !map.isContextAlive(); return !map.isContextAlive();
@ -328,6 +334,7 @@ public abstract class AbstractCachedLDAPAuthorizationMapLegacyTest extends Abstr
connection.add(entry.getEntry()); connection.add(entry.getEntry());
} }
reader.close();
Thread.sleep(2000); Thread.sleep(2000);
failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED"));
@ -378,6 +385,7 @@ public abstract class AbstractCachedLDAPAuthorizationMapLegacyTest extends Abstr
// We are assuming that there isn't already a security manager in place. // We are assuming that there isn't already a security manager in place.
final SecurityManager securityManager = new SecurityManager() { final SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPermission(java.security.Permission permission) { public void checkPermission(java.security.Permission permission) {
if (permission.getName().contains("exitVM")) { if (permission.getName().contains("exitVM")) {
throw new SecurityException("System.exit calls disabled for the moment."); throw new SecurityException("System.exit calls disabled for the moment.");

View File

@ -27,6 +27,7 @@ import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration; import javax.security.auth.login.Configuration;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.broker.StubBroker; import org.apache.activemq.broker.StubBroker;
import org.apache.activemq.command.ConnectionInfo; import org.apache.activemq.command.ConnectionInfo;
@ -42,6 +43,7 @@ public class JaasCertificateAuthenticationBrokerTest extends TestCase {
ConnectionContext connectionContext; ConnectionContext connectionContext;
ConnectionInfo connectionInfo; ConnectionInfo connectionInfo;
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
receiveBroker = new StubBroker(); receiveBroker = new StubBroker();
@ -53,6 +55,7 @@ public class JaasCertificateAuthenticationBrokerTest extends TestCase {
connectionInfo.setTransportContext(new StubX509Certificate[] {}); connectionInfo.setTransportContext(new StubX509Certificate[] {});
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
super.tearDown(); super.tearDown();
} }
@ -110,14 +113,14 @@ public class JaasCertificateAuthenticationBrokerTest extends TestCase {
assertEquals("Number of addConnection calls to underlying Broker must match number of calls made to " + "AuthenticationBroker.", 1, receiveBroker.addConnectionData.size()); assertEquals("Number of addConnection calls to underlying Broker must match number of calls made to " + "AuthenticationBroker.", 1, receiveBroker.addConnectionData.size());
ConnectionContext receivedContext = ((StubBroker.AddConnectionData)receiveBroker.addConnectionData.getFirst()).connectionContext; ConnectionContext receivedContext = receiveBroker.addConnectionData.getFirst().connectionContext;
assertEquals("The SecurityContext's userName must be set to that of the UserPrincipal.", dnUserName, receivedContext.getSecurityContext().getUserName()); assertEquals("The SecurityContext's userName must be set to that of the UserPrincipal.", dnUserName, receivedContext.getSecurityContext().getUserName());
Set receivedPrincipals = receivedContext.getSecurityContext().getPrincipals(); Set<Principal> receivedPrincipals = receivedContext.getSecurityContext().getPrincipals();
for (Iterator iter = receivedPrincipals.iterator(); iter.hasNext();) { for (Iterator<Principal> iter = receivedPrincipals.iterator(); iter.hasNext();) {
Principal currentPrincipal = (Principal)iter.next(); Principal currentPrincipal = iter.next();
if (currentPrincipal instanceof UserPrincipal) { if (currentPrincipal instanceof UserPrincipal) {
if (userNames.remove(currentPrincipal.getName())) { if (userNames.remove(currentPrincipal.getName())) {

View File

@ -17,7 +17,18 @@
package org.apache.activemq.security; package org.apache.activemq.security;
import java.net.URI;
import java.security.Principal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.net.ssl.SSLServerSocket;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.broker.Connector; import org.apache.activemq.broker.Connector;
import org.apache.activemq.broker.StubBroker; import org.apache.activemq.broker.StubBroker;
@ -25,17 +36,11 @@ import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.command.ConnectionInfo; import org.apache.activemq.command.ConnectionInfo;
import org.apache.activemq.jaas.GroupPrincipal; import org.apache.activemq.jaas.GroupPrincipal;
import org.apache.activemq.jaas.UserPrincipal; import org.apache.activemq.jaas.UserPrincipal;
import org.apache.activemq.transport.tcp.*; import org.apache.activemq.transport.tcp.SslTransportServer;
import org.apache.activemq.transport.tcp.StubSSLServerSocket;
import javax.net.ssl.SSLServerSocket; import org.apache.activemq.transport.tcp.StubSSLSocketFactory;
import javax.security.auth.login.AppConfigurationEntry; import org.apache.activemq.transport.tcp.StubX509Certificate;
import javax.security.auth.login.Configuration; import org.apache.activemq.transport.tcp.TcpTransportServer;
import java.net.URI;
import java.security.Principal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/** /**
* *
@ -81,6 +86,7 @@ public class JaasDualAuthenticationBrokerTest extends TestCase {
Configuration.setConfiguration(jaasConfig); Configuration.setConfiguration(jaasConfig);
} }
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
receiveBroker = new StubBroker(); receiveBroker = new StubBroker();
@ -112,6 +118,7 @@ public class JaasDualAuthenticationBrokerTest extends TestCase {
createLoginConfig(); createLoginConfig();
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
super.tearDown(); super.tearDown();
} }
@ -136,13 +143,13 @@ public class JaasDualAuthenticationBrokerTest extends TestCase {
assertEquals("The SecurityContext's userName must be set to that of the UserPrincipal.", assertEquals("The SecurityContext's userName must be set to that of the UserPrincipal.",
DN_USERNAME, receivedContext.getSecurityContext().getUserName()); DN_USERNAME, receivedContext.getSecurityContext().getUserName());
Set receivedPrincipals = receivedContext.getSecurityContext().getPrincipals(); Set<Principal> receivedPrincipals = receivedContext.getSecurityContext().getPrincipals();
assertEquals("2 Principals received", 2, receivedPrincipals.size()); assertEquals("2 Principals received", 2, receivedPrincipals.size());
for (Iterator iter = receivedPrincipals.iterator(); iter.hasNext();) { for (Iterator<Principal> iter = receivedPrincipals.iterator(); iter.hasNext();) {
Principal currentPrincipal = (Principal)iter.next(); Principal currentPrincipal = iter.next();
if (currentPrincipal instanceof UserPrincipal) { if (currentPrincipal instanceof UserPrincipal) {
assertEquals("UserPrincipal is '" + DN_USERNAME + "'", DN_USERNAME, currentPrincipal.getName()); assertEquals("UserPrincipal is '" + DN_USERNAME + "'", DN_USERNAME, currentPrincipal.getName());
@ -181,11 +188,11 @@ public class JaasDualAuthenticationBrokerTest extends TestCase {
assertEquals("The SecurityContext's userName must be set to that of the UserPrincipal.", assertEquals("The SecurityContext's userName must be set to that of the UserPrincipal.",
INSECURE_USERNAME, receivedContext.getSecurityContext().getUserName()); INSECURE_USERNAME, receivedContext.getSecurityContext().getUserName());
Set receivedPrincipals = receivedContext.getSecurityContext().getPrincipals(); Set<Principal> receivedPrincipals = receivedContext.getSecurityContext().getPrincipals();
assertEquals("2 Principals received", 2, receivedPrincipals.size()); assertEquals("2 Principals received", 2, receivedPrincipals.size());
for (Iterator iter = receivedPrincipals.iterator(); iter.hasNext();) { for (Iterator<Principal> iter = receivedPrincipals.iterator(); iter.hasNext();) {
Principal currentPrincipal = (Principal)iter.next(); Principal currentPrincipal = iter.next();
if (currentPrincipal instanceof UserPrincipal) { if (currentPrincipal instanceof UserPrincipal) {
assertEquals("UserPrincipal is '" + INSECURE_USERNAME + "'", assertEquals("UserPrincipal is '" + INSECURE_USERNAME + "'",

View File

@ -16,6 +16,17 @@
*/ */
package org.apache.activemq.security; package org.apache.activemq.security;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Set;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.directory.DirContext;
import org.apache.activemq.advisory.AdvisorySupport; import org.apache.activemq.advisory.AdvisorySupport;
import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQQueue;
@ -31,19 +42,8 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.directory.DirContext;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
* This test assumes setup like in file 'AMQauth.ldif'. Contents of this file is * This test assumes setup like in file 'AMQauth.ldif'. Contents of this file is attached below in comments.
* attached below in comments.
* *
* @author ngcutura * @author ngcutura
* *
@ -51,9 +51,7 @@ import static org.junit.Assert.assertTrue;
*/ */
@RunWith(FrameworkRunner.class) @RunWith(FrameworkRunner.class)
@CreateLdapServer(transports = { @CreateTransport(protocol = "LDAP") }) @CreateLdapServer(transports = { @CreateTransport(protocol = "LDAP") })
@ApplyLdifFiles( @ApplyLdifFiles("org/apache/activemq/security/AMQauth.ldif")
"org/apache/activemq/security/AMQauth.ldif"
)
public class LDAPAuthorizationMapTest extends AbstractLdapTestUnit { public class LDAPAuthorizationMapTest extends AbstractLdapTestUnit {
private static LDAPAuthorizationMap authMap; private static LDAPAuthorizationMap authMap;
@ -73,9 +71,9 @@ public class LDAPAuthorizationMapTest extends AbstractLdapTestUnit {
public void testOpen() throws Exception { public void testOpen() throws Exception {
DirContext ctx = authMap.open(); DirContext ctx = authMap.open();
HashSet<String> set = new HashSet<String>(); HashSet<String> set = new HashSet<String>();
NamingEnumeration list = ctx.list("ou=destinations,o=ActiveMQ,ou=system"); NamingEnumeration<NameClassPair> list = ctx.list("ou=destinations,o=ActiveMQ,ou=system");
while (list.hasMore()) { while (list.hasMore()) {
NameClassPair ncp = (NameClassPair) list.next(); NameClassPair ncp = list.next();
set.add(ncp.getName()); set.add(ncp.getName());
} }
assertTrue(set.contains("ou=topics")); assertTrue(set.contains("ou=topics"));
@ -83,53 +81,50 @@ public class LDAPAuthorizationMapTest extends AbstractLdapTestUnit {
} }
/* /*
* Test method for * Test method for 'org.apache.activemq.security.LDAPAuthorizationMap.getAdminACLs(ActiveMQDestination)'
* 'org.apache.activemq.security.LDAPAuthorizationMap.getAdminACLs(ActiveMQDestination)'
*/ */
@Test @Test
public void testGetAdminACLs() { public void testGetAdminACLs() {
ActiveMQDestination q1 = new ActiveMQQueue("queue1"); ActiveMQDestination q1 = new ActiveMQQueue("queue1");
Set aclsq1 = authMap.getAdminACLs(q1); Set<GroupPrincipal> aclsq1 = authMap.getAdminACLs(q1);
assertEquals(1, aclsq1.size()); assertEquals(1, aclsq1.size());
assertTrue(aclsq1.contains(new GroupPrincipal("role1"))); assertTrue(aclsq1.contains(new GroupPrincipal("role1")));
ActiveMQDestination t1 = new ActiveMQTopic("topic1"); ActiveMQDestination t1 = new ActiveMQTopic("topic1");
Set aclst1 = authMap.getAdminACLs(t1); Set<GroupPrincipal> aclst1 = authMap.getAdminACLs(t1);
assertEquals(1, aclst1.size()); assertEquals(1, aclst1.size());
assertTrue(aclst1.contains(new GroupPrincipal("role1"))); assertTrue(aclst1.contains(new GroupPrincipal("role1")));
} }
/* /*
* Test method for * Test method for 'org.apache.activemq.security.LDAPAuthorizationMap.getReadACLs(ActiveMQDestination)'
* 'org.apache.activemq.security.LDAPAuthorizationMap.getReadACLs(ActiveMQDestination)'
*/ */
@Test @Test
public void testGetReadACLs() { public void testGetReadACLs() {
ActiveMQDestination q1 = new ActiveMQQueue("queue1"); ActiveMQDestination q1 = new ActiveMQQueue("queue1");
Set aclsq1 = authMap.getReadACLs(q1); Set<GroupPrincipal> aclsq1 = authMap.getReadACLs(q1);
assertEquals(1, aclsq1.size()); assertEquals(1, aclsq1.size());
assertTrue(aclsq1.contains(new GroupPrincipal("role1"))); assertTrue(aclsq1.contains(new GroupPrincipal("role1")));
ActiveMQDestination t1 = new ActiveMQTopic("topic1"); ActiveMQDestination t1 = new ActiveMQTopic("topic1");
Set aclst1 = authMap.getReadACLs(t1); Set<GroupPrincipal> aclst1 = authMap.getReadACLs(t1);
assertEquals(1, aclst1.size()); assertEquals(1, aclst1.size());
assertTrue(aclst1.contains(new GroupPrincipal("role2"))); assertTrue(aclst1.contains(new GroupPrincipal("role2")));
} }
/* /*
* Test method for * Test method for 'org.apache.activemq.security.LDAPAuthorizationMap.getWriteACLs(ActiveMQDestination)'
* 'org.apache.activemq.security.LDAPAuthorizationMap.getWriteACLs(ActiveMQDestination)'
*/ */
@Test @Test
public void testGetWriteACLs() { public void testGetWriteACLs() {
ActiveMQDestination q1 = new ActiveMQQueue("queue1"); ActiveMQDestination q1 = new ActiveMQQueue("queue1");
Set aclsq1 = authMap.getWriteACLs(q1); Set<GroupPrincipal> aclsq1 = authMap.getWriteACLs(q1);
assertEquals(2, aclsq1.size()); assertEquals(2, aclsq1.size());
assertTrue(aclsq1.contains(new GroupPrincipal("role1"))); assertTrue(aclsq1.contains(new GroupPrincipal("role1")));
assertTrue(aclsq1.contains(new GroupPrincipal("role2"))); assertTrue(aclsq1.contains(new GroupPrincipal("role2")));
ActiveMQDestination t1 = new ActiveMQTopic("topic1"); ActiveMQDestination t1 = new ActiveMQTopic("topic1");
Set aclst1 = authMap.getWriteACLs(t1); Set<GroupPrincipal> aclst1 = authMap.getWriteACLs(t1);
assertEquals(1, aclst1.size()); assertEquals(1, aclst1.size());
assertTrue(aclst1.contains(new GroupPrincipal("role3"))); assertTrue(aclst1.contains(new GroupPrincipal("role3")));
} }
@ -137,14 +132,14 @@ public class LDAPAuthorizationMapTest extends AbstractLdapTestUnit {
@Test @Test
public void testComposite() { public void testComposite() {
ActiveMQDestination q1 = new ActiveMQQueue("queue1,topic://topic1"); ActiveMQDestination q1 = new ActiveMQQueue("queue1,topic://topic1");
Set aclsq1 = authMap.getWriteACLs(q1); Set<GroupPrincipal> aclsq1 = authMap.getWriteACLs(q1);
assertEquals(0, aclsq1.size()); assertEquals(0, aclsq1.size());
} }
@Test @Test
public void testAdvisory() { public void testAdvisory() {
ActiveMQDestination dest = AdvisorySupport.getConnectionAdvisoryTopic(); ActiveMQDestination dest = AdvisorySupport.getConnectionAdvisoryTopic();
Set acls = authMap.getWriteACLs(dest); Set<GroupPrincipal> acls = authMap.getWriteACLs(dest);
assertEquals(1, acls.size()); assertEquals(1, acls.size());
assertTrue(acls.contains(new GroupPrincipal("role3"))); assertTrue(acls.contains(new GroupPrincipal("role3")));
@ -152,11 +147,10 @@ public class LDAPAuthorizationMapTest extends AbstractLdapTestUnit {
@Test @Test
public void testTemp() { public void testTemp() {
Set acls = authMap.getTempDestinationAdminACLs(); Set<GroupPrincipal> acls = authMap.getTempDestinationAdminACLs();
assertEquals(1, acls.size()); assertEquals(1, acls.size());
assertTrue(acls.contains(new GroupPrincipal("role1"))); assertTrue(acls.contains(new GroupPrincipal("role1")));
} }
} }

View File

@ -16,10 +16,20 @@
*/ */
package org.apache.activemq.security; package org.apache.activemq.security;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.directory.server.annotations.CreateLdapServer; import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport; import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.annotations.ApplyLdifFiles; import org.apache.directory.server.core.annotations.ApplyLdifFiles;
@ -31,11 +41,6 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import javax.jms.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
@RunWith( FrameworkRunner.class ) @RunWith( FrameworkRunner.class )
@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP")}) @CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP")})

View File

@ -25,13 +25,9 @@ import org.apache.activemq.CombinationTestSupport;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.command.ActiveMQTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SimpleAnonymousPluginTest extends SimpleAuthenticationPluginTest { public class SimpleAnonymousPluginTest extends SimpleAuthenticationPluginTest {
private static final Logger LOG = LoggerFactory.getLogger(SimpleAnonymousPluginTest.class);
public static Test suite() { public static Test suite() {
return suite(SimpleAnonymousPluginTest.class); return suite(SimpleAnonymousPluginTest.class);
} }
@ -40,10 +36,12 @@ public class SimpleAnonymousPluginTest extends SimpleAuthenticationPluginTest {
junit.textui.TestRunner.run(suite()); junit.textui.TestRunner.run(suite());
} }
@Override
protected BrokerService createBroker() throws Exception { protected BrokerService createBroker() throws Exception {
return createBroker("org/apache/activemq/security/simple-anonymous-broker.xml"); return createBroker("org/apache/activemq/security/simple-anonymous-broker.xml");
} }
@Override
public void testInvalidAuthentication() throws JMSException { public void testInvalidAuthentication() throws JMSException {
try { try {

View File

@ -39,6 +39,8 @@ public class StubLoginModule implements LoginModule {
private String groupNames[]; private String groupNames[];
private boolean allowLogin; private boolean allowLogin;
@Override
@SuppressWarnings("rawtypes")
public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) { public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
String allowLoginString = (String)(options.get(ALLOW_LOGIN_PROPERTY)); String allowLoginString = (String)(options.get(ALLOW_LOGIN_PROPERTY));
String usersString = (String)(options.get(USERS_PROPERTY)); String usersString = (String)(options.get(USERS_PROPERTY));
@ -51,6 +53,7 @@ public class StubLoginModule implements LoginModule {
groupNames = groupsString.split(","); groupNames = groupsString.split(",");
} }
@Override
public boolean login() throws LoginException { public boolean login() throws LoginException {
if (!allowLogin) { if (!allowLogin) {
throw new FailedLoginException("Login was not allowed (as specified in configuration)."); throw new FailedLoginException("Login was not allowed (as specified in configuration).");
@ -59,6 +62,7 @@ public class StubLoginModule implements LoginModule {
return true; return true;
} }
@Override
public boolean commit() throws LoginException { public boolean commit() throws LoginException {
if (!allowLogin) { if (!allowLogin) {
throw new FailedLoginException("Login was not allowed (as specified in configuration)."); throw new FailedLoginException("Login was not allowed (as specified in configuration).");
@ -79,10 +83,12 @@ public class StubLoginModule implements LoginModule {
return true; return true;
} }
@Override
public boolean abort() throws LoginException { public boolean abort() throws LoginException {
return true; return true;
} }
@Override
public boolean logout() throws LoginException { public boolean logout() throws LoginException {
subject.getPrincipals().clear(); subject.getPrincipals().clear();

View File

@ -17,13 +17,13 @@
package org.apache.activemq.selector; package org.apache.activemq.selector;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.activemq.filter.BooleanExpression; import org.apache.activemq.filter.BooleanExpression;
import org.apache.activemq.filter.ComparisonExpression; import org.apache.activemq.filter.ComparisonExpression;
import org.apache.activemq.filter.Expression; import org.apache.activemq.filter.Expression;
import org.apache.activemq.filter.LogicExpression; import org.apache.activemq.filter.LogicExpression;
import org.apache.activemq.filter.PropertyExpression; import org.apache.activemq.filter.PropertyExpression;
import org.apache.activemq.filter.XPathExpression; import org.apache.activemq.filter.XPathExpression;
import org.apache.activemq.spring.ConsumerBean;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;

View File

@ -21,6 +21,7 @@ import javax.jms.JMSException;
import javax.jms.Message; import javax.jms.Message;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.activemq.command.ActiveMQMessage; import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.ActiveMQTextMessage; import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.command.ActiveMQTopic;
@ -272,44 +273,21 @@ public class SelectorTest extends TestCase {
public void testFloatComparisons() throws Exception { public void testFloatComparisons() throws Exception {
Message message = createMessage(); Message message = createMessage();
// JMS 1.1 Section 3.8.1.1 : Approximate literals use the Java
// floating-point literal syntax.
// We will use the java varible x to demo valid floating point syntaxs.
double x;
// test decimals like x.x
x = 1.0;
x = -1.1;
x = 1.0E1;
x = 1.1E1;
x = -1.1E1;
assertSelector(message, "1.0 < 1.1", true); assertSelector(message, "1.0 < 1.1", true);
assertSelector(message, "-1.1 < 1.0", true); assertSelector(message, "-1.1 < 1.0", true);
assertSelector(message, "1.0E1 < 1.1E1", true); assertSelector(message, "1.0E1 < 1.1E1", true);
assertSelector(message, "-1.1E1 < 1.0E1", true); assertSelector(message, "-1.1E1 < 1.0E1", true);
// test decimals like x.
x = 1.;
x = 1.E1;
assertSelector(message, "1. < 1.1", true); assertSelector(message, "1. < 1.1", true);
assertSelector(message, "-1.1 < 1.", true); assertSelector(message, "-1.1 < 1.", true);
assertSelector(message, "1.E1 < 1.1E1", true); assertSelector(message, "1.E1 < 1.1E1", true);
assertSelector(message, "-1.1E1 < 1.E1", true); assertSelector(message, "-1.1E1 < 1.E1", true);
// test decimals like .x
x = .5;
x = -.5;
x = .5E1;
assertSelector(message, ".1 < .5", true); assertSelector(message, ".1 < .5", true);
assertSelector(message, "-.5 < .1", true); assertSelector(message, "-.5 < .1", true);
assertSelector(message, ".1E1 < .5E1", true); assertSelector(message, ".1E1 < .5E1", true);
assertSelector(message, "-.5E1 < .1E1", true); assertSelector(message, "-.5E1 < .1E1", true);
// test exponents
x = 4E10;
x = -4E10;
x = 5E+10;
x = 5E-10;
assertSelector(message, "4E10 < 5E10", true); assertSelector(message, "4E10 < 5E10", true);
assertSelector(message, "5E8 < 5E10", true); assertSelector(message, "5E8 < 5E10", true);
assertSelector(message, "-4E10 < 2E10", true); assertSelector(message, "-4E10 < 2E10", true);
@ -361,10 +339,10 @@ public class SelectorTest extends TestCase {
message.setByteProperty("byteProp", (byte)123); message.setByteProperty("byteProp", (byte)123);
message.setByteProperty("byteProp2", (byte)33); message.setByteProperty("byteProp2", (byte)33);
message.setShortProperty("shortProp", (short)123); message.setShortProperty("shortProp", (short)123);
message.setIntProperty("intProp", (int)123); message.setIntProperty("intProp", 123);
message.setLongProperty("longProp", (long)123); message.setLongProperty("longProp", 123);
message.setFloatProperty("floatProp", (float)123); message.setFloatProperty("floatProp", 123);
message.setDoubleProperty("doubleProp", (double)123); message.setDoubleProperty("doubleProp", 123);
message.setIntProperty("rank", 123); message.setIntProperty("rank", 123);
message.setIntProperty("version", 2); message.setIntProperty("version", 2);

View File

@ -22,7 +22,7 @@ import java.util.List;
import javax.jms.Message; import javax.jms.Message;
import javax.jms.MessageListener; import javax.jms.MessageListener;
import junit.framework.Assert; import org.junit.Assert;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -37,7 +37,6 @@ public class ConsumerBean extends Assert implements MessageListener {
public ConsumerBean() { public ConsumerBean() {
} }
/** /**
* @return all the messages on the list so far, clearing the buffer * @return all the messages on the list so far, clearing the buffer
*/ */
@ -55,6 +54,7 @@ public class ConsumerBean extends Assert implements MessageListener {
* *
* @param message * @param message
*/ */
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
synchronized (messages) { synchronized (messages) {
messages.add(message); messages.add(message);

View File

@ -19,8 +19,10 @@ package org.apache.activemq.spring;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import javax.jms.Message;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.activemq.test.JmsTopicSendReceiveTest;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.AbstractApplicationContext;
@ -64,9 +66,9 @@ public class SpringTestSupport extends TestCase {
consumer.waitForMessagesToArrive(producer.getMessageCount()); consumer.waitForMessagesToArrive(producer.getMessageCount());
// now lets check that the consumer has received some messages // now lets check that the consumer has received some messages
List messages = consumer.flushMessages(); List<Message> messages = consumer.flushMessages();
LOG.info("Consumer has received messages...."); LOG.info("Consumer has received messages....");
for (Iterator iter = messages.iterator(); iter.hasNext();) { for (Iterator<Message> iter = messages.iterator(); iter.hasNext();) {
Object message = iter.next(); Object message = iter.next();
LOG.info("Received: " + message); LOG.info("Received: " + message);
} }
@ -79,6 +81,7 @@ public class SpringTestSupport extends TestCase {
* *
* @throws Exception * @throws Exception
*/ */
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
if (consumer != null) { if (consumer != null) {
consumer.stop(); consumer.stop();

View File

@ -67,6 +67,7 @@ abstract public class MessagePriorityTest extends CombinationTestSupport {
abstract protected PersistenceAdapter createPersistenceAdapter(boolean delete) throws Exception; abstract protected PersistenceAdapter createPersistenceAdapter(boolean delete) throws Exception;
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
broker = new BrokerService(); broker = new BrokerService();
broker.setBrokerName("priorityTest"); broker.setBrokerName("priorityTest");
@ -109,6 +110,7 @@ abstract public class MessagePriorityTest extends CombinationTestSupport {
sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
try { try {
sess.close(); sess.close();
@ -160,6 +162,7 @@ abstract public class MessagePriorityTest extends CombinationTestSupport {
this.dest = dest; this.dest = dest;
} }
@Override
public void run() { public void run() {
try { try {
MessageProducer producer = sess.createProducer(dest); MessageProducer producer = sess.createProducer(dest);
@ -414,7 +417,6 @@ abstract public class MessagePriorityTest extends CombinationTestSupport {
LOG.info("Ordered priority messages sent"); LOG.info("Ordered priority messages sent");
sub = sess.createDurableSubscriber(topic, subName); sub = sess.createDurableSubscriber(topic, subName);
int count = 0;
Message msg = sub.receive(15000); Message msg = sub.receive(15000);
assertNotNull("Message was null", msg); assertNotNull("Message was null", msg);

View File

@ -16,11 +16,11 @@
*/ */
package org.apache.activemq.store.jdbc; package org.apache.activemq.store.jdbc;
import static org.junit.Assert.assertEquals;
import org.apache.activemq.broker.AbstractLocker; import org.apache.activemq.broker.AbstractLocker;
import org.junit.Test; import org.junit.Test;
import static junit.framework.Assert.assertEquals;
public class DatabaseLockerConfigTest { public class DatabaseLockerConfigTest {
@Test @Test

View File

@ -24,6 +24,7 @@ import java.util.HashMap;
import java.util.Vector; import java.util.Vector;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import javax.jms.Connection; import javax.jms.Connection;
import javax.jms.DeliveryMode; import javax.jms.DeliveryMode;
import javax.jms.Message; import javax.jms.Message;
@ -32,15 +33,17 @@ import javax.jms.MessageProducer;
import javax.jms.Session; import javax.jms.Session;
import javax.jms.TextMessage; import javax.jms.TextMessage;
import javax.jms.TopicSubscriber; import javax.jms.TopicSubscriber;
import junit.framework.Test; import junit.framework.Test;
import org.apache.activemq.command.ActiveMQMessage; import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.store.MessagePriorityTest; import org.apache.activemq.store.MessagePriorityTest;
import org.apache.activemq.store.PersistenceAdapter; import org.apache.activemq.store.PersistenceAdapter;
import org.apache.activemq.util.Wait; import org.apache.activemq.util.Wait;
import org.apache.derby.jdbc.EmbeddedDataSource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.apache.derby.jdbc.EmbeddedDataSource;
public class JDBCMessagePriorityTest extends MessagePriorityTest { public class JDBCMessagePriorityTest extends MessagePriorityTest {
@ -62,6 +65,7 @@ public class JDBCMessagePriorityTest extends MessagePriorityTest {
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
super.tearDown(); super.tearDown();
try { try {
@ -154,7 +158,7 @@ public class JDBCMessagePriorityTest extends MessagePriorityTest {
} }
final int closeFrequency = MSG_NUM / 2; final int closeFrequency = MSG_NUM / 2;
HashMap dups = new HashMap(); HashMap<String, String> dups = new HashMap<String, String>();
sub = consumerSession.createDurableSubscriber(topic, subName); sub = consumerSession.createDurableSubscriber(topic, subName);
for (int i = 0; i < MSG_NUM * maxPriority; i++) { for (int i = 0; i < MSG_NUM * maxPriority; i++) {
Message msg = sub.receive(10000); Message msg = sub.receive(10000);
@ -228,6 +232,7 @@ public class JDBCMessagePriorityTest extends MessagePriorityTest {
sub = consumerSession.createDurableSubscriber(topic, subName); sub = consumerSession.createDurableSubscriber(topic, subName);
final AtomicInteger count = new AtomicInteger(); final AtomicInteger count = new AtomicInteger();
sub.setMessageListener(new MessageListener() { sub.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
try { try {
count.incrementAndGet(); count.incrementAndGet();
@ -273,6 +278,7 @@ public class JDBCMessagePriorityTest extends MessagePriorityTest {
assertTrue("max X times as slow with consumer:" + withConsumerAve + " , noConsumerMax:" + noConsumerAve, assertTrue("max X times as slow with consumer:" + withConsumerAve + " , noConsumerMax:" + noConsumerAve,
withConsumerAve < noConsumerAve * reasonableMultiplier); withConsumerAve < noConsumerAve * reasonableMultiplier);
Wait.waitFor(new Wait.Condition() { Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
LOG.info("count: " + count.get()); LOG.info("count: " + count.get());
return TO_SEND * 2 == count.get(); return TO_SEND * 2 == count.get();
@ -422,6 +428,7 @@ public class JDBCMessagePriorityTest extends MessagePriorityTest {
})); }));
} }
@SuppressWarnings("unused")
private int messageTableDump() throws Exception { private int messageTableDump() throws Exception {
int count = -1; int count = -1;
java.sql.Connection c = dataSource.getConnection(); java.sql.Connection c = dataSource.getConnection();

View File

@ -20,16 +20,10 @@ package org.apache.activemq.store.jdbc;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import javax.jms.DeliveryMode;
import javax.jms.Destination; import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message; import javax.jms.Message;
import javax.jms.MessageConsumer; import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.XAConnection; import javax.jms.XAConnection;
import javax.jms.XASession; import javax.jms.XASession;
import javax.transaction.xa.XAException; import javax.transaction.xa.XAException;
@ -40,8 +34,6 @@ import org.apache.activemq.ActiveMQXAConnectionFactory;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import junit.framework.TestCase;
// https://issues.apache.org/activemq/browse/AMQ-2880 // https://issues.apache.org/activemq/browse/AMQ-2880
public class JDBCXACommitExceptionTest extends JDBCCommitExceptionTest { public class JDBCXACommitExceptionTest extends JDBCCommitExceptionTest {
private static final Logger LOG = LoggerFactory.getLogger(JDBCXACommitExceptionTest.class); private static final Logger LOG = LoggerFactory.getLogger(JDBCXACommitExceptionTest.class);
@ -138,14 +130,17 @@ public class JDBCXACommitExceptionTest extends JDBCCommitExceptionTest {
final byte[] bs = baos.toByteArray(); final byte[] bs = baos.toByteArray();
return new Xid() { return new Xid() {
@Override
public int getFormatId() { public int getFormatId() {
return 86; return 86;
} }
@Override
public byte[] getGlobalTransactionId() { public byte[] getGlobalTransactionId() {
return bs; return bs;
} }
@Override
public byte[] getBranchQualifier() { public byte[] getBranchQualifier() {
return bs; return bs;
} }

View File

@ -16,6 +16,10 @@
*/ */
package org.apache.activemq.store.jdbc; package org.apache.activemq.store.jdbc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.util.HashSet; import java.util.HashSet;
@ -24,6 +28,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.activemq.broker.AbstractLocker; import org.apache.activemq.broker.AbstractLocker;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.store.jdbc.adapter.DefaultJDBCAdapter; import org.apache.activemq.store.jdbc.adapter.DefaultJDBCAdapter;
@ -33,10 +38,6 @@ import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static junit.framework.Assert.*;
public class LeaseDatabaseLockerTest { public class LeaseDatabaseLockerTest {
private static final Logger LOG = LoggerFactory.getLogger(LeaseDatabaseLockerTest.class); private static final Logger LOG = LoggerFactory.getLogger(LeaseDatabaseLockerTest.class);
@ -190,6 +191,6 @@ public class LeaseDatabaseLockerTest {
} }
private void printLockTable(Connection connection) throws Exception { private void printLockTable(Connection connection) throws Exception {
((DefaultJDBCAdapter)jdbc.getAdapter()).printQuery(connection, "SELECT * from ACTIVEMQ_LOCK", System.err); DefaultJDBCAdapter.printQuery(connection, "SELECT * from ACTIVEMQ_LOCK", System.err);
} }
} }

View File

@ -16,11 +16,17 @@
*/ */
package org.apache.activemq.store.kahadb; package org.apache.activemq.store.kahadb;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Vector; import java.util.Vector;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import javax.jms.BytesMessage; import javax.jms.BytesMessage;
import javax.jms.DeliveryMode; import javax.jms.DeliveryMode;
import javax.jms.Destination; import javax.jms.Destination;
@ -28,6 +34,7 @@ import javax.jms.Message;
import javax.jms.MessageConsumer; import javax.jms.MessageConsumer;
import javax.jms.MessageProducer; import javax.jms.MessageProducer;
import javax.jms.Session; import javax.jms.Session;
import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
@ -41,19 +48,16 @@ import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static junit.framework.Assert.*;
public class KahaDBFastEnqueueTest { public class KahaDBFastEnqueueTest {
private static final Logger LOG = LoggerFactory.getLogger(KahaDBFastEnqueueTest.class); private static final Logger LOG = LoggerFactory.getLogger(KahaDBFastEnqueueTest.class);
private BrokerService broker; private BrokerService broker;
private ActiveMQConnectionFactory connectionFactory; private ActiveMQConnectionFactory connectionFactory;
KahaDBPersistenceAdapter kahaDBPersistenceAdapter; KahaDBPersistenceAdapter kahaDBPersistenceAdapter;
private Destination destination = new ActiveMQQueue("Test"); private final Destination destination = new ActiveMQQueue("Test");
private String payloadString = new String(new byte[6*1024]); private final String payloadString = new String(new byte[6*1024]);
private boolean useBytesMessage= true; private final boolean useBytesMessage= true;
private final int parallelProducer = 20; private final int parallelProducer = 20;
private Vector<Exception> exceptions = new Vector<Exception>(); private final Vector<Exception> exceptions = new Vector<Exception>();
long toSend = 10000; long toSend = 10000;
// use with: // use with:

View File

@ -16,16 +16,24 @@
*/ */
package org.apache.activemq.store.kahadb; package org.apache.activemq.store.kahadb;
import junit.framework.Test;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.RecoveryBrokerTest;
import org.apache.activemq.broker.StubConnection;
import org.apache.activemq.command.*;
import java.io.File; import java.io.File;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
import java.util.ArrayList; import java.util.ArrayList;
import junit.framework.Test;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.RecoveryBrokerTest;
import org.apache.activemq.broker.StubConnection;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ConnectionInfo;
import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageAck;
import org.apache.activemq.command.ProducerInfo;
import org.apache.activemq.command.SessionInfo;
/** /**
* Used to verify that recovery works correctly against * Used to verify that recovery works correctly against
@ -37,6 +45,7 @@ public class KahaDBStoreRecoveryBrokerTest extends RecoveryBrokerTest {
enum CorruptionType { None, FailToLoad, LoadInvalid, LoadCorrupt }; enum CorruptionType { None, FailToLoad, LoadInvalid, LoadCorrupt };
public CorruptionType failTest = CorruptionType.None; public CorruptionType failTest = CorruptionType.None;
@Override
protected BrokerService createBroker() throws Exception { protected BrokerService createBroker() throws Exception {
BrokerService broker = new BrokerService(); BrokerService broker = new BrokerService();
KahaDBStore kaha = new KahaDBStore(); KahaDBStore kaha = new KahaDBStore();
@ -46,6 +55,8 @@ public class KahaDBStoreRecoveryBrokerTest extends RecoveryBrokerTest {
return broker; return broker;
} }
@Override
@SuppressWarnings("resource")
protected BrokerService createRestartedBroker() throws Exception { protected BrokerService createRestartedBroker() throws Exception {
// corrupting index // corrupting index

View File

@ -16,13 +16,18 @@
*/ */
package org.apache.activemq.store.kahadb; package org.apache.activemq.store.kahadb;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.jms.ConnectionFactory; import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode; import javax.jms.DeliveryMode;
import javax.jms.Destination; import javax.jms.Destination;
import javax.jms.MessageConsumer; import javax.jms.MessageConsumer;
import javax.jms.MessageProducer; import javax.jms.MessageProducer;
import javax.jms.Session; import javax.jms.Session;
import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
@ -35,15 +40,11 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
public class KahaDBStoreRecoveryExpiryTest { public class KahaDBStoreRecoveryExpiryTest {
private BrokerService broker; private BrokerService broker;
private ActiveMQConnection connection; private ActiveMQConnection connection;
private Destination destination = new ActiveMQQueue("Test"); private final Destination destination = new ActiveMQQueue("Test");
private Session session; private Session session;
@Test @Test

View File

@ -16,16 +16,21 @@
*/ */
package org.apache.activemq.store.kahadb; package org.apache.activemq.store.kahadb;
import junit.framework.TestCase;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import javax.jms.*;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
import java.io.FileNotFoundException;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.command.ActiveMQQueue;
/** /**
* @author chirino * @author chirino
@ -39,7 +44,6 @@ public class KahaDBTest extends TestCase {
broker.setPersistenceAdapter(kaha); broker.setPersistenceAdapter(kaha);
broker.start(); broker.start();
return broker; return broker;
} }
private KahaDBStore createStore(boolean delete) throws IOException { private KahaDBStore createStore(boolean delete) throws IOException {

View File

@ -23,14 +23,15 @@ import junit.framework.TestCase;
import org.apache.activemq.protobuf.Buffer; import org.apache.activemq.protobuf.Buffer;
import org.apache.activemq.store.kahadb.data.KahaAddMessageCommand; import org.apache.activemq.store.kahadb.data.KahaAddMessageCommand;
import org.apache.activemq.store.kahadb.data.KahaDestination; import org.apache.activemq.store.kahadb.data.KahaDestination;
import org.apache.activemq.store.kahadb.data.KahaEntryType;
import org.apache.activemq.store.kahadb.data.KahaDestination.DestinationType; import org.apache.activemq.store.kahadb.data.KahaDestination.DestinationType;
import org.apache.activemq.store.kahadb.data.KahaEntryType;
import org.apache.activemq.util.ByteSequence; import org.apache.activemq.util.ByteSequence;
import org.apache.activemq.util.DataByteArrayInputStream; import org.apache.activemq.util.DataByteArrayInputStream;
import org.apache.activemq.util.DataByteArrayOutputStream; import org.apache.activemq.util.DataByteArrayOutputStream;
public class PBMesssagesTest extends TestCase { public class PBMesssagesTest extends TestCase {
@SuppressWarnings("rawtypes")
public void testKahaAddMessageCommand() throws IOException { public void testKahaAddMessageCommand() throws IOException {
KahaAddMessageCommand expected = new KahaAddMessageCommand(); KahaAddMessageCommand expected = new KahaAddMessageCommand();

View File

@ -20,12 +20,10 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.jms.BytesMessage; import javax.jms.BytesMessage;
import javax.jms.ConnectionFactory; import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode; import javax.jms.DeliveryMode;
import javax.jms.Message;
import javax.jms.MessageConsumer; import javax.jms.MessageConsumer;
import javax.jms.MessageProducer; import javax.jms.MessageProducer;
import javax.jms.Session; import javax.jms.Session;
@ -35,13 +33,11 @@ import junit.framework.Test;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.JmsTestSupport; import org.apache.activemq.JmsTestSupport;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.ProgressPrinter;
import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.store.kahadb.KahaDBStore;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.apache.activemq.store.kahadb.KahaDBStore;
/** /**
* This tests bulk loading and unloading of messages to a Queue.s * This tests bulk loading and unloading of messages to a Queue.s
@ -54,6 +50,7 @@ public class KahaBulkLoadingTest extends JmsTestSupport {
protected int messageSize = 1024 * 4; protected int messageSize = 1024 * 4;
@Override
protected BrokerService createBroker() throws Exception { protected BrokerService createBroker() throws Exception {
BrokerService broker = new BrokerService(); BrokerService broker = new BrokerService();
KahaDBStore kaha = new KahaDBStore(); KahaDBStore kaha = new KahaDBStore();
@ -64,8 +61,9 @@ public class KahaBulkLoadingTest extends JmsTestSupport {
return broker; return broker;
} }
@Override
protected ConnectionFactory createConnectionFactory() throws URISyntaxException, IOException { protected ConnectionFactory createConnectionFactory() throws URISyntaxException, IOException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(((TransportConnector)broker.getTransportConnectors().get(0)).getServer().getConnectURI()); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getServer().getConnectURI());
factory.setUseAsyncSend(true); factory.setUseAsyncSend(true);
return factory; return factory;
} }

View File

@ -31,12 +31,13 @@ import org.slf4j.LoggerFactory;
/** /**
* Tests that a Message can have nested Map and List properties attached. * Tests that a Message can have nested Map and List properties attached.
* *
*
*/ */
public class NestedMapAndListPropertyTest extends JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest { public class NestedMapAndListPropertyTest extends JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest {
private static final Logger LOG = LoggerFactory.getLogger(NestedMapAndListPropertyTest.class); private static final Logger LOG = LoggerFactory.getLogger(NestedMapAndListPropertyTest.class);
@Override
@SuppressWarnings("rawtypes")
protected void assertMessageValid(int index, Message message) throws JMSException { protected void assertMessageValid(int index, Message message) throws JMSException {
Object value = message.getObjectProperty("textField"); Object value = message.getObjectProperty("textField");
assertEquals("textField", data[index], value); assertEquals("textField", data[index], value);
@ -69,6 +70,7 @@ public class NestedMapAndListPropertyTest extends JmsTopicSendReceiveWithTwoConn
assertEquals("JohnDoe", message.getStringProperty("JMSXUserID")); assertEquals("JohnDoe", message.getStringProperty("JMSXUserID"));
} }
@Override
protected Message createMessage(int index) throws JMSException { protected Message createMessage(int index) throws JMSException {
Message answer = session.createMessage(); Message answer = session.createMessage();
@ -90,5 +92,4 @@ public class NestedMapAndListPropertyTest extends JmsTopicSendReceiveWithTwoConn
return answer; return answer;
} }
} }

View File

@ -36,6 +36,8 @@ public class NestedMapMessageTest extends JmsTopicSendReceiveWithTwoConnectionsA
private static final Logger LOG = LoggerFactory.getLogger(NestedMapMessageTest.class); private static final Logger LOG = LoggerFactory.getLogger(NestedMapMessageTest.class);
@Override
@SuppressWarnings("rawtypes")
protected void assertMessageValid(int index, Message message) throws JMSException { protected void assertMessageValid(int index, Message message) throws JMSException {
assertTrue("Should be a MapMessage: " + message, message instanceof MapMessage); assertTrue("Should be a MapMessage: " + message, message instanceof MapMessage);
@ -71,6 +73,7 @@ public class NestedMapMessageTest extends JmsTopicSendReceiveWithTwoConnectionsA
assertEquals("listField[2]", "c", list.get(2)); assertEquals("listField[2]", "c", list.get(2));
} }
@Override
protected Message createMessage(int index) throws JMSException { protected Message createMessage(int index) throws JMSException {
MapMessage answer = session.createMapMessage(); MapMessage answer = session.createMapMessage();

View File

@ -31,7 +31,6 @@ import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.EmbeddedBrokerTestSupport; import org.apache.activemq.EmbeddedBrokerTestSupport;
import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.test.TemporaryDestinationToFromNameTest;
import org.apache.activemq.util.MessageIdList; import org.apache.activemq.util.MessageIdList;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -72,12 +71,14 @@ public class RetroactiveConsumerTestWithSimpleMessageListTest extends EmbeddedBr
} }
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
useTopic = true; useTopic = true;
bindAddress = "vm://localhost"; bindAddress = "vm://localhost";
super.setUp(); super.setUp();
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
if (session != null) { if (session != null) {
session.close(); session.close();
@ -89,18 +90,21 @@ public class RetroactiveConsumerTestWithSimpleMessageListTest extends EmbeddedBr
super.tearDown(); super.tearDown();
} }
@Override
protected ConnectionFactory createConnectionFactory() throws Exception { protected ConnectionFactory createConnectionFactory() throws Exception {
ActiveMQConnectionFactory answer = new ActiveMQConnectionFactory(bindAddress); ActiveMQConnectionFactory answer = new ActiveMQConnectionFactory(bindAddress);
answer.setUseRetroactiveConsumer(true); answer.setUseRetroactiveConsumer(true);
return answer; return answer;
} }
@Override
protected BrokerService createBroker() throws Exception { protected BrokerService createBroker() throws Exception {
String uri = getBrokerXml(); String uri = getBrokerXml();
LOG.info("Loading broker configuration from the classpath with URI: " + uri); LOG.info("Loading broker configuration from the classpath with URI: " + uri);
return BrokerFactory.createBroker(new URI("xbean:" + uri)); return BrokerFactory.createBroker(new URI("xbean:" + uri));
} }
@Override
protected void startBroker() throws Exception { protected void startBroker() throws Exception {
// broker already started by XBean // broker already started by XBean
} }

View File

@ -30,7 +30,6 @@ import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.EmbeddedBrokerTestSupport; import org.apache.activemq.EmbeddedBrokerTestSupport;
import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.usecases.CreateLotsOfTemporaryQueuesTest;
import org.apache.activemq.util.MessageIdList; import org.apache.activemq.util.MessageIdList;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -69,12 +68,14 @@ public class RetroactiveConsumerWithMessageQueryTest extends EmbeddedBrokerTestS
listener.assertMessagesReceived(messageCount); listener.assertMessagesReceived(messageCount);
} }
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
useTopic = true; useTopic = true;
bindAddress = "vm://localhost"; bindAddress = "vm://localhost";
super.setUp(); super.setUp();
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
if (session != null) { if (session != null) {
session.close(); session.close();
@ -86,6 +87,7 @@ public class RetroactiveConsumerWithMessageQueryTest extends EmbeddedBrokerTestS
super.tearDown(); super.tearDown();
} }
@Override
protected ConnectionFactory createConnectionFactory() throws Exception { protected ConnectionFactory createConnectionFactory() throws Exception {
ActiveMQConnectionFactory answer = new ActiveMQConnectionFactory(bindAddress); ActiveMQConnectionFactory answer = new ActiveMQConnectionFactory(bindAddress);
// answer.setUseRetroactiveConsumer(true); // answer.setUseRetroactiveConsumer(true);
@ -93,12 +95,14 @@ public class RetroactiveConsumerWithMessageQueryTest extends EmbeddedBrokerTestS
return answer; return answer;
} }
@Override
protected BrokerService createBroker() throws Exception { protected BrokerService createBroker() throws Exception {
String uri = getBrokerXml(); String uri = getBrokerXml();
LOG.info("Loading broker configuration from the classpath with URI: " + uri); LOG.info("Loading broker configuration from the classpath with URI: " + uri);
return BrokerFactory.createBroker(new URI("xbean:" + uri)); return BrokerFactory.createBroker(new URI("xbean:" + uri));
} }
@Override
protected void startBroker() throws Exception { protected void startBroker() throws Exception {
// broker already started by XBean // broker already started by XBean
} }

View File

@ -26,28 +26,32 @@ import java.util.concurrent.ConcurrentLinkedQueue;
*/ */
public class StubTransportListener implements TransportListener { public class StubTransportListener implements TransportListener {
private Queue commands = new ConcurrentLinkedQueue(); private final Queue<Object> commands = new ConcurrentLinkedQueue<Object>();
private Queue exceptions = new ConcurrentLinkedQueue(); private final Queue<Object> exceptions = new ConcurrentLinkedQueue<Object>();
public Queue getCommands() { public Queue<Object> getCommands() {
return commands; return commands;
} }
public Queue getExceptions() { public Queue<Object> getExceptions() {
return exceptions; return exceptions;
} }
@Override
public void onCommand(Object command) { public void onCommand(Object command) {
commands.add(command); commands.add(command);
} }
@Override
public void onException(IOException error) { public void onException(IOException error) {
exceptions.add(error); exceptions.add(error);
} }
@Override
public void transportInterupted() { public void transportInterupted() {
} }
@Override
public void transportResumed() { public void transportResumed() {
} }

View File

@ -21,6 +21,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import javax.jms.Connection; import javax.jms.Connection;
import javax.jms.JMSException; import javax.jms.JMSException;
import javax.jms.Message; import javax.jms.Message;
@ -30,6 +31,7 @@ import javax.jms.MessageProducer;
import javax.jms.Queue; import javax.jms.Queue;
import javax.jms.Session; import javax.jms.Session;
import javax.jms.TextMessage; import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.TestSupport; import org.apache.activemq.TestSupport;
import org.apache.activemq.broker.BrokerPlugin; import org.apache.activemq.broker.BrokerPlugin;
@ -49,7 +51,7 @@ public class FailoverDuplicateTest extends TestSupport {
private String url; private String url;
BrokerService broker; BrokerService broker;
@Override
public void tearDown() throws Exception { public void tearDown() throws Exception {
stopBroker(); stopBroker();
} }
@ -60,10 +62,6 @@ public class FailoverDuplicateTest extends TestSupport {
} }
} }
private void startCleanBroker() throws Exception {
startBroker(true);
}
public void startBroker(boolean deleteAllMessagesOnStartup) throws Exception { public void startBroker(boolean deleteAllMessagesOnStartup) throws Exception {
broker = createBroker(deleteAllMessagesOnStartup); broker = createBroker(deleteAllMessagesOnStartup);
broker.start(); broker.start();
@ -115,6 +113,7 @@ public class FailoverDuplicateTest extends TestSupport {
if (first.compareAndSet(false, true)) { if (first.compareAndSet(false, true)) {
producerExchange.getConnectionContext().setDontSendReponse(true); producerExchange.getConnectionContext().setDontSendReponse(true);
Executors.newSingleThreadExecutor().execute(new Runnable() { Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() { public void run() {
try { try {
LOG.info("Waiting for recepit"); LOG.info("Waiting for recepit");
@ -160,6 +159,7 @@ public class FailoverDuplicateTest extends TestSupport {
final CountDownLatch sendDoneLatch = new CountDownLatch(1); final CountDownLatch sendDoneLatch = new CountDownLatch(1);
// broker will die on send reply so this will hang till restart // broker will die on send reply so this will hang till restart
Executors.newSingleThreadExecutor().execute(new Runnable() { Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() { public void run() {
LOG.info("doing async send..."); LOG.info("doing async send...");
try { try {

View File

@ -40,8 +40,6 @@ public class FailoverTransportBackupsTest {
protected Transport transport; protected Transport transport;
protected FailoverTransport failoverTransport; protected FailoverTransport failoverTransport;
private int commandsReceived;
private int exceptionReceived;
private int transportInterruptions; private int transportInterruptions;
private int transportResumptions; private int transportResumptions;
@ -64,8 +62,6 @@ public class FailoverTransportBackupsTest {
broker3.waitUntilStarted(); broker3.waitUntilStarted();
// Reset stats // Reset stats
commandsReceived = 0;
exceptionReceived = 0;
transportInterruptions = 0; transportInterruptions = 0;
transportResumptions = 0; transportResumptions = 0;
} }
@ -92,6 +88,7 @@ public class FailoverTransportBackupsTest {
assertEquals(2, failoverTransport.getBackupPoolSize()); assertEquals(2, failoverTransport.getBackupPoolSize());
assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){ assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups());
return failoverTransport.getCurrentBackups() == 2; return failoverTransport.getCurrentBackups() == 2;
@ -107,6 +104,7 @@ public class FailoverTransportBackupsTest {
assertEquals(2, failoverTransport.getBackupPoolSize()); assertEquals(2, failoverTransport.getBackupPoolSize());
assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){ assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups());
return failoverTransport.getCurrentBackups() == 2; return failoverTransport.getCurrentBackups() == 2;
@ -116,6 +114,7 @@ public class FailoverTransportBackupsTest {
broker1.stop(); broker1.stop();
assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){ assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups());
return failoverTransport.getCurrentBackups() == 1; return failoverTransport.getCurrentBackups() == 1;
@ -128,6 +127,7 @@ public class FailoverTransportBackupsTest {
broker2.stop(); broker2.stop();
assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){ assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups());
return failoverTransport.getCurrentBackups() == 0; return failoverTransport.getCurrentBackups() == 0;
@ -146,6 +146,7 @@ public class FailoverTransportBackupsTest {
assertEquals(1, failoverTransport.getBackupPoolSize()); assertEquals(1, failoverTransport.getBackupPoolSize());
assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){ assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups());
return failoverTransport.getCurrentBackups() == 1; return failoverTransport.getCurrentBackups() == 1;
@ -155,6 +156,7 @@ public class FailoverTransportBackupsTest {
broker1.stop(); broker1.stop();
assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){ assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups());
return failoverTransport.getCurrentBackups() == 1; return failoverTransport.getCurrentBackups() == 1;
@ -164,6 +166,7 @@ public class FailoverTransportBackupsTest {
broker2.stop(); broker2.stop();
assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){ assertTrue("Timed out waiting for Backups to connect.", Wait.waitFor(new Wait.Condition(){
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups()); LOG.debug("Current Backup Count = " + failoverTransport.getCurrentBackups());
return failoverTransport.getCurrentBackups() == 0; return failoverTransport.getCurrentBackups() == 0;
@ -193,21 +196,23 @@ public class FailoverTransportBackupsTest {
Transport transport = TransportFactory.connect(new URI(connectionUri)); Transport transport = TransportFactory.connect(new URI(connectionUri));
transport.setTransportListener(new TransportListener() { transport.setTransportListener(new TransportListener() {
@Override
public void onCommand(Object command) { public void onCommand(Object command) {
LOG.debug("Test Transport Listener received Command: " + command); LOG.debug("Test Transport Listener received Command: " + command);
commandsReceived++;
} }
@Override
public void onException(IOException error) { public void onException(IOException error) {
LOG.debug("Test Transport Listener received Exception: " + error); LOG.debug("Test Transport Listener received Exception: " + error);
exceptionReceived++;
} }
@Override
public void transportInterupted() { public void transportInterupted() {
transportInterruptions++; transportInterruptions++;
LOG.debug("Test Transport Listener records transport Interrupted: " + transportInterruptions); LOG.debug("Test Transport Listener records transport Interrupted: " + transportInterruptions);
} }
@Override
public void transportResumed() { public void transportResumed() {
transportResumptions++; transportResumptions++;
LOG.debug("Test Transport Listener records transport Resumed: " + transportResumptions); LOG.debug("Test Transport Listener records transport Resumed: " + transportResumptions);

View File

@ -23,6 +23,7 @@ import java.util.concurrent.TimeUnit;
import javax.jms.DeliveryMode; import javax.jms.DeliveryMode;
import junit.framework.Test; import junit.framework.Test;
import org.apache.activemq.broker.StubConnection; import org.apache.activemq.broker.StubConnection;
import org.apache.activemq.broker.TransportConnector; import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQDestination;
@ -152,15 +153,16 @@ public class FailoverTransportBrokerTest extends NetworkTestSupport {
assertNull("no peer brokers present", info[0].getPeerBrokerInfos()); assertNull("no peer brokers present", info[0].getPeerBrokerInfos());
} }
@Override
protected String getLocalURI() { protected String getLocalURI() {
return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true";
} }
@Override
protected String getRemoteURI() { protected String getRemoteURI() {
return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true";
} }
@SuppressWarnings("unchecked")
protected StubConnection createFailoverConnection(TransportListener listener) throws Exception { protected StubConnection createFailoverConnection(TransportListener listener) throws Exception {
URI failoverURI = new URI("failover://" + connector.getServer().getConnectURI() + "," + remoteConnector.getServer().getConnectURI() + ""); URI failoverURI = new URI("failover://" + connector.getServer().getConnectURI() + "," + remoteConnector.getServer().getConnectURI() + "");
Transport transport = TransportFactory.connect(failoverURI); Transport transport = TransportFactory.connect(failoverURI);

View File

@ -27,6 +27,7 @@ import javax.jms.Session;
import javax.jms.TextMessage; import javax.jms.TextMessage;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.advisory.AdvisorySupport; import org.apache.activemq.advisory.AdvisorySupport;
import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQDestination;
@ -54,6 +55,7 @@ public class PeerTransportTest extends TestCase {
protected Connection[] connections; protected Connection[] connections;
protected MessageIdList messageIdList[]; protected MessageIdList messageIdList[];
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
connections = new Connection[NUMBER_IN_CLUSTER]; connections = new Connection[NUMBER_IN_CLUSTER];
@ -61,8 +63,6 @@ public class PeerTransportTest extends TestCase {
messageIdList = new MessageIdList[NUMBER_IN_CLUSTER]; messageIdList = new MessageIdList[NUMBER_IN_CLUSTER];
ActiveMQDestination destination = createDestination(); ActiveMQDestination destination = createDestination();
String root = System.getProperty("activemq.store.dir");
for (int i = 0; i < NUMBER_IN_CLUSTER; i++) { for (int i = 0; i < NUMBER_IN_CLUSTER; i++) {
connections[i] = createConnection(i); connections[i] = createConnection(i);
connections[i].setClientID("ClusterTest" + i); connections[i].setClientID("ClusterTest" + i);
@ -102,6 +102,7 @@ public class PeerTransportTest extends TestCase {
LOG.info("Cluster is online."); LOG.info("Cluster is online.");
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
if (connections != null) { if (connections != null) {
for (int i = 0; i < connections.length; i++) { for (int i = 0; i < connections.length; i++) {

View File

@ -20,7 +20,6 @@ import java.net.SocketAddress;
import java.net.URI; import java.net.URI;
import org.apache.activemq.openwire.OpenWireFormat; import org.apache.activemq.openwire.OpenWireFormat;
import org.apache.activemq.test.JmsTopicSendReceiveWithEmbeddedBrokerAndUserIDTest;
import org.apache.activemq.transport.CommandJoiner; import org.apache.activemq.transport.CommandJoiner;
import org.apache.activemq.transport.Transport; import org.apache.activemq.transport.Transport;
import org.apache.activemq.transport.udp.ResponseRedirectInterceptor; import org.apache.activemq.transport.udp.ResponseRedirectInterceptor;
@ -38,6 +37,7 @@ public class UnreliableUdpTransportTest extends UdpTransportTest {
protected DropCommandStrategy dropStrategy = new DropCommandStrategy() { protected DropCommandStrategy dropStrategy = new DropCommandStrategy() {
@Override
public boolean shouldDropCommand(int commandId, SocketAddress address, boolean redelivery) { public boolean shouldDropCommand(int commandId, SocketAddress address, boolean redelivery) {
if (redelivery) { if (redelivery) {
return false; return false;
@ -46,6 +46,7 @@ public class UnreliableUdpTransportTest extends UdpTransportTest {
} }
}; };
@Override
protected Transport createProducer() throws Exception { protected Transport createProducer() throws Exception {
LOG.info("Producer using URI: " + producerURI); LOG.info("Producer using URI: " + producerURI);
@ -60,6 +61,7 @@ public class UnreliableUdpTransportTest extends UdpTransportTest {
return new CommandJoiner(reliableTransport, wireFormat); return new CommandJoiner(reliableTransport, wireFormat);
} }
@Override
protected Transport createConsumer() throws Exception { protected Transport createConsumer() throws Exception {
LOG.info("Consumer on port: " + consumerPort); LOG.info("Consumer on port: " + consumerPort);
OpenWireFormat wireFormat = createWireFormat(); OpenWireFormat wireFormat = createWireFormat();

View File

@ -19,6 +19,7 @@ package org.apache.activemq.transport.tcp;
import java.net.Socket; import java.net.Socket;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import junit.framework.TestCase; import junit.framework.TestCase;
public class QualityOfServiceUtilsTest extends TestCase { public class QualityOfServiceUtilsTest extends TestCase {
@ -33,6 +34,7 @@ public class QualityOfServiceUtilsTest extends TestCase {
protected void setUp() throws Exception { protected void setUp() throws Exception {
Socket socket = new Socket(); Socket socket = new Socket();
ECN = socket.getTrafficClass() & Integer.parseInt("00000011", 2); ECN = socket.getTrafficClass() & Integer.parseInt("00000011", 2);
socket.close();
} }
@Override @Override
@ -104,7 +106,7 @@ public class QualityOfServiceUtilsTest extends TestCase {
private void testInvalidDiffServName(String name) { private void testInvalidDiffServName(String name) {
try { try {
int dscp = QualityOfServiceUtils.getDSCP(name); QualityOfServiceUtils.getDSCP(name);
fail("No IllegalArgumentException thrown for invalid Differentiated" fail("No IllegalArgumentException thrown for invalid Differentiated"
+ " Services value: " + name + "."); + " Services value: " + name + ".");
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
@ -125,7 +127,7 @@ public class QualityOfServiceUtilsTest extends TestCase {
private void testInvalidDiffServIntegerValue(int val) { private void testInvalidDiffServIntegerValue(int val) {
try { try {
int dscp = QualityOfServiceUtils.getDSCP(Integer.toString(val)); QualityOfServiceUtils.getDSCP(Integer.toString(val));
fail("No IllegalArgumentException thrown for invalid " fail("No IllegalArgumentException thrown for invalid "
+ "Differentiated Services value " + val + "."); + "Differentiated Services value " + val + ".");
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
@ -159,7 +161,7 @@ public class QualityOfServiceUtilsTest extends TestCase {
private void testInvalidTypeOfServiceValue(int val) { private void testInvalidTypeOfServiceValue(int val) {
try { try {
int typeOfService = QualityOfServiceUtils.getToS(val); QualityOfServiceUtils.getToS(val);
fail("No IllegalArgumentException thrown for invalid " fail("No IllegalArgumentException thrown for invalid "
+ "Type of Service value " + val + "."); + "Type of Service value " + val + ".");
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {

View File

@ -22,7 +22,9 @@ import java.net.Socket;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.Random; import java.util.Random;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import javax.net.SocketFactory; import javax.net.SocketFactory;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -39,14 +41,12 @@ public class SocketTstFactory extends SocketFactory {
private class SocketTst { private class SocketTst {
private class Bagot implements Runnable { private class Bagot implements Runnable {
private Thread processus; private final Thread processus;
private Random rnd; private final Socket socket;
private Socket socket;
private final InetAddress address; private final InetAddress address;
public Bagot(Random rnd, Socket socket, InetAddress address) { public Bagot(Random rnd, Socket socket, InetAddress address) {
this.processus = new Thread(this, "Network Faults maker : undefined"); this.processus = new Thread(this, "Network Faults maker : undefined");
this.rnd = rnd;
this.socket = socket; this.socket = socket;
this.address = address; this.address = address;
} }
@ -56,6 +56,7 @@ public class SocketTstFactory extends SocketFactory {
this.processus.start(); this.processus.start();
} }
@Override
public void run() { public void run() {
int lastDelayVal; int lastDelayVal;
Integer lastDelay; Integer lastDelay;
@ -65,12 +66,12 @@ public class SocketTstFactory extends SocketFactory {
lastDelay = closeIter.get(this.address); lastDelay = closeIter.get(this.address);
if (lastDelay == null) { if (lastDelay == null) {
lastDelayVal = 0; lastDelayVal = 0;
} } else {
else {
lastDelayVal = lastDelay.intValue(); lastDelayVal = lastDelay.intValue();
if (lastDelayVal > 10) if (lastDelayVal > 10)
lastDelayVal += 20; lastDelayVal += 20;
else lastDelayVal += 1; else
lastDelayVal += 1;
} }
lastDelay = new Integer(lastDelayVal); lastDelay = new Integer(lastDelayVal);
@ -137,6 +138,7 @@ public class SocketTstFactory extends SocketFactory {
this.rnd = new Random(); this.rnd = new Random();
} }
@Override
public Socket createSocket(InetAddress host, int port) throws IOException { public Socket createSocket(InetAddress host, int port) throws IOException {
SocketTst sockTst; SocketTst sockTst;
sockTst = new SocketTst(host, port, this.rnd); sockTst = new SocketTst(host, port, this.rnd);
@ -144,6 +146,7 @@ public class SocketTstFactory extends SocketFactory {
return sockTst.getSocket(); return sockTst.getSocket();
} }
@Override
public Socket createSocket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException { public Socket createSocket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException {
SocketTst sockTst; SocketTst sockTst;
sockTst = new SocketTst(host, port, localAddress, localPort, this.rnd); sockTst = new SocketTst(host, port, localAddress, localPort, this.rnd);
@ -151,6 +154,7 @@ public class SocketTstFactory extends SocketFactory {
return sockTst.getSocket(); return sockTst.getSocket();
} }
@Override
public Socket createSocket(String host, int port) throws IOException { public Socket createSocket(String host, int port) throws IOException {
SocketTst sockTst; SocketTst sockTst;
sockTst = new SocketTst(host, port, this.rnd); sockTst = new SocketTst(host, port, this.rnd);
@ -158,6 +162,7 @@ public class SocketTstFactory extends SocketFactory {
return sockTst.getSocket(); return sockTst.getSocket();
} }
@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException { public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException {
SocketTst sockTst; SocketTst sockTst;
sockTst = new SocketTst(host, port, localAddress, localPort, this.rnd); sockTst = new SocketTst(host, port, localAddress, localPort, this.rnd);

View File

@ -20,12 +20,10 @@ import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.Map; import java.util.Map;
import junit.framework.Test;
import junit.framework.TestCase; import junit.framework.TestCase;
import junit.textui.TestRunner;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector; import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.transport.TransportBrokerTestSupport;
import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
/** /**
@ -33,12 +31,10 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
*/ */
public class SslContextBrokerServiceTest extends TestCase { public class SslContextBrokerServiceTest extends TestCase {
private ClassPathXmlApplicationContext context; private ClassPathXmlApplicationContext context;
private BrokerService broker; private BrokerService broker;
private TransportConnector connector; private TransportConnector connector;
public void testConfiguration() throws URISyntaxException { public void testConfiguration() throws URISyntaxException {
assertNotNull(broker); assertNotNull(broker);
@ -52,11 +48,12 @@ public class SslContextBrokerServiceTest extends TestCase {
} }
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
Thread.currentThread().setContextClassLoader(SslContextBrokerServiceTest.class.getClassLoader()); Thread.currentThread().setContextClassLoader(SslContextBrokerServiceTest.class.getClassLoader());
context = new ClassPathXmlApplicationContext("org/apache/activemq/transport/tcp/activemq-ssl.xml"); context = new ClassPathXmlApplicationContext("org/apache/activemq/transport/tcp/activemq-ssl.xml");
Map beansOfType = context.getBeansOfType(BrokerService.class); Map<String, BrokerService> beansOfType = context.getBeansOfType(BrokerService.class);
broker = (BrokerService)beansOfType.values().iterator().next(); broker = beansOfType.values().iterator().next();
connector = broker.getTransportConnectors().get(0); connector = broker.getTransportConnectors().get(0);
} }

View File

@ -36,12 +36,11 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SslContextNBrokerServiceTest extends TestCase { public class SslContextNBrokerServiceTest extends TestCase {
private static final transient Logger LOG = LoggerFactory.getLogger(SslContextNBrokerServiceTest.class); private static final transient Logger LOG = LoggerFactory.getLogger(SslContextNBrokerServiceTest.class);
private ClassPathXmlApplicationContext context; private ClassPathXmlApplicationContext context;
Map beansOfType; Map<String, BrokerService> beansOfType;
public void testConfigurationIsolation() throws Exception { public void testConfigurationIsolation() throws Exception {
@ -71,8 +70,7 @@ public class SslContextNBrokerServiceTest extends TestCase {
context.init(null, new TrustManager[] { catcher }, null); context.init(null, new TrustManager[] { catcher }, null);
SSLSocketFactory factory = context.getSocketFactory(); SSLSocketFactory factory = context.getSocketFactory();
LOG.info("Connecting to broker: " + broker.getBrokerName() LOG.info("Connecting to broker: " + broker.getBrokerName() + " on: " + brokerUri.getHost() + ":" + brokerUri.getPort());
+ " on: " + brokerUri.getHost() + ":" + brokerUri.getPort());
SSLSocket socket = (SSLSocket) factory.createSocket(brokerUri.getHost(), brokerUri.getPort()); SSLSocket socket = (SSLSocket) factory.createSocket(brokerUri.getHost(), brokerUri.getPort());
socket.setSoTimeout(5000); socket.setSoTimeout(5000);
socket.startHandshake(); socket.startHandshake();
@ -94,12 +92,11 @@ public class SslContextNBrokerServiceTest extends TestCase {
return matches; return matches;
} }
private BrokerService getBroker(String name) { private BrokerService getBroker(String name) {
BrokerService result = null; BrokerService result = null;
Iterator iterator = beansOfType.values().iterator(); Iterator<BrokerService> iterator = beansOfType.values().iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
BrokerService candidate = (BrokerService)iterator.next(); BrokerService candidate = iterator.next();
if (candidate.getBrokerName().equals(name)) { if (candidate.getBrokerName().equals(name)) {
result = candidate; result = candidate;
break; break;
@ -108,13 +105,12 @@ public class SslContextNBrokerServiceTest extends TestCase {
return result; return result;
} }
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
// System.setProperty("javax.net.debug", "ssl"); // System.setProperty("javax.net.debug", "ssl");
Thread.currentThread().setContextClassLoader(SslContextNBrokerServiceTest.class.getClassLoader()); Thread.currentThread().setContextClassLoader(SslContextNBrokerServiceTest.class.getClassLoader());
context = new ClassPathXmlApplicationContext("org/apache/activemq/transport/tcp/n-brokers-ssl.xml"); context = new ClassPathXmlApplicationContext("org/apache/activemq/transport/tcp/n-brokers-ssl.xml");
beansOfType = context.getBeansOfType(BrokerService.class); beansOfType = context.getBeansOfType(BrokerService.class);
} }
@Override @Override
@ -122,15 +118,19 @@ public class SslContextNBrokerServiceTest extends TestCase {
context.destroy(); context.destroy();
} }
class CertChainCatcher implements X509TrustManager { class CertChainCatcher implements X509TrustManager {
X509Certificate[] serverCerts; X509Certificate[] serverCerts;
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
} }
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
serverCerts = arg0; serverCerts = arg0;
} }
@Override
public X509Certificate[] getAcceptedIssuers() { public X509Certificate[] getAcceptedIssuers() {
return null; return null;
} }

View File

@ -26,8 +26,8 @@ import javax.jms.Message;
import javax.jms.Session; import javax.jms.Session;
import javax.jms.TextMessage; import javax.jms.TextMessage;
import junit.framework.Assert;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector; import org.apache.activemq.broker.TransportConnector;
@ -66,6 +66,7 @@ public class AMQStackOverFlowTest extends TestCase {
template1.send("test.q", new MessageCreator() { template1.send("test.q", new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException { public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("test"); return session.createTextMessage("test");
} }
@ -80,14 +81,14 @@ public class AMQStackOverFlowTest extends TestCase {
final TextMessage tm = (TextMessage)m; final TextMessage tm = (TextMessage)m;
Assert.assertEquals("test", tm.getText()); assertEquals("test", tm.getText());
template2.send("test2.q", new MessageCreator() { template2.send("test2.q", new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException { public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("test2"); return session.createTextMessage("test2");
} }
}); });
final Message m2 = template1.receive("test2.q"); final Message m2 = template1.receive("test2.q");
@ -96,17 +97,14 @@ public class AMQStackOverFlowTest extends TestCase {
final TextMessage tm2 = (TextMessage)m2; final TextMessage tm2 = (TextMessage)m2;
Assert.assertEquals("test2", tm2.getText()); assertEquals("test2", tm2.getText());
} finally { } finally {
brokerService1.stop(); brokerService1.stop();
brokerService1 = null; brokerService1 = null;
brokerService2.stop(); brokerService2.stop();
brokerService2 = null; brokerService2 = null;
} }
} }
private BrokerService createBrokerService(final String brokerName, final String uri1, final String uri2) private BrokerService createBrokerService(final String brokerName, final String uri1, final String uri2)
@ -146,6 +144,5 @@ public class AMQStackOverFlowTest extends TestCase {
} }
return brokerService; return brokerService;
} }
} }

View File

@ -28,7 +28,6 @@ import org.apache.activemq.broker.region.DestinationInterceptor;
import org.apache.activemq.broker.region.virtual.VirtualDestination; import org.apache.activemq.broker.region.virtual.VirtualDestination;
import org.apache.activemq.broker.region.virtual.VirtualDestinationInterceptor; import org.apache.activemq.broker.region.virtual.VirtualDestinationInterceptor;
import org.apache.activemq.broker.region.virtual.VirtualTopic; import org.apache.activemq.broker.region.virtual.VirtualTopic;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.network.NetworkConnector; import org.apache.activemq.network.NetworkConnector;
import org.apache.activemq.store.kahadb.KahaDBStore; import org.apache.activemq.store.kahadb.KahaDBStore;
import org.apache.activemq.util.MessageIdList; import org.apache.activemq.util.MessageIdList;
@ -100,6 +99,7 @@ public abstract class AbstractTwoBrokerNetworkConnectorWildcardIncludedDestinati
protected abstract void addIncludedDestination(NetworkConnector networkConnector); protected abstract void addIncludedDestination(NetworkConnector networkConnector);
@Override
public void setUp() throws Exception { public void setUp() throws Exception {
super.setAutoFail(true); super.setAutoFail(true);
super.setUp(); super.setUp();

View File

@ -23,12 +23,11 @@ import javax.jms.MessageConsumer;
import javax.jms.MessageProducer; import javax.jms.MessageProducer;
import javax.jms.Session; import javax.jms.Session;
import org.apache.activemq.TestSupport;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.TestSupport;
import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -38,16 +37,19 @@ public class AdvisoryTopicDeletionTest extends TestSupport {
private BrokerService broker; private BrokerService broker;
private Connection connection; private Connection connection;
@Override
protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { protected ActiveMQConnectionFactory createConnectionFactory() throws Exception {
return new ActiveMQConnectionFactory("vm://" + getName()); return new ActiveMQConnectionFactory("vm://" + getName());
} }
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
createBroker(); createBroker();
topic = false; topic = false;
super.setUp(); super.setUp();
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
super.tearDown(); super.tearDown();
destroyBroker(); destroyBroker();

View File

@ -19,6 +19,7 @@ package org.apache.activemq.usecases;
import java.net.URI; import java.net.URI;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.jms.Destination; import javax.jms.Destination;
import javax.jms.MessageConsumer; import javax.jms.MessageConsumer;
import javax.jms.TextMessage; import javax.jms.TextMessage;
@ -55,7 +56,6 @@ public class BrokerQueueNetworkWithDisconnectTest extends JmsMultipleBrokersTest
private long inactiveDuration = 1000; private long inactiveDuration = 1000;
private boolean useSocketProxy = true; private boolean useSocketProxy = true;
public void initCombosForTestSendOnAReceiveOnBWithTransportDisconnect() { public void initCombosForTestSendOnAReceiveOnBWithTransportDisconnect() {
addCombinationValues( "useDuplexNetworkBridge", new Object[]{ Boolean.TRUE, Boolean.FALSE} ); addCombinationValues( "useDuplexNetworkBridge", new Object[]{ Boolean.TRUE, Boolean.FALSE} );
addCombinationValues( "simulateStalledNetwork", new Object[]{ Boolean.TRUE } ); addCombinationValues( "simulateStalledNetwork", new Object[]{ Boolean.TRUE } );
@ -86,6 +86,7 @@ public class BrokerQueueNetworkWithDisconnectTest extends JmsMultipleBrokersTest
MESSAGE_COUNT <= msgs.getMessageCount()); MESSAGE_COUNT <= msgs.getMessageCount());
} }
@SuppressWarnings("unchecked")
public void testNoStuckConnectionsWithTransportDisconnect() throws Exception { public void testNoStuckConnectionsWithTransportDisconnect() throws Exception {
inactiveDuration=60000l; inactiveDuration=60000l;
useDuplexNetworkBridge = true; useDuplexNetworkBridge = true;
@ -123,6 +124,7 @@ public class BrokerQueueNetworkWithDisconnectTest extends JmsMultipleBrokersTest
// wait for full reformation of bridge // wait for full reformation of bridge
// verify no extra connections // verify no extra connections
boolean allGood = Wait.waitFor(new Wait.Condition(){ boolean allGood = Wait.waitFor(new Wait.Condition(){
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
long numConnections = hub.broker.getTransportConnectors().get(0).getConnections().size(); long numConnections = hub.broker.getTransportConnectors().get(0).getConnections().size();
LOG.info("Num connetions:" + numConnections); LOG.info("Num connetions:" + numConnections);
@ -134,6 +136,7 @@ public class BrokerQueueNetworkWithDisconnectTest extends JmsMultipleBrokersTest
assertTrue("should be only one transport connection for the single duplex network connector", allGood); assertTrue("should be only one transport connection for the single duplex network connector", allGood);
allGood = Wait.waitFor(new Wait.Condition(){ allGood = Wait.waitFor(new Wait.Condition(){
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
long numVmConnections = VMTransportFactory.SERVERS.get(HUB).getConnectionCount(); long numVmConnections = VMTransportFactory.SERVERS.get(HUB).getConnectionCount();
LOG.info("Num VM connetions:" + numVmConnections); LOG.info("Num VM connetions:" + numVmConnections);
@ -171,6 +174,7 @@ public class BrokerQueueNetworkWithDisconnectTest extends JmsMultipleBrokersTest
sleep(600); sleep(600);
} }
@Override
public void setUp() throws Exception { public void setUp() throws Exception {
networkDownTimeStart = 0; networkDownTimeStart = 0;
inactiveDuration = 1000; inactiveDuration = 1000;
@ -182,6 +186,7 @@ public class BrokerQueueNetworkWithDisconnectTest extends JmsMultipleBrokersTest
createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options)); createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options));
} }
@Override
public void tearDown() throws Exception { public void tearDown() throws Exception {
super.tearDown(); super.tearDown();
if (socketProxy != null) { if (socketProxy != null) {
@ -232,7 +237,7 @@ public class BrokerQueueNetworkWithDisconnectTest extends JmsMultipleBrokersTest
List<TransportConnector> transportConnectors = remoteBroker.getTransportConnectors(); List<TransportConnector> transportConnectors = remoteBroker.getTransportConnectors();
URI remoteURI; URI remoteURI;
if (!transportConnectors.isEmpty()) { if (!transportConnectors.isEmpty()) {
remoteURI = ((TransportConnector)transportConnectors.get(0)).getConnectUri(); remoteURI = transportConnectors.get(0).getConnectUri();
if (useSocketProxy) { if (useSocketProxy) {
socketProxy = new SocketProxy(remoteURI); socketProxy = new SocketProxy(remoteURI);
remoteURI = socketProxy.getUrl(); remoteURI = socketProxy.getUrl();

View File

@ -110,6 +110,7 @@ public class BrowseOverNetworkTest extends JmsMultipleBrokersTestSupport {
this.expect = expect; this.expect = expect;
} }
@Override
public void run() { public void run() {
int retries = 0; int retries = 0;
while (retries++ < 20 && totalCount != expect) { while (retries++ < 20 && totalCount != expect) {
@ -122,8 +123,8 @@ public class BrowseOverNetworkTest extends JmsMultipleBrokersTestSupport {
totalCount += count; totalCount += count;
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
ActiveMQTextMessage message = (ActiveMQTextMessage)consumer.receive(1000); ActiveMQTextMessage message = (ActiveMQTextMessage)consumer.receive(1000);
LOG.info(broker + " consumer: " + message.getText() + " " + message.getDestination() + " " + message.getMessageId() + " " + Arrays.toString(message.getBrokerPath()));
if (message == null) break; if (message == null) break;
LOG.info(broker + " consumer: " + message.getText() + " " + message.getDestination() + " " + message.getMessageId() + " " + Arrays.toString(message.getBrokerPath()));
} }
} }
} else { } else {
@ -222,7 +223,7 @@ public class BrowseOverNetworkTest extends JmsMultipleBrokersTestSupport {
} }
protected int browseMessages(QueueBrowser browser, String name) throws Exception { protected int browseMessages(QueueBrowser browser, String name) throws Exception {
Enumeration msgs = browser.getEnumeration(); Enumeration<?> msgs = browser.getEnumeration();
int browsedMessage = 0; int browsedMessage = 0;
while (msgs.hasMoreElements()) { while (msgs.hasMoreElements()) {
browsedMessage++; browsedMessage++;
@ -240,6 +241,7 @@ public class BrowseOverNetworkTest extends JmsMultipleBrokersTestSupport {
return browsedMessage; return browsedMessage;
} }
@Override
public void setUp() throws Exception { public void setUp() throws Exception {
super.setAutoFail(true); super.setAutoFail(true);
super.setUp(); super.setUp();

View File

@ -18,6 +18,7 @@
package org.apache.activemq.usecases; package org.apache.activemq.usecases;
import java.util.HashMap; import java.util.HashMap;
import javax.jms.Connection; import javax.jms.Connection;
import javax.jms.Destination; import javax.jms.Destination;
import javax.jms.MessageConsumer; import javax.jms.MessageConsumer;
@ -39,6 +40,7 @@ public class ChangeSentMessageTest extends TestSupport {
* *
* @throws Exception * @throws Exception
*/ */
@SuppressWarnings("rawtypes")
public void testDoChangeSentMessage() throws Exception { public void testDoChangeSentMessage() throws Exception {
Destination destination = createDestination("test-" + ChangeSentMessageTest.class.getName()); Destination destination = createDestination("test-" + ChangeSentMessageTest.class.getName());
Connection connection = createConnection(); Connection connection = createConnection();

View File

@ -47,7 +47,6 @@ public class ChangeSessionDeliveryModeTest extends TestSupport implements Messag
Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer1 = consumerSession.createConsumer(destination); MessageConsumer consumer1 = consumerSession.createConsumer(destination);
consumer1.setMessageListener(this); consumer1.setMessageListener(this);
JMSException jmsEx = null;
MessageConsumer consumer2 = consumerSession.createConsumer(destination); MessageConsumer consumer2 = consumerSession.createConsumer(destination);
try { try {
@ -58,6 +57,7 @@ public class ChangeSessionDeliveryModeTest extends TestSupport implements Messag
} }
} }
@Override
public void onMessage(Message msg) { public void onMessage(Message msg) {
} }
} }

View File

@ -29,7 +29,6 @@ import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.test.JmsSendReceiveTestSupport; import org.apache.activemq.test.JmsSendReceiveTestSupport;
import org.apache.activemq.test.retroactive.RetroactiveConsumerTestWithSimpleMessageListTest;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -43,8 +42,11 @@ public class CompositePublishTest extends JmsSendReceiveTestSupport {
protected Connection receiveConnection; protected Connection receiveConnection;
protected Session receiveSession; protected Session receiveSession;
protected MessageConsumer[] consumers; protected MessageConsumer[] consumers;
@SuppressWarnings("rawtypes")
protected List[] messageLists; protected List[] messageLists;
@SuppressWarnings("unchecked")
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
super.setUp(); super.setUp();
@ -95,6 +97,7 @@ public class CompositePublishTest extends JmsSendReceiveTestSupport {
protected MessageListener createMessageListener(int i, final List<Message> messageList) { protected MessageListener createMessageListener(int i, final List<Message> messageList) {
return new MessageListener() { return new MessageListener() {
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
consumeMessage(message, messageList); consumeMessage(message, messageList);
} }
@ -104,6 +107,7 @@ public class CompositePublishTest extends JmsSendReceiveTestSupport {
/** /**
* Returns the subject on which we publish * Returns the subject on which we publish
*/ */
@Override
protected String getSubject() { protected String getSubject() {
return getPrefix() + "FOO.BAR," + getPrefix() + "FOO.X.Y"; return getPrefix() + "FOO.BAR," + getPrefix() + "FOO.X.Y";
} }
@ -119,6 +123,8 @@ public class CompositePublishTest extends JmsSendReceiveTestSupport {
return super.getSubject() + "."; return super.getSubject() + ".";
} }
@SuppressWarnings("unchecked")
@Override
protected void assertMessagesAreReceived() throws JMSException { protected void assertMessagesAreReceived() throws JMSException {
waitForMessagesToBeDelivered(); waitForMessagesToBeDelivered();
int size = messageLists.length; int size = messageLists.length;
@ -131,10 +137,12 @@ public class CompositePublishTest extends JmsSendReceiveTestSupport {
} }
} }
@Override
protected ActiveMQConnectionFactory createConnectionFactory() { protected ActiveMQConnectionFactory createConnectionFactory() {
return new ActiveMQConnectionFactory("vm://localhost"); return new ActiveMQConnectionFactory("vm://localhost");
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
session.close(); session.close();
receiveSession.close(); receiveSession.close();

View File

@ -18,55 +18,46 @@ package org.apache.activemq.usecases;
import javax.jms.Connection; import javax.jms.Connection;
import javax.jms.DeliveryMode; import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer; import javax.jms.MessageConsumer;
import javax.jms.MessageProducer; import javax.jms.MessageProducer;
import javax.jms.Queue; import javax.jms.Queue;
import javax.jms.Session; import javax.jms.Session;
import javax.jms.TextMessage; import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.JmsConnectionStartStopTest;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.region.policy.PolicyEntry; import org.apache.activemq.broker.region.policy.PolicyEntry;
import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.broker.region.policy.PolicyMap;
/** /**
* Test case intended to demonstrate delivery interruption to queue consumers when * Test case intended to demonstrate delivery interruption to queue consumers when a JMS selector leaves some messages
* a JMS selector leaves some messages on the queue (due to use of a JMS Selector) * on the queue (due to use of a JMS Selector)
* *
* testNonDiscriminatingConsumer() demonstrates proper functionality for consumers that don't use * testNonDiscriminatingConsumer() demonstrates proper functionality for consumers that don't use a selector to qualify
* a selector to qualify their input. * their input.
* *
* testDiscriminatingConsumer() demonstrates the failure condition in which delivery to the consumer * testDiscriminatingConsumer() demonstrates the failure condition in which delivery to the consumer eventually halts.
* eventually halts.
* *
* The expected behavior is for the delivery to the client to be maintained regardless of the depth * The expected behavior is for the delivery to the client to be maintained regardless of the depth of the queue,
* of the queue, particularly when the messages in the queue do not meet the selector criteria of the * particularly when the messages in the queue do not meet the selector criteria of the client.
* client.
* *
* https://issues.apache.org/activemq/browse/AMQ-2217 * https://issues.apache.org/activemq/browse/AMQ-2217
* *
*/ */
public class DiscriminatingConsumerLoadTest extends TestSupport { public class DiscriminatingConsumerLoadTest extends TestSupport {
private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(DiscriminatingConsumerLoadTest.class);
.getLog(DiscriminatingConsumerLoadTest.class);
private Connection producerConnection; private Connection producerConnection;
private Connection consumerConnection; private Connection consumerConnection;
private int counterSent = 0;
private int counterReceived = 0;
public static final String JMSTYPE_EATME = "DiscriminatingLoadClient.EatMe"; public static final String JMSTYPE_EATME = "DiscriminatingLoadClient.EatMe";
public static final String JMSTYPE_IGNOREME = "DiscriminatingLoadClient.IgnoreMe"; public static final String JMSTYPE_IGNOREME = "DiscriminatingLoadClient.IgnoreMe";
private int testSize = 5000; // setting this to a small number will pass all tests private final int testSize = 5000; // setting this to a small number will pass all tests
BrokerService broker; BrokerService broker;
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
broker = new BrokerService(); broker = new BrokerService();
broker.setPersistent(false); broker.setPersistent(false);
@ -87,6 +78,7 @@ public class DiscriminatingConsumerLoadTest extends TestSupport {
/** /**
* @see junit.framework.TestCase#tearDown() * @see junit.framework.TestCase#tearDown()
*/ */
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
if (producerConnection != null) { if (producerConnection != null) {
producerConnection.close(); producerConnection.close();
@ -111,7 +103,10 @@ public class DiscriminatingConsumerLoadTest extends TestSupport {
consumerConnection.start(); consumerConnection.start();
LOG.info("consumerConnection = " + consumerConnection); LOG.info("consumerConnection = " + consumerConnection);
try {Thread.sleep(1000); } catch (Exception e) {} try {
Thread.sleep(1000);
} catch (Exception e) {
}
// here we pass in null for the JMS selector // here we pass in null for the JMS selector
Consumer consumer = new Consumer(consumerConnection, null); Consumer consumer = new Consumer(consumerConnection, null);
@ -123,7 +118,10 @@ public class DiscriminatingConsumerLoadTest extends TestSupport {
producerConnection.start(); producerConnection.start();
LOG.info("producerConnection = " + producerConnection); LOG.info("producerConnection = " + producerConnection);
try {Thread.sleep(3000); } catch (Exception e) {} try {
Thread.sleep(3000);
} catch (Exception e) {
}
Producer producer = new Producer(producerConnection); Producer producer = new Producer(producerConnection);
Thread producerThread = new Thread(producer); Thread producerThread = new Thread(producer);
@ -136,15 +134,11 @@ public class DiscriminatingConsumerLoadTest extends TestSupport {
if (consumer.getCount() == testSize) if (consumer.getCount() == testSize)
LOG.info("test complete .... all messsages consumed!!"); LOG.info("test complete .... all messsages consumed!!");
else else
LOG.info("test failed .... Sent " + (testSize / 1) + LOG.info("test failed .... Sent " + (testSize / 1) + " messages intended to be consumed ( " + testSize + " total), but only consumed "
" messages intended to be consumed ( " + testSize + " total), but only consumed " + consumer.getCount()); + consumer.getCount());
assertTrue("Sent " + testSize + " messages intended to be consumed, but only consumed " + consumer.getCount(), (consumer.getCount() == testSize));
assertTrue("Sent " + testSize + " messages intended to be consumed, but only consumed " + consumer.getCount(),
(consumer.getCount() == testSize ));
assertFalse("Delivery of messages to consumer was halted during this test", consumer.deliveryHalted()); assertFalse("Delivery of messages to consumer was halted during this test", consumer.deliveryHalted());
} }
/** /**
@ -158,7 +152,10 @@ public class DiscriminatingConsumerLoadTest extends TestSupport {
consumerConnection.start(); consumerConnection.start();
LOG.info("consumerConnection = " + consumerConnection); LOG.info("consumerConnection = " + consumerConnection);
try {Thread.sleep(1000); } catch (Exception e) {} try {
Thread.sleep(1000);
} catch (Exception e) {
}
// here we pass the JMS selector we intend to consume // here we pass the JMS selector we intend to consume
Consumer consumer = new Consumer(consumerConnection, JMSTYPE_EATME); Consumer consumer = new Consumer(consumerConnection, JMSTYPE_EATME);
@ -170,7 +167,10 @@ public class DiscriminatingConsumerLoadTest extends TestSupport {
producerConnection.start(); producerConnection.start();
LOG.info("producerConnection = " + producerConnection); LOG.info("producerConnection = " + producerConnection);
try {Thread.sleep(3000); } catch (Exception e) {} try {
Thread.sleep(3000);
} catch (Exception e) {
}
Producer producer = new Producer(producerConnection); Producer producer = new Producer(producerConnection);
Thread producerThread = new Thread(producer); Thread producerThread = new Thread(producer);
@ -180,46 +180,40 @@ public class DiscriminatingConsumerLoadTest extends TestSupport {
consumerThread.join(); consumerThread.join();
producer.stop = true; producer.stop = true;
if (consumer.getCount() == (testSize / 2)) if (consumer.getCount() == (testSize / 2)) {
{
LOG.info("test complete .... all messsages consumed!!"); LOG.info("test complete .... all messsages consumed!!");
} } else {
else LOG.info("test failed .... Sent " + testSize + " original messages, only half of which (" + (testSize / 2)
{ + ") were intended to be consumed: consumer paused at: " + consumer.getCount());
LOG.info("test failed .... Sent " + testSize + " original messages, only half of which (" + (testSize / 2) + // System.out.println("test failed .... Sent " + testSize + " original messages, only half of which (" +
") were intended to be consumed: consumer paused at: " + consumer.getCount()); // (testSize / 2) +
//System.out.println("test failed .... Sent " + testSize + " original messages, only half of which (" + (testSize / 2) +
// ") were intended to be consumed: consumer paused at: " + consumer.getCount()); // ") were intended to be consumed: consumer paused at: " + consumer.getCount());
} }
assertTrue("Sent " + testSize + " original messages, only half of which (" + (testSize / 2) + assertTrue("Sent " + testSize + " original messages, only half of which (" + (testSize / 2) + ") were intended to be consumed: consumer paused at: "
") were intended to be consumed: consumer paused at: " + consumer.getCount(), + consumer.getCount(), (consumer.getCount() == (testSize / 2)));
(consumer.getCount() == (testSize / 2)));
assertTrue("Delivery of messages to consumer was halted during this test as it only wants half", consumer.deliveryHalted()); assertTrue("Delivery of messages to consumer was halted during this test as it only wants half", consumer.deliveryHalted());
} }
/** /**
* Helper class that will publish 2 * testSize messages. The messages will be distributed evenly * Helper class that will publish 2 * testSize messages. The messages will be distributed evenly between the
* between the following two JMS types: * following two JMS types:
* *
* @see JMSTYPE_INTENDED_FOR_CONSUMPTION * @see JMSTYPE_INTENDED_FOR_CONSUMPTION
* @see JMSTYPE_NOT_INTENDED_FOR_CONSUMPTION * @see JMSTYPE_NOT_INTENDED_FOR_CONSUMPTION
* *
* @author jlyons
*
*/ */
private class Producer extends Thread private class Producer extends Thread {
{
private int counterSent = 0; private int counterSent = 0;
private Connection connection = null; private Connection connection = null;
public boolean stop = false; public boolean stop = false;
public Producer(Connection connection) public Producer(Connection connection) {
{
this.connection = connection; this.connection = connection;
} }
@Override
public void run() { public void run() {
try { try {
final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
@ -230,8 +224,7 @@ public class DiscriminatingConsumerLoadTest extends TestSupport {
Thread.sleep(10000); Thread.sleep(10000);
MessageProducer producer = session.createProducer(queue); MessageProducer producer = session.createProducer(queue);
while (!stop && (counterSent < testSize)) while (!stop && (counterSent < testSize)) {
{
// first send a message intended to be consumed .... // first send a message intended to be consumed ....
TextMessage message = session.createTextMessage("*** Ill ....... Ini ***"); // alma mater ... TextMessage message = session.createTextMessage("*** Ill ....... Ini ***"); // alma mater ...
message.setJMSType(JMSTYPE_EATME); message.setJMSType(JMSTYPE_EATME);
@ -257,60 +250,43 @@ public class DiscriminatingConsumerLoadTest extends TestSupport {
} }
LOG.info("producer thread complete ... " + counterSent + " messages sent to the queue"); LOG.info("producer thread complete ... " + counterSent + " messages sent to the queue");
} }
public int getCount()
{
return this.counterSent;
}
} }
/** /**
* Helper class that will consume messages from the queue based on the supplied JMS selector. * Helper class that will consume messages from the queue based on the supplied JMS selector. Thread will stop after
* Thread will stop after the first receive(..) timeout, or once all expected messages have * the first receive(..) timeout, or once all expected messages have been received (see testSize). If the thread
* been received (see testSize). If the thread stops due to a timeout, it is experiencing the * stops due to a timeout, it is experiencing the delivery pause that is symptomatic of a bug in the broker.
* delivery pause that is symptomatic of a bug in the broker.
*
* @author jlyons
* *
*/ */
private class Consumer extends Thread private class Consumer extends Thread {
{
protected int counterReceived = 0; protected int counterReceived = 0;
private Connection connection = null;
private String jmsSelector = null; private String jmsSelector = null;
private boolean deliveryHalted = false; private boolean deliveryHalted = false;
public Consumer(Connection connection, String jmsSelector) public Consumer(Connection connection, String jmsSelector) {
{
this.connection = connection;
this.jmsSelector = jmsSelector; this.jmsSelector = jmsSelector;
} }
@Override
public void run() { public void run() {
boolean testComplete = false;
try { try {
Session session = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); Session session = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
final Queue queue = session.createQueue("test"); final Queue queue = session.createQueue("test");
MessageConsumer consumer = null; MessageConsumer consumer = null;
if (null != this.jmsSelector) if (null != this.jmsSelector) {
{
consumer = session.createConsumer(queue, "JMSType='" + this.jmsSelector + "'"); consumer = session.createConsumer(queue, "JMSType='" + this.jmsSelector + "'");
} } else {
else
{
consumer = session.createConsumer(queue); consumer = session.createConsumer(queue);
} }
while (!deliveryHalted && (counterReceived < testSize)) while (!deliveryHalted && (counterReceived < testSize)) {
{
TextMessage result = (TextMessage) consumer.receive(30000); TextMessage result = (TextMessage) consumer.receive(30000);
if (result != null) { if (result != null) {
counterReceived++; counterReceived++;
//System.out.println("consuming .... JMSType = " + result.getJMSType() + " received = " + counterReceived); // System.out.println("consuming .... JMSType = " + result.getJMSType() + " received = " +
// counterReceived);
LOG.info("consuming .... JMSType = " + result.getJMSType() + " received = " + counterReceived); LOG.info("consuming .... JMSType = " + result.getJMSType() + " received = " + counterReceived);
} else } else {
{
LOG.info("consuming .... timeout while waiting for a message ... broker must have stopped delivery ... received = " + counterReceived); LOG.info("consuming .... timeout while waiting for a message ... broker must have stopped delivery ... received = " + counterReceived);
deliveryHalted = true; deliveryHalted = true;
} }
@ -322,13 +298,11 @@ public class DiscriminatingConsumerLoadTest extends TestSupport {
} }
public int getCount() public int getCount() {
{
return this.counterReceived; return this.counterReceived;
} }
public boolean deliveryHalted() public boolean deliveryHalted() {
{
return this.deliveryHalted; return this.deliveryHalted;
} }
} }

View File

@ -16,6 +16,8 @@
*/ */
package org.apache.activemq.usecases; package org.apache.activemq.usecases;
import static org.junit.Assert.assertTrue;
import java.io.File; import java.io.File;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
@ -27,6 +29,7 @@ import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.jms.Connection; import javax.jms.Connection;
import javax.jms.ConnectionFactory; import javax.jms.ConnectionFactory;
import javax.jms.JMSException; import javax.jms.JMSException;
@ -53,9 +56,6 @@ import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertTrue;
public class DurableSubProcessConcurrentCommitActivateNoDuplicateTest { public class DurableSubProcessConcurrentCommitActivateNoDuplicateTest {
private static final Logger LOG = LoggerFactory.getLogger(DurableSubProcessConcurrentCommitActivateNoDuplicateTest.class); private static final Logger LOG = LoggerFactory.getLogger(DurableSubProcessConcurrentCommitActivateNoDuplicateTest.class);
public static final long RUNTIME = 5 * 60 * 1000; public static final long RUNTIME = 5 * 60 * 1000;

View File

@ -16,6 +16,9 @@
*/ */
package org.apache.activemq.usecases; package org.apache.activemq.usecases;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File; import java.io.File;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
@ -26,6 +29,7 @@ import java.util.Vector;
import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.jms.Connection; import javax.jms.Connection;
import javax.jms.ConnectionFactory; import javax.jms.ConnectionFactory;
import javax.jms.JMSException; import javax.jms.JMSException;
@ -33,6 +37,7 @@ import javax.jms.Message;
import javax.jms.MessageConsumer; import javax.jms.MessageConsumer;
import javax.jms.MessageProducer; import javax.jms.MessageProducer;
import javax.jms.Session; import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
@ -47,10 +52,6 @@ import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class DurableSubProcessWithRestartTest { public class DurableSubProcessWithRestartTest {
private static final Logger LOG = LoggerFactory.getLogger(DurableSubProcessWithRestartTest.class); private static final Logger LOG = LoggerFactory.getLogger(DurableSubProcessWithRestartTest.class);
public static final long RUNTIME = 5 * 60 * 1000; public static final long RUNTIME = 5 * 60 * 1000;
@ -93,9 +94,6 @@ public class DurableSubProcessWithRestartTest {
if (ALLOW_SUBSCRIPTION_ABANDONMENT) if (ALLOW_SUBSCRIPTION_ABANDONMENT)
houseKeeper.start(); houseKeeper.start();
if (BROKER_RESTART <= 0)
Thread.sleep(RUNTIME);
else {
long end = System.currentTimeMillis() + RUNTIME; long end = System.currentTimeMillis() + RUNTIME;
while (true) { while (true) {
@ -109,7 +107,6 @@ public class DurableSubProcessWithRestartTest {
restartBroker(); restartBroker();
} }
}
} catch (Throwable e) { } catch (Throwable e) {
exit("ProcessTest.testProcess failed.", e); exit("ProcessTest.testProcess failed.", e);
} }
@ -588,6 +585,7 @@ public class DurableSubProcessWithRestartTest {
/** /**
* Checks if the message was not delivered fast enough. * Checks if the message was not delivered fast enough.
*/ */
@SuppressWarnings("unused")
public void checkDeliveryTime(Message message) throws JMSException { public void checkDeliveryTime(Message message) throws JMSException {
long creation = message.getJMSTimestamp(); long creation = message.getJMSTimestamp();
long min = System.currentTimeMillis() - (offline.max + online.min) long min = System.currentTimeMillis() - (offline.max + online.min)

View File

@ -736,9 +736,7 @@ public class DurableSubscriptionOfflineTest extends org.apache.activemq.TestSupp
session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(null); MessageProducer producer = session.createProducer(null);
int sent = 0;
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
sent++;
Message message = session.createMessage(); Message message = session.createMessage();
message.setStringProperty("filter", "true"); message.setStringProperty("filter", "true");
producer.send(topic, message); producer.send(topic, message);

View File

@ -25,9 +25,9 @@ import javax.jms.MessageProducer;
import javax.jms.Session; import javax.jms.Session;
import javax.jms.TopicSubscriber; import javax.jms.TopicSubscriber;
import javax.management.MBeanServer; import javax.management.MBeanServer;
import javax.management.ObjectName;
import junit.framework.Test; import junit.framework.Test;
import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
@ -74,7 +74,8 @@ public class DurableSubscriptionSelectorTest extends org.apache.activemq.TestSup
sendMessage(true); sendMessage(true);
Wait.waitFor(new Wait.Condition() { public boolean isSatisified() { return received >= 1;} }, 10000); Wait.waitFor(new Wait.Condition() { @Override
public boolean isSatisified() { return received >= 1;} }, 10000);
assertEquals("Message is not received.", 1, received); assertEquals("Message is not received.", 1, received);
@ -92,6 +93,7 @@ public class DurableSubscriptionSelectorTest extends org.apache.activemq.TestSup
TopicSubscriber subscriber = session.createDurableSubscriber(topic, "subName", "filter=true", false); TopicSubscriber subscriber = session.createDurableSubscriber(topic, "subName", "filter=true", false);
subscriber.setMessageListener(new MessageListener() { subscriber.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
received++; received++;
} }
@ -123,18 +125,6 @@ public class DurableSubscriptionSelectorTest extends org.apache.activemq.TestSup
producerConnection = null; producerConnection = null;
} }
private int getPendingQueueSize() throws Exception {
ObjectName[] subs = broker.getAdminView().getDurableTopicSubscribers();
for (ObjectName sub: subs) {
if ("cliID".equals(mbs.getAttribute(sub, "ClientId"))) {
Integer size = (Integer) mbs.getAttribute(sub, "PendingQueueSize");
return size != null ? size : 0;
}
}
assertTrue(false);
return -1;
}
private void startBroker(boolean deleteMessages) throws Exception { private void startBroker(boolean deleteMessages) throws Exception {
broker = new BrokerService(); broker = new BrokerService();
broker.setBrokerName("test-broker"); broker.setBrokerName("test-broker");
@ -164,6 +154,7 @@ public class DurableSubscriptionSelectorTest extends org.apache.activemq.TestSup
broker = null; broker = null;
} }
@Override
protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { protected ActiveMQConnectionFactory createConnectionFactory() throws Exception {
return new ActiveMQConnectionFactory("vm://test-broker?jms.watchTopicAdvisories=false&waitForStart=5000&create=false"); return new ActiveMQConnectionFactory("vm://test-broker?jms.watchTopicAdvisories=false&waitForStart=5000&create=false");
} }

View File

@ -16,14 +16,21 @@
*/ */
package org.apache.activemq.usecases; package org.apache.activemq.usecases;
import java.io.File;
import java.util.List;
import javax.jms.Connection;
import javax.jms.Session;
import javax.management.InstanceNotFoundException;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.TestSupport; import org.apache.activemq.TestSupport;
import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.broker.jmx.DurableSubscriptionViewMBean; import org.apache.activemq.broker.jmx.DurableSubscriptionViewMBean;
import org.apache.activemq.broker.jmx.SubscriptionView;
import org.apache.activemq.broker.jmx.SubscriptionViewMBean;
import org.apache.activemq.broker.region.Destination; import org.apache.activemq.broker.region.Destination;
import org.apache.activemq.broker.region.DurableTopicSubscription; import org.apache.activemq.broker.region.DurableTopicSubscription;
import org.apache.activemq.broker.region.Subscription; import org.apache.activemq.broker.region.Subscription;
@ -31,14 +38,6 @@ import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.command.RemoveSubscriptionInfo; import org.apache.activemq.command.RemoveSubscriptionInfo;
import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter;
import javax.jms.Connection;
import javax.jms.Session;
import javax.management.*;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.util.List;
public class DurableSubscriptionUnsubscribeTest extends TestSupport { public class DurableSubscriptionUnsubscribeTest extends TestSupport {
BrokerService broker = null; BrokerService broker = null;
@ -283,6 +282,7 @@ public class DurableSubscriptionUnsubscribeTest extends TestSupport {
startBroker(false); startBroker(false);
} }
@Override
protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { protected ActiveMQConnectionFactory createConnectionFactory() throws Exception {
return new ActiveMQConnectionFactory("vm://" + getName() + "?waitForStart=5000&create=false"); return new ActiveMQConnectionFactory("vm://" + getName() + "?waitForStart=5000&create=false");
} }

View File

@ -16,6 +16,9 @@
*/ */
package org.apache.activemq.usecases; package org.apache.activemq.usecases;
import static org.apache.activemq.TestSupport.getDestination;
import static org.apache.activemq.TestSupport.getDestinationStatistics;
import java.io.File; import java.io.File;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
@ -42,9 +45,6 @@ import org.apache.activemq.store.amq.AMQPersistenceAdapter;
import org.apache.activemq.util.Wait; import org.apache.activemq.util.Wait;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static org.apache.activemq.TestSupport.getDestination;
import static org.apache.activemq.TestSupport.getDestinationStatistics;
public class ExpiredMessagesTest extends CombinationTestSupport { public class ExpiredMessagesTest extends CombinationTestSupport {
@ -69,6 +69,7 @@ public class ExpiredMessagesTest extends CombinationTestSupport {
junit.textui.TestRunner.run(suite()); junit.textui.TestRunner.run(suite());
} }
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
final boolean deleteAllMessages = true; final boolean deleteAllMessages = true;
broker = createBroker(deleteAllMessages, 100); broker = createBroker(deleteAllMessages, 100);
@ -87,6 +88,7 @@ public class ExpiredMessagesTest extends CombinationTestSupport {
final AtomicLong received = new AtomicLong(); final AtomicLong received = new AtomicLong();
Thread consumerThread = new Thread("Consumer Thread") { Thread consumerThread = new Thread("Consumer Thread") {
@Override
public void run() { public void run() {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
try { try {
@ -109,6 +111,7 @@ public class ExpiredMessagesTest extends CombinationTestSupport {
final int numMessagesToSend = 10000; final int numMessagesToSend = 10000;
Thread producingThread = new Thread("Producing Thread") { Thread producingThread = new Thread("Producing Thread") {
@Override
public void run() { public void run() {
try { try {
int i = 0; int i = 0;
@ -132,6 +135,7 @@ public class ExpiredMessagesTest extends CombinationTestSupport {
// wait for all to inflight to expire // wait for all to inflight to expire
assertTrue("all inflight messages expired ", Wait.waitFor(new Wait.Condition() { assertTrue("all inflight messages expired ", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
return view.getInflight().getCount() == 0; return view.getInflight().getCount() == 0;
} }
@ -143,6 +147,7 @@ public class ExpiredMessagesTest extends CombinationTestSupport {
// wait for all sent to get delivered and expire // wait for all sent to get delivered and expire
assertTrue("all sent messages expired ", Wait.waitFor(new Wait.Condition() { assertTrue("all sent messages expired ", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
long oldEnqueues = view.getEnqueues().getCount(); long oldEnqueues = view.getEnqueues().getCount();
Thread.sleep(200); Thread.sleep(200);
@ -159,6 +164,7 @@ public class ExpiredMessagesTest extends CombinationTestSupport {
assertTrue("got at least what did not expire", received.get() >= view.getDequeues().getCount() - view.getExpired().getCount()); assertTrue("got at least what did not expire", received.get() >= view.getDequeues().getCount() - view.getExpired().getCount());
assertTrue("all messages expired - queue size gone to zero " + view.getMessages().getCount(), Wait.waitFor(new Wait.Condition() { assertTrue("all messages expired - queue size gone to zero " + view.getMessages().getCount(), Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
LOG.info("Stats: received: " + received.get() + ", size= " + view.getMessages().getCount() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() LOG.info("Stats: received: " + received.get() + ", size= " + view.getMessages().getCount() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount()
+ ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount());
@ -174,6 +180,7 @@ public class ExpiredMessagesTest extends CombinationTestSupport {
+ ", dispatched: " + dlqView.getDispatched().getCount() + ", inflight: " + dlqView.getInflight().getCount() + ", expiries: " + dlqView.getExpired().getCount()); + ", dispatched: " + dlqView.getDispatched().getCount() + ", inflight: " + dlqView.getInflight().getCount() + ", expiries: " + dlqView.getExpired().getCount());
Wait.waitFor(new Wait.Condition() { Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
return totalExpiredCount == dlqView.getMessages().getCount(); return totalExpiredCount == dlqView.getMessages().getCount();
} }
@ -190,6 +197,7 @@ public class ExpiredMessagesTest extends CombinationTestSupport {
dlqConsumer.setMessageListener(dlqListener); dlqConsumer.setMessageListener(dlqListener);
Wait.waitFor(new Wait.Condition() { Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
return totalExpiredCount == dlqListener.count; return totalExpiredCount == dlqListener.count;
} }
@ -202,6 +210,7 @@ public class ExpiredMessagesTest extends CombinationTestSupport {
int count = 0; int count = 0;
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
count++; count++;
} }
@ -228,6 +237,7 @@ public class ExpiredMessagesTest extends CombinationTestSupport {
producer.setDeliveryMode(DeliveryMode.PERSISTENT); producer.setDeliveryMode(DeliveryMode.PERSISTENT);
Thread producingThread = new Thread("Producing Thread") { Thread producingThread = new Thread("Producing Thread") {
@Override
public void run() { public void run() {
try { try {
int i = 0; int i = 0;
@ -266,6 +276,7 @@ public class ExpiredMessagesTest extends CombinationTestSupport {
broker = createBroker(deleteAllMessages, 5000); broker = createBroker(deleteAllMessages, 5000);
Wait.waitFor(new Wait.Condition() { Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
DestinationStatistics view = getDestinationStatistics(broker, destination); DestinationStatistics view = getDestinationStatistics(broker, destination);
LOG.info("Stats: size: " + view.getMessages().getCount() + ", enqueues: " LOG.info("Stats: size: " + view.getMessages().getCount() + ", enqueues: "
@ -311,6 +322,7 @@ public class ExpiredMessagesTest extends CombinationTestSupport {
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
connection.stop(); connection.stop();
broker.stop(); broker.stop();

View File

@ -16,11 +16,14 @@
*/ */
package org.apache.activemq.usecases; package org.apache.activemq.usecases;
import static org.junit.Assert.assertTrue;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.Vector; import java.util.Vector;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import javax.jms.Connection; import javax.jms.Connection;
import javax.jms.DeliveryMode; import javax.jms.DeliveryMode;
import javax.jms.JMSException; import javax.jms.JMSException;
@ -31,20 +34,17 @@ import javax.jms.MessageProducer;
import javax.jms.Session; import javax.jms.Session;
import javax.jms.TextMessage; import javax.jms.TextMessage;
import javax.jms.Topic; import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.region.policy.PolicyEntry; import org.apache.activemq.broker.region.policy.PolicyEntry;
import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.broker.region.policy.PolicyMap;
import org.apache.activemq.broker.region.policy.StorePendingDurableSubscriberMessageStoragePolicy;
import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertTrue;
public class JdbcDurableSubDupTest { public class JdbcDurableSubDupTest {
@ -63,7 +63,7 @@ public class JdbcDurableSubDupTest {
final int TO_RECEIVE = 5000; final int TO_RECEIVE = 5000;
BrokerService broker = null; BrokerService broker = null;
Vector<Throwable> exceptions = new Vector(); Vector<Throwable> exceptions = new Vector<Throwable>();
final int MAX_MESSAGES = 100000; final int MAX_MESSAGES = 100000;
int[] dupChecker = new int[MAX_MESSAGES]; int[] dupChecker = new int[MAX_MESSAGES];
@ -185,6 +185,7 @@ public class JdbcDurableSubDupTest {
} }
} }
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
++count; ++count;
@ -229,6 +230,7 @@ public class JdbcDurableSubDupTest {
int priorityModulator = 10; int priorityModulator = 10;
@Override
public void run() { public void run() {
Connection connection; Connection connection;

View File

@ -77,7 +77,7 @@ public class MessageGroupCloseTest extends TestCase {
if (i % 100 == 0) { if (i % 100 == 0) {
LOG.info("Sent messages: group=" + i); LOG.info("Sent messages: group=" + i);
} }
messageGroupCount++; setMessageGroupCount(getMessageGroupCount() + 1);
} }
LOG.info(messagesSent+" messages sent"); LOG.info(messagesSent+" messages sent");
latchMessagesCreated.countDown(); latchMessagesCreated.countDown();
@ -218,4 +218,18 @@ public class MessageGroupCloseTest extends TestCase {
messageGroups.put(groupId, count + 1); messageGroups.put(groupId, count + 1);
} }
} }
/**
* @return the messageGroupCount
*/
public int getMessageGroupCount() {
return messageGroupCount;
}
/**
* @param messageGroupCount the messageGroupCount to set
*/
public void setMessageGroupCount(int messageGroupCount) {
this.messageGroupCount = messageGroupCount;
}
} }

View File

@ -40,8 +40,6 @@ import org.apache.activemq.command.ActiveMQQueue;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
public class MessageGroupDelayedTest extends JmsTestSupport { public class MessageGroupDelayedTest extends JmsTestSupport {
public static final Logger log = LoggerFactory.getLogger(MessageGroupDelayedTest.class); public static final Logger log = LoggerFactory.getLogger(MessageGroupDelayedTest.class);
protected Connection connection; protected Connection connection;
@ -66,6 +64,7 @@ public class MessageGroupDelayedTest extends JmsTestSupport {
junit.textui.TestRunner.run(suite()); junit.textui.TestRunner.run(suite());
} }
@Override
public void setUp() throws Exception { public void setUp() throws Exception {
broker = createBroker(); broker = createBroker();
broker.start(); broker.start();
@ -77,6 +76,7 @@ public class MessageGroupDelayedTest extends JmsTestSupport {
connection.start(); connection.start();
} }
@Override
protected BrokerService createBroker() throws Exception { protected BrokerService createBroker() throws Exception {
BrokerService service = new BrokerService(); BrokerService service = new BrokerService();
service.setPersistent(false); service.setPersistent(false);
@ -95,6 +95,7 @@ public class MessageGroupDelayedTest extends JmsTestSupport {
return service; return service;
} }
@Override
public void tearDown() throws Exception { public void tearDown() throws Exception {
producer.close(); producer.close();
session.close(); session.close();
@ -102,8 +103,6 @@ public class MessageGroupDelayedTest extends JmsTestSupport {
broker.stop(); broker.stop();
} }
public void initCombosForTestDelayedDirectConnectionListener() { public void initCombosForTestDelayedDirectConnectionListener() {
addCombinationValues("consumersBeforeDispatchStarts", new Object[] { 0, 3, 5 }); addCombinationValues("consumersBeforeDispatchStarts", new Object[] { 0, 3, 5 });
addCombinationValues("timeBeforeDispatchStarts", new Object[] { 0, 100 }); addCombinationValues("timeBeforeDispatchStarts", new Object[] { 0, 100 });
@ -139,7 +138,6 @@ public class MessageGroupDelayedTest extends JmsTestSupport {
messageGroups.put("worker3", new HashSet<String>()); messageGroups.put("worker3", new HashSet<String>());
Worker worker3 = new Worker(connection, destination, "worker3", startSignal, doneSignal, counters, messageCount, messageGroups); Worker worker3 = new Worker(connection, destination, "worker3", startSignal, doneSignal, counters, messageCount, messageGroups);
new Thread(worker1).start(); new Thread(worker1).start();
new Thread(worker2).start(); new Thread(worker2).start();
new Thread(worker3).start(); new Thread(worker3).start();
@ -155,10 +153,10 @@ public class MessageGroupDelayedTest extends JmsTestSupport {
for (String worker : messageCount.keySet()) { for (String worker : messageCount.keySet()) {
log.info("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker)); log.info("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker));
assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker) assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker), 10, messageCount
, 10, messageCount.get(worker).intValue()); .get(worker).intValue());
assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker) assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker), 1, messageGroups
, 1, messageGroups.get(worker).size()); .get(worker).size());
} }
} }
@ -170,11 +168,11 @@ public class MessageGroupDelayedTest extends JmsTestSupport {
private CountDownLatch startSignal = null; private CountDownLatch startSignal = null;
private CountDownLatch doneSignal = null; private CountDownLatch doneSignal = null;
private int[] counters = null; private int[] counters = null;
private HashMap<String, Integer> messageCount; private final HashMap<String, Integer> messageCount;
private HashMap<String, Set<String>>messageGroups; private final HashMap<String, Set<String>> messageGroups;
private Worker(Connection connection, Destination queueName, String workerName, CountDownLatch startSignal, CountDownLatch doneSignal, int[] counters,
private Worker(Connection connection, Destination queueName, String workerName, CountDownLatch startSignal, CountDownLatch doneSignal, int[] counters, HashMap<String, Integer> messageCount, HashMap<String, Set<String>>messageGroups) { HashMap<String, Integer> messageCount, HashMap<String, Set<String>> messageGroups) {
this.connection = connection; this.connection = connection;
this.queueName = queueName; this.queueName = queueName;
this.workerName = workerName; this.workerName = workerName;
@ -193,6 +191,7 @@ public class MessageGroupDelayedTest extends JmsTestSupport {
messageGroups.put(workerName, groups); messageGroups.put(workerName, groups);
} }
@Override
public void run() { public void run() {
try { try {
@ -213,24 +212,21 @@ public class MessageGroupDelayedTest extends JmsTestSupport {
continue; continue;
String group = msg.getStringProperty("JMSXGroupID"); String group = msg.getStringProperty("JMSXGroupID");
boolean first = msg.getBooleanProperty("JMSXGroupFirstForConsumer"); msg.getBooleanProperty("JMSXGroupFirstForConsumer");
if ("A".equals(group)) { if ("A".equals(group)) {
--counters[0]; --counters[0];
update(group); update(group);
Thread.sleep(500); Thread.sleep(500);
} } else if ("B".equals(group)) {
else if("B".equals(group)) {
--counters[1]; --counters[1];
update(group); update(group);
Thread.sleep(100); Thread.sleep(100);
} } else if ("C".equals(group)) {
else if("C".equals(group)) {
--counters[2]; --counters[2];
update(group); update(group);
Thread.sleep(10); Thread.sleep(10);
} } else {
else {
log.warn("unknown group"); log.warn("unknown group");
} }
if (counters[0] != 0 || counters[1] != 0 || counters[2] != 0) { if (counters[0] != 0 || counters[1] != 0 || counters[2] != 0) {

View File

@ -17,19 +17,18 @@
package org.apache.activemq.usecases; package org.apache.activemq.usecases;
import java.io.Serializable;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectStreamException; import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
public class MyObject implements Serializable { public class MyObject implements Serializable {
private static final long serialVersionUID = -2505777188753549398L;
private String message; private String message;
private AtomicInteger writeObjectCalled = new AtomicInteger(0); private final AtomicInteger writeObjectCalled = new AtomicInteger(0);
private AtomicInteger readObjectCalled = new AtomicInteger(0); private final AtomicInteger readObjectCalled = new AtomicInteger(0);
private AtomicInteger readObjectNoDataCalled = new AtomicInteger(0); private final AtomicInteger readObjectNoDataCalled = new AtomicInteger(0);
public MyObject(String message) { public MyObject(String message) {
this.setMessage(message); this.setMessage(message);
@ -53,10 +52,6 @@ public class MyObject implements Serializable {
readObjectCalled.incrementAndGet(); readObjectCalled.incrementAndGet();
} }
private void readObjectNoData() throws ObjectStreamException {
readObjectNoDataCalled.incrementAndGet();
}
public int getWriteObjectCalled() { public int getWriteObjectCalled() {
return writeObjectCalled.get(); return writeObjectCalled.get();
} }

View File

@ -56,7 +56,7 @@ public class NewConsumerCreatesDestinationTest extends EmbeddedBrokerAndConnecti
} }
protected void assertDestinationCreated(Destination destination, boolean expected) throws Exception { protected void assertDestinationCreated(Destination destination, boolean expected) throws Exception {
Set answer = broker.getBroker().getDestinations((ActiveMQDestination) destination); Set<?> answer = broker.getBroker().getDestinations((ActiveMQDestination) destination);
int size = expected ? 1 : 0; int size = expected ? 1 : 0;
assertEquals("Size of found destinations: " + answer, size, answer.size()); assertEquals("Size of found destinations: " + answer, size, answer.size());
} }

View File

@ -16,6 +16,19 @@
*/ */
package org.apache.activemq.usecases; package org.apache.activemq.usecases;
import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.util.Enumeration;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.QueueBrowser;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector; import org.apache.activemq.broker.TransportConnector;
@ -26,13 +39,6 @@ import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.jms.*;
import java.net.URI;
import java.util.Enumeration;
import static org.junit.Assert.*;
public class QueueBrowsingTest { public class QueueBrowsingTest {
private static final Logger LOG = LoggerFactory.getLogger(QueueBrowsingTest.class); private static final Logger LOG = LoggerFactory.getLogger(QueueBrowsingTest.class);
@ -80,11 +86,12 @@ public class QueueBrowsingTest {
} }
QueueBrowser browser = session.createBrowser(queue); QueueBrowser browser = session.createBrowser(queue);
Enumeration enumeration = browser.getEnumeration(); Enumeration<?> enumeration = browser.getEnumeration();
int received = 0; int received = 0;
while (enumeration.hasMoreElements()) { while (enumeration.hasMoreElements()) {
Message m = (Message) enumeration.nextElement(); Message m = (Message) enumeration.nextElement();
received++; received++;
LOG.info("Browsed message " + received + ": " + m.getJMSMessageID());
} }
browser.close(); browser.close();
@ -117,11 +124,12 @@ public class QueueBrowsingTest {
public void run() { public void run() {
try { try {
QueueBrowser browser = session.createBrowser(queue); QueueBrowser browser = session.createBrowser(queue);
Enumeration enumeration = browser.getEnumeration(); Enumeration<?> enumeration = browser.getEnumeration();
int received = 0; int received = 0;
while (enumeration.hasMoreElements()) { while (enumeration.hasMoreElements()) {
Message m = (Message) enumeration.nextElement(); Message m = (Message) enumeration.nextElement();
received++; received++;
LOG.info("Browsed message " + received + ": " + m.getJMSMessageID());
} }
assertEquals("Browsed all messages", messageToSend, received); assertEquals("Browsed all messages", messageToSend, received);
} catch (Exception e) { } catch (Exception e) {
@ -139,7 +147,7 @@ public class QueueBrowsingTest {
MessageConsumer consumer = session.createConsumer(queue); MessageConsumer consumer = session.createConsumer(queue);
int received = 0; int received = 0;
while (true) { while (true) {
Message m = (Message) consumer.receive(1000); Message m = consumer.receive(1000);
if (m == null) if (m == null)
break; break;
received++; received++;
@ -155,7 +163,6 @@ public class QueueBrowsingTest {
browserThread.join(); browserThread.join();
consumerThread.join(); consumerThread.join();
} }
@Test @Test
@ -180,7 +187,7 @@ public class QueueBrowsingTest {
} }
QueueBrowser browser = session.createBrowser(queue); QueueBrowser browser = session.createBrowser(queue);
Enumeration enumeration = browser.getEnumeration(); Enumeration<?> enumeration = browser.getEnumeration();
int received = 0; int received = 0;
while (enumeration.hasMoreElements()) { while (enumeration.hasMoreElements()) {
Message m = (Message) enumeration.nextElement(); Message m = (Message) enumeration.nextElement();
@ -189,10 +196,6 @@ public class QueueBrowsingTest {
} }
browser.close(); browser.close();
assertEquals(3, received); assertEquals(3, received);
} }
} }

View File

@ -27,10 +27,12 @@ import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory; import java.net.URLStreamHandlerFactory;
import java.util.Map; import java.util.Map;
import java.util.Vector; import java.util.Vector;
import javax.jms.MessageConsumer; import javax.jms.MessageConsumer;
import javax.jms.MessageProducer; import javax.jms.MessageProducer;
import javax.jms.Session; import javax.jms.Session;
import javax.jms.TextMessage; import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQSession; import org.apache.activemq.ActiveMQSession;
@ -56,7 +58,7 @@ public class RequestReplyNoAdvisoryNetworkTest extends JmsMultipleBrokersTestSup
ActiveMQQueue sendQ = new ActiveMQQueue("sendQ"); ActiveMQQueue sendQ = new ActiveMQQueue("sendQ");
static final String connectionIdMarker = "ID:marker."; static final String connectionIdMarker = "ID:marker.";
ActiveMQTempQueue replyQWildcard = new ActiveMQTempQueue(connectionIdMarker + ">"); ActiveMQTempQueue replyQWildcard = new ActiveMQTempQueue(connectionIdMarker + ">");
private long receiveTimeout = 30000; private final long receiveTimeout = 30000;
public void testNonAdvisoryNetworkRequestReplyXmlConfig() throws Exception { public void testNonAdvisoryNetworkRequestReplyXmlConfig() throws Exception {
final String xmlConfigString = new String( final String xmlConfigString = new String(
@ -197,9 +199,9 @@ public class RequestReplyNoAdvisoryNetworkTest extends JmsMultipleBrokersTestSup
assertTrue("all temps are gone on " + regionBroker.getBrokerName(), Wait.waitFor(new Wait.Condition(){ assertTrue("all temps are gone on " + regionBroker.getBrokerName(), Wait.waitFor(new Wait.Condition(){
@Override @Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
Map tempTopics = regionBroker.getTempTopicRegion().getDestinationMap(); Map<?,?> tempTopics = regionBroker.getTempTopicRegion().getDestinationMap();
LOG.info("temp topics on " + regionBroker.getBrokerName() + ", " + tempTopics); LOG.info("temp topics on " + regionBroker.getBrokerName() + ", " + tempTopics);
Map tempQ = regionBroker.getTempQueueRegion().getDestinationMap(); Map<?,?> tempQ = regionBroker.getTempQueueRegion().getDestinationMap();
LOG.info("temp queues on " + regionBroker.getBrokerName() + ", " + tempQ); LOG.info("temp queues on " + regionBroker.getBrokerName() + ", " + tempQ);
return tempQ.isEmpty() && tempTopics.isEmpty(); return tempQ.isEmpty() && tempTopics.isEmpty();
} }
@ -236,6 +238,7 @@ public class RequestReplyNoAdvisoryNetworkTest extends JmsMultipleBrokersTestSup
} }
} }
@Override
public void tearDown() throws Exception { public void tearDown() throws Exception {
for (BrokerService broker: brokers) { for (BrokerService broker: brokers) {
broker.stop(); broker.stop();

View File

@ -17,6 +17,8 @@
package org.apache.activemq.usecases; package org.apache.activemq.usecases;
import static org.junit.Assert.assertTrue;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.ArrayList; import java.util.ArrayList;
@ -25,6 +27,7 @@ import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.jms.Connection; import javax.jms.Connection;
import javax.jms.Destination; import javax.jms.Destination;
import javax.jms.JMSException; import javax.jms.JMSException;
@ -33,6 +36,7 @@ import javax.jms.MessageConsumer;
import javax.jms.MessageProducer; import javax.jms.MessageProducer;
import javax.jms.Session; import javax.jms.Session;
import javax.jms.TextMessage; import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQSession; import org.apache.activemq.ActiveMQSession;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
@ -43,9 +47,6 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class RequestReplyToTopicViaThreeNetworkHopsTest { public class RequestReplyToTopicViaThreeNetworkHopsTest {
protected static final int CONCURRENT_CLIENT_COUNT = 5; protected static final int CONCURRENT_CLIENT_COUNT = 5;
protected static final int CONCURRENT_SERVER_COUNT = 5; protected static final int CONCURRENT_SERVER_COUNT = 5;
@ -69,8 +70,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
LOG = LogFactory.getLog(RequestReplyToTopicViaThreeNetworkHopsTest.class); LOG = LogFactory.getLog(RequestReplyToTopicViaThreeNetworkHopsTest.class);
} }
public RequestReplyToTopicViaThreeNetworkHopsTest() public RequestReplyToTopicViaThreeNetworkHopsTest() throws Exception {
throws Exception {
edge1 = new EmbeddedTcpBroker("edge", 1); edge1 = new EmbeddedTcpBroker("edge", 1);
edge2 = new EmbeddedTcpBroker("edge", 2); edge2 = new EmbeddedTcpBroker("edge", 2);
core1 = new EmbeddedTcpBroker("core", 1); core1 = new EmbeddedTcpBroker("core", 1);
@ -80,7 +80,6 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
edge1.coreConnectTo(core1, duplex); edge1.coreConnectTo(core1, duplex);
edge2.coreConnectTo(core2, duplex); edge2.coreConnectTo(core2, duplex);
core1.coreConnectTo(core2, duplex); core1.coreConnectTo(core2, duplex);
} }
public void logMessage(String msg) { public void logMessage(String msg) {
@ -88,8 +87,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
System.out.flush(); System.out.flush();
} }
public void testMessages(Session sess, MessageProducer req_prod, Destination resp_dest, int num_msg) public void testMessages(Session sess, MessageProducer req_prod, Destination resp_dest, int num_msg) throws Exception {
throws Exception {
MessageConsumer resp_cons; MessageConsumer resp_cons;
TextMessage msg; TextMessage msg;
MessageClient cons_client; MessageClient cons_client;
@ -130,7 +128,6 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
else else
LOG.debug("Consumer client shutdown incomplete!!!"); LOG.debug("Consumer client shutdown incomplete!!!");
// //
// Check that the correct number of messages was received. // Check that the correct number of messages was received.
// //
@ -144,15 +141,13 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
if (cons_client.getNumMsgReceived() == 0) if (cons_client.getNumMsgReceived() == 0)
fatalTestError = true; fatalTestError = true;
LOG.error("Have " + cons_client.getNumMsgReceived() + " messages; expected " + tot_expected + LOG.error("Have " + cons_client.getNumMsgReceived() + " messages; expected " + tot_expected + " on destination " + resp_dest);
" on destination " + resp_dest);
} }
resp_cons.close(); resp_cons.close();
} }
protected void sendWithRetryOnDeletedDest(MessageProducer prod, Message msg) protected void sendWithRetryOnDeletedDest(MessageProducer prod, Message msg) throws JMSException {
throws JMSException {
try { try {
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled())
LOG.debug("SENDING REQUEST message " + msg); LOG.debug("SENDING REQUEST message " + msg);
@ -167,12 +162,10 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
/** /**
* Test one destination between the given "producer broker" and "consumer broker" specified. * Test one destination between the given "producer broker" and "consumer broker" specified.
*/ */
public void testOneDest(Connection conn, Session sess, Destination cons_dest, int num_msg) public void testOneDest(Connection conn, Session sess, Destination cons_dest, int num_msg) throws Exception {
throws Exception {
Destination prod_dest; Destination prod_dest;
MessageProducer msg_prod; MessageProducer msg_prod;
// //
// Create the Producer to the echo request Queue // Create the Producer to the echo request Queue
// //
@ -180,7 +173,6 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
prod_dest = sess.createQueue("echo"); prod_dest = sess.createQueue("echo");
msg_prod = sess.createProducer(prod_dest); msg_prod = sess.createProducer(prod_dest);
// //
// Pass messages around. // Pass messages around.
// //
@ -189,57 +181,45 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
msg_prod.close(); msg_prod.close();
} }
/** /**
* TEST TEMPORARY TOPICS * TEST TEMPORARY TOPICS
*/ */
public void testTempTopic(String prod_broker_url, String cons_broker_url) public void testTempTopic(String prod_broker_url, String cons_broker_url) throws Exception {
throws Exception {
Connection conn; Connection conn;
Session sess; Session sess;
Destination cons_dest; Destination cons_dest;
int echo_id;
int num_msg; int num_msg;
num_msg = 5; num_msg = 5;
LOG.debug("TESTING TEMP TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + LOG.debug("TESTING TEMP TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)");
" messages)");
// //
// Connect to the bus. // Connect to the bus.
// //
conn = createConnection(cons_broker_url); conn = createConnection(cons_broker_url);
conn.start(); conn.start();
sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
// //
// Create the destination on which messages are being tested. // Create the destination on which messages are being tested.
// //
LOG.trace("Creating destination"); LOG.trace("Creating destination");
cons_dest = sess.createTemporaryTopic(); cons_dest = sess.createTemporaryTopic();
testOneDest(conn, sess, cons_dest, num_msg); testOneDest(conn, sess, cons_dest, num_msg);
// //
// Cleanup // Cleanup
// //
sess.close(); sess.close();
conn.close(); conn.close();
} }
/** /**
* TEST TOPICS * TEST TOPICS
*/ */
public void testTopic(String prod_broker_url, String cons_broker_url) public void testTopic(String prod_broker_url, String cons_broker_url) throws Exception {
throws Exception {
int num_msg; int num_msg;
Connection conn; Connection conn;
@ -250,19 +230,15 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
num_msg = 5; num_msg = 5;
LOG.info("TESTING TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + LOG.info("TESTING TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)");
" messages)");
conn = createConnection(cons_broker_url); conn = createConnection(cons_broker_url);
conn.start(); conn.start();
sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
// //
// Create the destination on which messages are being tested. // Create the destination on which messages are being tested.
// //
topic_name = "topotest2.perm.topic"; topic_name = "topotest2.perm.topic";
LOG.trace("Removing existing Topic"); LOG.trace("Removing existing Topic");
removeTopic(conn, topic_name); removeTopic(conn, topic_name);
@ -271,23 +247,18 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
testOneDest(conn, sess, cons_dest, num_msg); testOneDest(conn, sess, cons_dest, num_msg);
// //
// Cleanup // Cleanup
// //
removeTopic(conn, topic_name); removeTopic(conn, topic_name);
sess.close(); sess.close();
conn.close(); conn.close();
} }
/** /**
* TEST TEMPORARY QUEUES * TEST TEMPORARY QUEUES
*/ */
public void testTempQueue(String prod_broker_url, String cons_broker_url) public void testTempQueue(String prod_broker_url, String cons_broker_url) throws Exception {
throws Exception {
int echo_id;
int num_msg; int num_msg;
Connection conn; Connection conn;
@ -297,43 +268,34 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
num_msg = 5; num_msg = 5;
LOG.info("TESTING TEMP QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + LOG.info("TESTING TEMP QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)");
" messages)");
// //
// Connect to the bus. // Connect to the bus.
// //
conn = createConnection(cons_broker_url); conn = createConnection(cons_broker_url);
conn.start(); conn.start();
sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
// //
// Create the destination on which messages are being tested. // Create the destination on which messages are being tested.
// //
LOG.trace("Creating destination"); LOG.trace("Creating destination");
cons_dest = sess.createTemporaryQueue(); cons_dest = sess.createTemporaryQueue();
testOneDest(conn, sess, cons_dest, num_msg); testOneDest(conn, sess, cons_dest, num_msg);
// //
// Cleanup // Cleanup
// //
sess.close(); sess.close();
conn.close(); conn.close();
} }
/** /**
* TEST QUEUES * TEST QUEUES
*/ */
public void testQueue(String prod_broker_url, String cons_broker_url) public void testQueue(String prod_broker_url, String cons_broker_url) throws Exception {
throws Exception {
int num_msg; int num_msg;
Connection conn; Connection conn;
@ -344,15 +306,12 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
num_msg = 5; num_msg = 5;
LOG.info("TESTING QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + LOG.info("TESTING QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)");
" messages)");
conn = createConnection(cons_broker_url); conn = createConnection(cons_broker_url);
conn.start(); conn.start();
sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
// //
// Create the destination on which messages are being tested. // Create the destination on which messages are being tested.
// //
@ -364,15 +323,13 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
testOneDest(conn, sess, cons_dest, num_msg); testOneDest(conn, sess, cons_dest, num_msg);
removeQueue(conn, queue_name); removeQueue(conn, queue_name);
sess.close(); sess.close();
conn.close(); conn.close();
} }
@Test @Test
public void runWithTempTopicReplyTo() public void runWithTempTopicReplyTo() throws Exception {
throws Exception {
EchoService echo_svc; EchoService echo_svc;
TopicTrafficGenerator traffic_gen; TopicTrafficGenerator traffic_gen;
Thread start1; Thread start1;
@ -390,16 +347,15 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
// Execute up to 20 clients at a time to simulate that load. // Execute up to 20 clients at a time to simulate that load.
// //
clientExecPool = new ThreadPoolExecutor(CONCURRENT_CLIENT_COUNT, CONCURRENT_CLIENT_COUNT, clientExecPool = new ThreadPoolExecutor(CONCURRENT_CLIENT_COUNT, CONCURRENT_CLIENT_COUNT, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10000));
0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10000));
clientCompletionLatch = new CountDownLatch(TOTAL_CLIENT_ITER); clientCompletionLatch = new CountDownLatch(TOTAL_CLIENT_ITER);
// Use threads to avoid startup deadlock since the first broker started waits until // Use threads to avoid startup deadlock since the first broker started waits until
// it knows the name of the remote broker before finishing its startup, which means // it knows the name of the remote broker before finishing its startup, which means
// the remote must already be running. // the remote must already be running.
start1 = new Thread() { start1 = new Thread() {
@Override
public void run() { public void run() {
try { try {
edge1.start(); edge1.start();
@ -410,6 +366,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
}; };
start2 = new Thread() { start2 = new Thread() {
@Override
public void run() { public void run() {
try { try {
edge2.start(); edge2.start();
@ -420,6 +377,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
}; };
start3 = new Thread() { start3 = new Thread() {
@Override
public void run() { public void run() {
try { try {
core1.start(); core1.start();
@ -430,6 +388,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
}; };
start4 = new Thread() { start4 = new Thread() {
@Override
public void run() { public void run() {
try { try {
core2.start(); core2.start();
@ -452,14 +411,12 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
traffic_gen = new TopicTrafficGenerator(edge1.getConnectionUrl(), edge2.getConnectionUrl()); traffic_gen = new TopicTrafficGenerator(edge1.getConnectionUrl(), edge2.getConnectionUrl());
traffic_gen.start(); traffic_gen.start();
// //
// Now start the echo service with that queue. // Now start the echo service with that queue.
// //
echo_svc = new EchoService("echo", edge1.getConnectionUrl()); echo_svc = new EchoService("echo", edge1.getConnectionUrl());
echo_svc.start(); echo_svc.start();
// //
// Run the tests on Temp Topics. // Run the tests on Temp Topics.
// //
@ -468,10 +425,10 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
iter = 0; iter = 0;
while ((iter < TOTAL_CLIENT_ITER) && (!fatalTestError)) { while ((iter < TOTAL_CLIENT_ITER) && (!fatalTestError)) {
clientExecPool.execute(new Runnable() { clientExecPool.execute(new Runnable() {
@Override
public void run() { public void run() {
try { try {
RequestReplyToTopicViaThreeNetworkHopsTest.this.testTempTopic(edge1.getConnectionUrl(), RequestReplyToTopicViaThreeNetworkHopsTest.this.testTempTopic(edge1.getConnectionUrl(), edge2.getConnectionUrl());
edge2.getConnectionUrl());
} catch (Exception exc) { } catch (Exception exc) {
LOG.error("test exception", exc); LOG.error("test exception", exc);
fatalTestError = true; fatalTestError = true;
@ -487,7 +444,8 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
boolean allDoneOnTime = clientCompletionLatch.await(20, TimeUnit.MINUTES); boolean allDoneOnTime = clientCompletionLatch.await(20, TimeUnit.MINUTES);
LOG.info("** FINISHED TEMP TOPIC TESTS AFTER " + iter + " ITERATIONS, testError:" + testError + ", fatal: " + fatalTestError + ", onTime:" + allDoneOnTime); LOG.info("** FINISHED TEMP TOPIC TESTS AFTER " + iter + " ITERATIONS, testError:" + testError + ", fatal: " + fatalTestError + ", onTime:"
+ allDoneOnTime);
Thread.sleep(100); Thread.sleep(100);
@ -500,46 +458,39 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
assertTrue("no errors", !testError); assertTrue("no errors", !testError);
} }
public void shutdown() public void shutdown() throws Exception {
throws Exception {
edge1.stop(); edge1.stop();
edge2.stop(); edge2.stop();
core1.stop(); core1.stop();
core2.stop(); core2.stop();
} }
protected Connection createConnection(String url) protected Connection createConnection(String url) throws Exception {
throws Exception {
return org.apache.activemq.ActiveMQConnection.makeConnection(url); return org.apache.activemq.ActiveMQConnection.makeConnection(url);
} }
protected static void removeQueue(Connection conn, String dest_name) protected static void removeQueue(Connection conn, String dest_name) throws java.lang.Exception {
throws java.lang.Exception {
org.apache.activemq.command.ActiveMQDestination dest; org.apache.activemq.command.ActiveMQDestination dest;
if (conn instanceof org.apache.activemq.ActiveMQConnection) { if (conn instanceof org.apache.activemq.ActiveMQConnection) {
dest = org.apache.activemq.command.ActiveMQDestination. dest = org.apache.activemq.command.ActiveMQDestination.createDestination(dest_name, org.apache.activemq.command.ActiveMQDestination.QUEUE_TYPE);
createDestination(dest_name, (byte) org.apache.activemq.command.ActiveMQDestination.QUEUE_TYPE);
((org.apache.activemq.ActiveMQConnection) conn).destroyDestination(dest); ((org.apache.activemq.ActiveMQConnection) conn).destroyDestination(dest);
} }
} }
protected static void removeTopic(Connection conn, String dest_name) protected static void removeTopic(Connection conn, String dest_name) throws java.lang.Exception {
throws java.lang.Exception {
org.apache.activemq.command.ActiveMQDestination dest; org.apache.activemq.command.ActiveMQDestination dest;
if (conn instanceof org.apache.activemq.ActiveMQConnection) { if (conn instanceof org.apache.activemq.ActiveMQConnection) {
dest = org.apache.activemq.command.ActiveMQDestination. dest = org.apache.activemq.command.ActiveMQDestination.createDestination(dest_name, org.apache.activemq.command.ActiveMQDestination.TOPIC_TYPE);
createDestination(dest_name, (byte) org.apache.activemq.command.ActiveMQDestination.TOPIC_TYPE);
((org.apache.activemq.ActiveMQConnection) conn).destroyDestination(dest); ((org.apache.activemq.ActiveMQConnection) conn).destroyDestination(dest);
} }
} }
public static String fmtMsgInfo(Message msg) public static String fmtMsgInfo(Message msg) throws Exception {
throws Exception {
StringBuilder msg_desc; StringBuilder msg_desc;
String prop; String prop;
Enumeration prop_enum; Enumeration<?> prop_enum;
msg_desc = new StringBuilder(); msg_desc = new StringBuilder();
msg_desc = new StringBuilder(); msg_desc = new StringBuilder();
@ -573,8 +524,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
protected String tcpUrl; protected String tcpUrl;
protected String fullUrl; protected String fullUrl;
public EmbeddedTcpBroker(String name, int number) public EmbeddedTcpBroker(String name, int number) throws Exception {
throws Exception {
brokerSvc = new BrokerService(); brokerSvc = new BrokerService();
synchronized (this.getClass()) { synchronized (this.getClass()) {
@ -599,8 +549,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
brokerSvc.addConnector(tcpUrl); brokerSvc.addConnector(tcpUrl);
} }
public Connection createConnection() public Connection createConnection() throws URISyntaxException, JMSException {
throws URISyntaxException, JMSException {
Connection result; Connection result;
result = org.apache.activemq.ActiveMQConnection.makeConnection(this.fullUrl); result = org.apache.activemq.ActiveMQConnection.makeConnection(this.fullUrl);
@ -612,9 +561,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
return this.fullUrl; return this.fullUrl;
} }
public void coreConnectTo(EmbeddedTcpBroker other, boolean duplex_f) throws Exception {
public void coreConnectTo(EmbeddedTcpBroker other, boolean duplex_f)
throws Exception {
this.makeConnectionTo(other, duplex_f, true); this.makeConnectionTo(other, duplex_f, true);
this.makeConnectionTo(other, duplex_f, false); this.makeConnectionTo(other, duplex_f, false);
if (!duplex_f) { if (!duplex_f) {
@ -623,24 +570,20 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
} }
} }
public void start() public void start() throws Exception {
throws Exception {
brokerSvc.start(); brokerSvc.start();
brokerSvc.waitUntilStarted(); brokerSvc.waitUntilStarted();
} }
public void stop() public void stop() throws Exception {
throws Exception {
brokerSvc.stop(); brokerSvc.stop();
} }
protected void makeConnectionTo(EmbeddedTcpBroker other, boolean duplex_f, boolean queue_f) throws Exception {
protected void makeConnectionTo(EmbeddedTcpBroker other, boolean duplex_f, boolean queue_f)
throws Exception {
NetworkConnector nw_conn; NetworkConnector nw_conn;
String prefix; String prefix;
ActiveMQDestination excl_dest; ActiveMQDestination excl_dest;
ArrayList excludes; ArrayList<ActiveMQDestination> excludes;
nw_conn = new DiscoveryNetworkConnector(new URI("static:(" + other.tcpUrl + ")")); nw_conn = new DiscoveryNetworkConnector(new URI("static:(" + other.tcpUrl + ")"));
nw_conn.setDuplex(duplex_f); nw_conn.setDuplex(duplex_f);
@ -663,7 +606,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
excl_dest = ActiveMQDestination.createDestination(">", ActiveMQDestination.QUEUE_TYPE); excl_dest = ActiveMQDestination.createDestination(">", ActiveMQDestination.QUEUE_TYPE);
} }
excludes = new ArrayList(); excludes = new ArrayList<ActiveMQDestination>();
excludes.add(excl_dest); excludes.add(excl_dest);
nw_conn.setExcludedDestinations(excludes); nw_conn.setExcludedDestinations(excludes);
@ -691,6 +634,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
shutdownLatch = new CountDownLatch(1); shutdownLatch = new CountDownLatch(1);
} }
@Override
public void run() { public void run() {
CountDownLatch latch; CountDownLatch latch;
@ -748,8 +692,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
return msgCount; return msgCount;
} }
protected void processMessages() protected void processMessages() throws Exception {
throws Exception {
Message in_msg; Message in_msg;
haveFirstSeq = false; haveFirstSeq = false;
@ -770,8 +713,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
msgCons.close(); msgCons.close();
} }
protected void checkMessage(Message in_msg) protected void checkMessage(Message in_msg) throws Exception {
throws Exception {
int seq; int seq;
LOG.debug("received message " + fmtMsgInfo(in_msg) + " from " + in_msg.getJMSDestination()); LOG.debug("received message " + fmtMsgInfo(in_msg) + " from " + in_msg.getJMSDestination());
@ -784,9 +726,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
seq = in_msg.getIntProperty("SEQ"); seq = in_msg.getIntProperty("SEQ");
if ((haveFirstSeq) && (seq != (lastSeq + 1))) { if ((haveFirstSeq) && (seq != (lastSeq + 1))) {
LOG.error("***ERROR*** incorrect sequence number; expected " + LOG.error("***ERROR*** incorrect sequence number; expected " + Integer.toString(lastSeq + 1) + " but have " + Integer.toString(seq));
Integer.toString(lastSeq + 1) + " but have " +
Integer.toString(seq));
testError = true; testError = true;
} }
@ -794,8 +734,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
lastSeq = seq; lastSeq = seq;
if (msgCount > expectedCount) { if (msgCount > expectedCount) {
LOG.error("*** have more messages than expected; have " + msgCount + LOG.error("*** have more messages than expected; have " + msgCount + "; expect " + expectedCount);
"; expect " + expectedCount);
testError = true; testError = true;
} }
@ -823,8 +762,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
protected ThreadPoolExecutor processorPool; protected ThreadPoolExecutor processorPool;
public EchoService(String dest, Connection broker_conn) public EchoService(String dest, Connection broker_conn) throws Exception {
throws Exception {
destName = dest; destName = dest;
jmsConn = broker_conn; jmsConn = broker_conn;
@ -838,16 +776,15 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
waitShutdown = new CountDownLatch(1); waitShutdown = new CountDownLatch(1);
processorPool = new ThreadPoolExecutor(CONCURRENT_SERVER_COUNT, CONCURRENT_SERVER_COUNT, processorPool = new ThreadPoolExecutor(CONCURRENT_SERVER_COUNT, CONCURRENT_SERVER_COUNT, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(
0, TimeUnit.SECONDS, 10000));
new ArrayBlockingQueue<Runnable>(10000));
} }
public EchoService(String dest, String broker_url) public EchoService(String dest, String broker_url) throws Exception {
throws Exception {
this(dest, ActiveMQConnection.makeConnection(broker_url)); this(dest, ActiveMQConnection.makeConnection(broker_url));
} }
@Override
public void run() { public void run() {
Message req; Message req;
@ -877,7 +814,6 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
} }
} }
/** /**
* Shut down the service, waiting up to 3 seconds for the service to terminate. * Shut down the service, waiting up to 3 seconds for the service to terminate.
*/ */
@ -916,8 +852,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
protected Message request; protected Message request;
public EchoRequestProcessor(Session sess, Message req) public EchoRequestProcessor(Session sess, Message req) throws Exception {
throws Exception {
this.session = sess; this.session = sess;
this.request = req; this.request = req;
@ -930,6 +865,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
this.msg_prod = session.createProducer(this.resp_dest); this.msg_prod = session.createProducer(this.resp_dest);
} }
@Override
public void run() { public void run() {
try { try {
this.processRequest(this.request); this.processRequest(this.request);
@ -941,8 +877,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
/** /**
* Process one request for the Echo Service. * Process one request for the Echo Service.
*/ */
protected void processRequest(Message req) protected void processRequest(Message req) throws Exception {
throws Exception {
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled())
LOG.debug("ECHO request message " + req.toString()); LOG.debug("ECHO request message " + req.toString());
@ -975,8 +910,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
protected boolean Shutdown_ind; protected boolean Shutdown_ind;
protected int send_count; protected int send_count;
public TopicTrafficGenerator(String url1, String url2) public TopicTrafficGenerator(String url1, String url2) throws Exception {
throws Exception {
conn1 = createConnection(url1); conn1 = createConnection(url1);
conn2 = createConnection(url2); conn2 = createConnection(url2);
@ -997,6 +931,7 @@ public class RequestReplyToTopicViaThreeNetworkHopsTest {
Shutdown_ind = true; Shutdown_ind = true;
} }
@Override
public void run() { public void run() {
Message msg; Message msg;

View File

@ -20,7 +20,6 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import javax.jms.Destination;
import javax.jms.MessageConsumer; import javax.jms.MessageConsumer;
import org.apache.activemq.JmsMultipleBrokersTestSupport; import org.apache.activemq.JmsMultipleBrokersTestSupport;
@ -29,9 +28,6 @@ import org.apache.activemq.broker.region.DestinationInterceptor;
import org.apache.activemq.broker.region.virtual.VirtualDestination; import org.apache.activemq.broker.region.virtual.VirtualDestination;
import org.apache.activemq.broker.region.virtual.VirtualDestinationInterceptor; import org.apache.activemq.broker.region.virtual.VirtualDestinationInterceptor;
import org.apache.activemq.broker.region.virtual.VirtualTopic; import org.apache.activemq.broker.region.virtual.VirtualTopic;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.network.NetworkConnector;
import org.apache.activemq.store.kahadb.KahaDBStore; import org.apache.activemq.store.kahadb.KahaDBStore;
import org.apache.activemq.util.MessageIdList; import org.apache.activemq.util.MessageIdList;
@ -100,6 +96,7 @@ public class SingleBrokerVirtualDestinationsWithWildcardTest extends JmsMultiple
Thread.sleep(500); Thread.sleep(500);
} }
@Override
public void setUp() throws Exception { public void setUp() throws Exception {
super.setAutoFail(true); super.setAutoFail(true);
super.setUp(); super.setUp();

View File

@ -46,6 +46,7 @@ public class TestBrokerConnectionDuplexExcludedDestinations extends TestCase {
Connection spokeConnection; Connection spokeConnection;
Session spokeSession; Session spokeSession;
@Override
public void setUp() throws Exception { public void setUp() throws Exception {
// Hub broker // Hub broker
String configFileName = "org/apache/activemq/usecases/receiver-duplex.xml"; String configFileName = "org/apache/activemq/usecases/receiver-duplex.xml";
@ -79,6 +80,7 @@ public class TestBrokerConnectionDuplexExcludedDestinations extends TestCase {
spokeSession = spokeConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); spokeSession = spokeConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
} }
@Override
public void tearDown() throws Exception { public void tearDown() throws Exception {
hubSession.close(); hubSession.close();
hubConnection.stop(); hubConnection.stop();
@ -92,8 +94,7 @@ public class TestBrokerConnectionDuplexExcludedDestinations extends TestCase {
receiverBroker.stop(); receiverBroker.stop();
} }
public void testDuplexSendFromHubToSpoke() public void testDuplexSendFromHubToSpoke() throws Exception {
throws Exception {
//create hub producer //create hub producer
MessageProducer hubProducer = hubSession.createProducer(null); MessageProducer hubProducer = hubSession.createProducer(null);
@ -126,7 +127,6 @@ public class TestBrokerConnectionDuplexExcludedDestinations extends TestCase {
hubProducer.send(includedQueueHub, includedMsgHub); hubProducer.send(includedQueueHub, includedMsgHub);
hubProducer.send(alwaysIncludedQueueHub, alwaysIncludedMsgHub); hubProducer.send(alwaysIncludedQueueHub, alwaysIncludedMsgHub);
Queue excludedQueueSpoke = spokeSession.createQueue("exclude.test.foo"); Queue excludedQueueSpoke = spokeSession.createQueue("exclude.test.foo");
MessageConsumer excludedConsumerSpoke = spokeSession.createConsumer(excludedQueueSpoke); MessageConsumer excludedConsumerSpoke = spokeSession.createConsumer(excludedQueueSpoke);
@ -145,9 +145,8 @@ public class TestBrokerConnectionDuplexExcludedDestinations extends TestCase {
alwaysIncludedMsgSpoke.setText(alwaysIncludedQueueSpoke.toString()); alwaysIncludedMsgSpoke.setText(alwaysIncludedQueueSpoke.toString());
spokeProducer.send(alwaysIncludedQueueSpoke, alwaysIncludedMsgSpoke); spokeProducer.send(alwaysIncludedQueueSpoke, alwaysIncludedMsgSpoke);
MessageConsumer alwaysIncludedConsumerHub = spokeSession.createConsumer(alwaysIncludedQueueHub); MessageConsumer alwaysIncludedConsumerHub = spokeSession.createConsumer(alwaysIncludedQueueHub);
assertNotNull(alwaysIncludedConsumerHub);
// Receiving from excluded Spoke queue // Receiving from excluded Spoke queue
Message msg = excludedConsumerSpoke.receive(200); Message msg = excludedConsumerSpoke.receive(200);
@ -168,7 +167,5 @@ public class TestBrokerConnectionDuplexExcludedDestinations extends TestCase {
hubProducer.close(); hubProducer.close();
excludedConsumerSpoke.close(); excludedConsumerSpoke.close();
} }
} }

View File

@ -23,22 +23,17 @@ import javax.jms.Message;
import javax.jms.TextMessage; import javax.jms.TextMessage;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQMessage; import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.command.ActiveMQTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Useful base class for unit test cases * Useful base class for unit test cases
*
*
*/ */
public class TestSupport extends TestCase { public class TestSupport extends TestCase {
private static final Logger LOG = LoggerFactory.getLogger(TestSupport.class);
protected ActiveMQConnectionFactory connectionFactory; protected ActiveMQConnectionFactory connectionFactory;
protected boolean topic = true; protected boolean topic = true;

View File

@ -33,14 +33,14 @@ public class ThreeBrokerQueueNetworkUsingTcpTest extends ThreeBrokerQueueNetwork
protected List<DemandForwardingBridge> bridges; protected List<DemandForwardingBridge> bridges;
protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception { protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception {
List remoteTransports = remoteBroker.getTransportConnectors(); List<TransportConnector> remoteTransports = remoteBroker.getTransportConnectors();
List localTransports = localBroker.getTransportConnectors(); List<TransportConnector> localTransports = localBroker.getTransportConnectors();
URI remoteURI; URI remoteURI;
URI localURI; URI localURI;
if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) { if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) {
remoteURI = ((TransportConnector)remoteTransports.get(0)).getConnectUri(); remoteURI = remoteTransports.get(0).getConnectUri();
localURI = ((TransportConnector)localTransports.get(0)).getConnectUri(); localURI = localTransports.get(0).getConnectUri();
// Ensure that we are connecting using tcp // Ensure that we are connecting using tcp
if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) { if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) {
@ -61,6 +61,7 @@ public class ThreeBrokerQueueNetworkUsingTcpTest extends ThreeBrokerQueueNetwork
maxSetupTime = 2000; maxSetupTime = 2000;
} }
@Override
public void setUp() throws Exception { public void setUp() throws Exception {
super.setUp(); super.setUp();

View File

@ -38,6 +38,7 @@ public class ThreeBrokerStompTemporaryQueueTest extends JmsMultipleBrokersTestSu
private static final Logger LOG = LoggerFactory.getLogger(ThreeBrokerStompTemporaryQueueTest.class); private static final Logger LOG = LoggerFactory.getLogger(ThreeBrokerStompTemporaryQueueTest.class);
private StompConnection stompConnection; private StompConnection stompConnection;
@Override
protected NetworkConnector bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker, boolean dynamicOnly, int networkTTL, boolean conduit, boolean failover) throws Exception { protected NetworkConnector bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker, boolean dynamicOnly, int networkTTL, boolean conduit, boolean failover) throws Exception {
List<TransportConnector> transportConnectors = remoteBroker.getTransportConnectors(); List<TransportConnector> transportConnectors = remoteBroker.getTransportConnectors();
URI remoteURI; URI remoteURI;
@ -108,7 +109,6 @@ public class ThreeBrokerStompTemporaryQueueTest extends JmsMultipleBrokersTestSu
advisoryTopicsForTempQueues = countTopicsByName("BrokerC", "ActiveMQ.Advisory.Consumer.Queue.ID"); advisoryTopicsForTempQueues = countTopicsByName("BrokerC", "ActiveMQ.Advisory.Consumer.Queue.ID");
assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues);
LOG.info("Restarting brokerA"); LOG.info("Restarting brokerA");
BrokerItem brokerItem = brokers.remove("BrokerA"); BrokerItem brokerItem = brokers.remove("BrokerA");
if (brokerItem != null) { if (brokerItem != null) {
@ -133,7 +133,6 @@ public class ThreeBrokerStompTemporaryQueueTest extends JmsMultipleBrokersTestSu
assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues);
advisoryTopicsForTempQueues = countTopicsByName("BrokerC", "ActiveMQ.Advisory.Consumer.Queue.ID"); advisoryTopicsForTempQueues = countTopicsByName("BrokerC", "ActiveMQ.Advisory.Consumer.Queue.ID");
assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues);
} }
private int countTopicsByName(String broker, String name) private int countTopicsByName(String broker, String name)
@ -147,11 +146,12 @@ public class ThreeBrokerStompTemporaryQueueTest extends JmsMultipleBrokersTestSu
return advisoryTopicsForTempQueues; return advisoryTopicsForTempQueues;
} }
private void bridgeAndConfigureBrokers(String local, String remote) throws Exception { private void bridgeAndConfigureBrokers(String local, String remote) throws Exception {
NetworkConnector bridge = bridgeBrokers(local, remote); NetworkConnector bridge = bridgeBrokers(local, remote);
assertNotNull(bridge);
} }
@Override
public void setUp() throws Exception { public void setUp() throws Exception {
super.setAutoFail(true); super.setAutoFail(true);
super.setUp(); super.setUp();
@ -159,14 +159,11 @@ public class ThreeBrokerStompTemporaryQueueTest extends JmsMultipleBrokersTestSu
createAndConfigureBroker(new URI("broker:(tcp://localhost:61616,stomp://localhost:61613)/BrokerA" + options)); createAndConfigureBroker(new URI("broker:(tcp://localhost:61616,stomp://localhost:61613)/BrokerA" + options));
createAndConfigureBroker(new URI("broker:(tcp://localhost:61617,stomp://localhost:61614)/BrokerB" + options)); createAndConfigureBroker(new URI("broker:(tcp://localhost:61617,stomp://localhost:61614)/BrokerB" + options));
createAndConfigureBroker(new URI("broker:(tcp://localhost:61618,stomp://localhost:61615)/BrokerC" + options)); createAndConfigureBroker(new URI("broker:(tcp://localhost:61618,stomp://localhost:61615)/BrokerC" + options));
} }
private BrokerService createAndConfigureBroker(URI uri) throws Exception { private BrokerService createAndConfigureBroker(URI uri) throws Exception {
BrokerService broker = createBroker(uri); BrokerService broker = createBroker(uri);
configurePersistenceAdapter(broker); configurePersistenceAdapter(broker);
return broker; return broker;
} }
@ -176,5 +173,4 @@ public class ThreeBrokerStompTemporaryQueueTest extends JmsMultipleBrokersTestSu
kaha.setDirectory(dataFileDir); kaha.setDirectory(dataFileDir);
broker.setPersistenceAdapter(kaha); broker.setPersistenceAdapter(kaha);
} }
} }

View File

@ -41,20 +41,20 @@ public class ThreeBrokerTempQueueNetworkTest extends JmsMultipleBrokersTestSuppo
bridgeBrokers("BrokerA", "BrokerB", false, 2); bridgeBrokers("BrokerA", "BrokerB", false, 2);
bridgeBrokers("BrokerB", "BrokerC", false, 2); bridgeBrokers("BrokerB", "BrokerC", false, 2);
startAllBrokers(); startAllBrokers();
BrokerItem brokerItem = (BrokerItem)brokers.get("BrokerC"); BrokerItem brokerItem = brokers.get("BrokerC");
Connection conn = brokerItem.createConnection(); Connection conn = brokerItem.createConnection();
conn.start(); conn.start();
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
TemporaryQueue tempQ = sess.createTemporaryQueue(); TemporaryQueue tempQ = sess.createTemporaryQueue();
Thread.sleep(5000); Thread.sleep(5000);
for (Iterator i = brokers.values().iterator(); i.hasNext();) { for (Iterator<BrokerItem> i = brokers.values().iterator(); i.hasNext();) {
BrokerItem bi = (BrokerItem)i.next(); BrokerItem bi = i.next();
assertEquals("No queues on broker " + bi.broker.getBrokerName(), 1, bi.broker.getAdminView().getTemporaryQueues().length); assertEquals("No queues on broker " + bi.broker.getBrokerName(), 1, bi.broker.getAdminView().getTemporaryQueues().length);
} }
tempQ.delete(); tempQ.delete();
Thread.sleep(2000); Thread.sleep(2000);
for (Iterator i = brokers.values().iterator(); i.hasNext();) { for (Iterator<BrokerItem> i = brokers.values().iterator(); i.hasNext();) {
BrokerItem bi = (BrokerItem)i.next(); BrokerItem bi = i.next();
assertEquals("Temp queue left behind on broker " + bi.broker.getBrokerName(), 0, bi.broker.getAdminView().getTemporaryQueues().length); assertEquals("Temp queue left behind on broker " + bi.broker.getBrokerName(), 0, bi.broker.getAdminView().getTemporaryQueues().length);
} }
} }
@ -65,26 +65,26 @@ public class ThreeBrokerTempQueueNetworkTest extends JmsMultipleBrokersTestSuppo
bridgeBrokers("BrokerA", "BrokerB", false, 3); bridgeBrokers("BrokerA", "BrokerB", false, 3);
bridgeBrokers("BrokerB", "BrokerC", false, 3); bridgeBrokers("BrokerB", "BrokerC", false, 3);
startAllBrokers(); startAllBrokers();
BrokerItem brokerItem = (BrokerItem)brokers.get("BrokerC"); BrokerItem brokerItem = brokers.get("BrokerC");
Connection conn = brokerItem.createConnection(); Connection conn = brokerItem.createConnection();
conn.start(); conn.start();
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
TemporaryQueue tempQ = sess.createTemporaryQueue(); TemporaryQueue tempQ = sess.createTemporaryQueue();
Thread.sleep(5000); Thread.sleep(5000);
for (Iterator i = brokers.values().iterator(); i.hasNext();) { for (Iterator<BrokerItem> i = brokers.values().iterator(); i.hasNext();) {
BrokerItem bi = (BrokerItem)i.next(); BrokerItem bi = i.next();
assertEquals("No queues on broker " + bi.broker.getBrokerName(), 1, bi.broker.getAdminView().getTemporaryQueues().length); 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")); createBroker(new URI("broker:(tcp://localhost:61619)/BrokerD?persistent=false&useJmx=true"));
bridgeBrokers("BrokerD", "BrokerA", false, 3); bridgeBrokers("BrokerD", "BrokerA", false, 3);
BrokerItem newBroker = (BrokerItem)brokers.get("BrokerD"); BrokerItem newBroker = brokers.get("BrokerD");
newBroker.broker.start(); newBroker.broker.start();
Thread.sleep(1000); Thread.sleep(1000);
assertEquals("No queues on broker D", 1, newBroker.broker.getAdminView().getTemporaryQueues().length); assertEquals("No queues on broker D", 1, newBroker.broker.getAdminView().getTemporaryQueues().length);
tempQ.delete(); tempQ.delete();
Thread.sleep(2000); Thread.sleep(2000);
for (Iterator i = brokers.values().iterator(); i.hasNext();) { for (Iterator<BrokerItem> i = brokers.values().iterator(); i.hasNext();) {
BrokerItem bi = (BrokerItem)i.next(); BrokerItem bi = i.next();
assertEquals("Temp queue left behind on broker " + bi.broker.getBrokerName(), 0, bi.broker.getAdminView().getTemporaryQueues().length); assertEquals("Temp queue left behind on broker " + bi.broker.getBrokerName(), 0, bi.broker.getAdminView().getTemporaryQueues().length);
} }
} }
@ -100,6 +100,7 @@ public class ThreeBrokerTempQueueNetworkTest extends JmsMultipleBrokersTestSuppo
fail("Test should have failed since temp queues are disabled."); fail("Test should have failed since temp queues are disabled.");
} }
@Override
public void setUp() throws Exception { public void setUp() throws Exception {
super.setAutoFail(true); super.setAutoFail(true);
super.setUp(); super.setUp();

View File

@ -28,7 +28,6 @@ import javax.jms.Topic;
import junit.framework.Test; import junit.framework.Test;
import org.apache.activemq.JmsMultipleBrokersTestSupport; import org.apache.activemq.JmsMultipleBrokersTestSupport;
import org.apache.activemq.JmsMultipleBrokersTestSupport.BrokerItem;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.region.policy.PolicyEntry; import org.apache.activemq.broker.region.policy.PolicyEntry;
import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.broker.region.policy.PolicyMap;
@ -387,6 +386,7 @@ public class ThreeBrokerTopicNetworkTest extends JmsMultipleBrokersTestSupport {
assertEquals(MESSAGE_COUNT * 3, msgsC.getMessageCount()); assertEquals(MESSAGE_COUNT * 3, msgsC.getMessageCount());
} }
@Override
public void setUp() throws Exception { public void setUp() throws Exception {
super.setAutoFail(true); super.setAutoFail(true);
super.setUp(); super.setUp();

View File

@ -33,14 +33,14 @@ public class ThreeBrokerTopicNetworkUsingTcpTest extends ThreeBrokerTopicNetwork
protected List<DemandForwardingBridge> bridges; protected List<DemandForwardingBridge> bridges;
protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception { protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception {
List remoteTransports = remoteBroker.getTransportConnectors(); List<TransportConnector> remoteTransports = remoteBroker.getTransportConnectors();
List localTransports = localBroker.getTransportConnectors(); List<TransportConnector> localTransports = localBroker.getTransportConnectors();
URI remoteURI; URI remoteURI;
URI localURI; URI localURI;
if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) { if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) {
remoteURI = ((TransportConnector)remoteTransports.get(0)).getConnectUri(); remoteURI = remoteTransports.get(0).getConnectUri();
localURI = ((TransportConnector)localTransports.get(0)).getConnectUri(); localURI = localTransports.get(0).getConnectUri();
// Ensure that we are connecting using tcp // Ensure that we are connecting using tcp
if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) { if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) {
@ -61,6 +61,7 @@ public class ThreeBrokerTopicNetworkUsingTcpTest extends ThreeBrokerTopicNetwork
maxSetupTime = 2000; maxSetupTime = 2000;
} }
@Override
public void setUp() throws Exception { public void setUp() throws Exception {
super.setUp(); super.setUp();

View File

@ -34,7 +34,9 @@ import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler; import javax.management.MBeanServerInvocationHandler;
import javax.management.MalformedObjectNameException; import javax.management.MalformedObjectNameException;
import javax.management.ObjectName; import javax.management.ObjectName;
import junit.framework.Test; import junit.framework.Test;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQPrefetchPolicy; import org.apache.activemq.ActiveMQPrefetchPolicy;
import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerFactory;
@ -50,8 +52,8 @@ public class TopicDurableConnectStatsTest extends org.apache.activemq.TestSuppor
private static final Logger LOG = LoggerFactory.getLogger(TopicDurableConnectStatsTest.class); private static final Logger LOG = LoggerFactory.getLogger(TopicDurableConnectStatsTest.class);
private BrokerService broker; private BrokerService broker;
private ActiveMQTopic topic; private ActiveMQTopic topic;
private Vector<Throwable> exceptions = new Vector<Throwable>(); private final Vector<Throwable> exceptions = new Vector<Throwable>();
private int messageSize = 4000; private final int messageSize = 4000;
protected MBeanServerConnection mbeanServer; protected MBeanServerConnection mbeanServer;
protected String domain = "org.apache.activemq"; protected String domain = "org.apache.activemq";
private ActiveMQConnectionFactory connectionFactory = null; private ActiveMQConnectionFactory connectionFactory = null;
@ -59,6 +61,7 @@ public class TopicDurableConnectStatsTest extends org.apache.activemq.TestSuppor
private static Session session2 = null; private static Session session2 = null;
@Override
protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { protected ActiveMQConnectionFactory createConnectionFactory() throws Exception {
connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true));
@ -87,6 +90,7 @@ public class TopicDurableConnectStatsTest extends org.apache.activemq.TestSuppor
return suite(TopicDurableConnectStatsTest.class); return suite(TopicDurableConnectStatsTest.class);
} }
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
exceptions.clear(); exceptions.clear();
topic = (ActiveMQTopic) createDestination(); topic = (ActiveMQTopic) createDestination();
@ -96,6 +100,7 @@ public class TopicDurableConnectStatsTest extends org.apache.activemq.TestSuppor
super.setUp(); super.setUp();
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
super.tearDown(); super.tearDown();
destroyBroker(); destroyBroker();
@ -143,6 +148,7 @@ public class TopicDurableConnectStatsTest extends org.apache.activemq.TestSuppor
Connection consumerCon = createConnection("cliId1"); Connection consumerCon = createConnection("cliId1");
Session consumerSession = consumerCon.createSession(true, Session.AUTO_ACKNOWLEDGE); Session consumerSession = consumerCon.createSession(true, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer1 = consumerSession.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); MessageConsumer consumer1 = consumerSession.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true);
assertNotNull(consumer1);
DurableSubscriptionViewMBean subscriber1 = null; DurableSubscriptionViewMBean subscriber1 = null;
@ -201,6 +207,7 @@ public class TopicDurableConnectStatsTest extends org.apache.activemq.TestSuppor
consumer2.setMessageListener(listener); consumer2.setMessageListener(listener);
assertTrue("received all sent", Wait.waitFor(new Wait.Condition() { assertTrue("received all sent", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception { public boolean isSatisified() throws Exception {
return numMessages == listener.count; return numMessages == listener.count;
} }
@ -238,6 +245,7 @@ public class TopicDurableConnectStatsTest extends org.apache.activemq.TestSuppor
Listener() { Listener() {
} }
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
count++; count++;
try { try {

View File

@ -17,7 +17,6 @@
package org.apache.activemq.usecases; package org.apache.activemq.usecases;
import java.util.Date; import java.util.Date;
import java.util.Map;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -32,6 +31,7 @@ import javax.jms.Session;
import javax.jms.TextMessage; import javax.jms.TextMessage;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQQueue;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -54,7 +54,7 @@ public final class TransactionTest extends TestCase {
private MessageProducer producer; private MessageProducer producer;
private MessageConsumer consumer; private MessageConsumer consumer;
private Connection connection; private Connection connection;
private CountDownLatch latch = new CountDownLatch(1); private final CountDownLatch latch = new CountDownLatch(1);
public void testTransaction() throws Exception { public void testTransaction() throws Exception {
@ -70,6 +70,7 @@ public final class TransactionTest extends TestCase {
consumer = consumerSession.createConsumer(queue); consumer = consumerSession.createConsumer(queue);
consumer.setMessageListener(new MessageListener() { consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message m) { public void onMessage(Message m) {
try { try {
TextMessage tm = (TextMessage)m; TextMessage tm = (TextMessage)m;
@ -111,6 +112,7 @@ public final class TransactionTest extends TestCase {
LOG.info("test completed, destination=" + receivedText); LOG.info("test completed, destination=" + receivedText);
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
if (connection != null) { if (connection != null) {
connection.close(); connection.close();

View File

@ -366,6 +366,7 @@ public class TwoBrokerQueueClientsReconnectTest extends JmsMultipleBrokersTestSu
assertEquals("Client for " + broker2 + " should have received 50% of the messages.", (int)(MESSAGE_COUNT * 0.50), msgsClient2); assertEquals("Client for " + broker2 + " should have received 50% of the messages.", (int)(MESSAGE_COUNT * 0.50), msgsClient2);
} }
@SuppressWarnings("unchecked")
public void testDuplicateSend() throws Exception { public void testDuplicateSend() throws Exception {
broker1 = "BrokerA"; broker1 = "BrokerA";
broker2 = "BrokerB"; broker2 = "BrokerB";
@ -391,6 +392,7 @@ public class TwoBrokerQueueClientsReconnectTest extends JmsMultipleBrokersTestSu
if (first.compareAndSet(false, true)) { if (first.compareAndSet(false, true)) {
producerExchange.getConnectionContext().setDontSendReponse(true); producerExchange.getConnectionContext().setDontSendReponse(true);
Executors.newSingleThreadExecutor().execute(new Runnable() { Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() { public void run() {
try { try {
LOG.info("Waiting for recepit"); LOG.info("Waiting for recepit");
@ -441,6 +443,7 @@ public class TwoBrokerQueueClientsReconnectTest extends JmsMultipleBrokersTestSu
})); }));
} }
@SuppressWarnings("unchecked")
public void testDuplicateSendWithNoAuditEnqueueCountStat() throws Exception { public void testDuplicateSendWithNoAuditEnqueueCountStat() throws Exception {
broker1 = "BrokerA"; broker1 = "BrokerA";
broker2 = "BrokerB"; broker2 = "BrokerB";
@ -463,6 +466,7 @@ public class TwoBrokerQueueClientsReconnectTest extends JmsMultipleBrokersTestSu
if (first.compareAndSet(false, true)) { if (first.compareAndSet(false, true)) {
producerExchange.getConnectionContext().setDontSendReponse(true); producerExchange.getConnectionContext().setDontSendReponse(true);
Executors.newSingleThreadExecutor().execute(new Runnable() { Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() { public void run() {
try { try {
LOG.info("Waiting for recepit"); LOG.info("Waiting for recepit");
@ -547,6 +551,7 @@ public class TwoBrokerQueueClientsReconnectTest extends JmsMultipleBrokersTestSu
return msgsReceived; return msgsReceived;
} }
@Override
protected MessageConsumer createConsumer(String brokerName, Destination dest) throws Exception { protected MessageConsumer createConsumer(String brokerName, Destination dest) throws Exception {
Connection conn = createConnection(brokerName); Connection conn = createConnection(brokerName);
conn.start(); conn.start();
@ -554,6 +559,7 @@ public class TwoBrokerQueueClientsReconnectTest extends JmsMultipleBrokersTestSu
return sess.createConsumer(dest); return sess.createConsumer(dest);
} }
@Override
protected void configureBroker(BrokerService broker) { protected void configureBroker(BrokerService broker) {
PolicyMap policyMap = new PolicyMap(); PolicyMap policyMap = new PolicyMap();
PolicyEntry defaultEntry = new PolicyEntry(); PolicyEntry defaultEntry = new PolicyEntry();
@ -562,6 +568,7 @@ public class TwoBrokerQueueClientsReconnectTest extends JmsMultipleBrokersTestSu
broker.setDestinationPolicy(policyMap); broker.setDestinationPolicy(policyMap);
} }
@Override
protected NetworkConnector bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker, boolean dynamicOnly, int networkTTL, boolean conduit, boolean failover) throws Exception { protected NetworkConnector bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker, boolean dynamicOnly, int networkTTL, boolean conduit, boolean failover) throws Exception {
NetworkConnector nc = super.bridgeBrokers(localBroker,remoteBroker, dynamicOnly, networkTTL, conduit, failover); NetworkConnector nc = super.bridgeBrokers(localBroker,remoteBroker, dynamicOnly, networkTTL, conduit, failover);
nc.setPrefetchSize(NETWORK_PREFETCH); nc.setPrefetchSize(NETWORK_PREFETCH);
@ -569,6 +576,7 @@ public class TwoBrokerQueueClientsReconnectTest extends JmsMultipleBrokersTestSu
return nc; return nc;
} }
@Override
public void setUp() throws Exception { public void setUp() throws Exception {
super.setAutoFail(true); super.setAutoFail(true);
super.setUp(); super.setUp();

View File

@ -39,8 +39,9 @@ public class TwoBrokerTopicSendReceiveTest extends JmsTopicSendReceiveWithTwoCon
protected ActiveMQConnectionFactory sendFactory; protected ActiveMQConnectionFactory sendFactory;
protected ActiveMQConnectionFactory receiveFactory; protected ActiveMQConnectionFactory receiveFactory;
protected HashMap brokers = new HashMap(); protected HashMap<String, BrokerService> brokers = new HashMap<String, BrokerService>();
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
sendFactory = createSenderConnectionFactory(); sendFactory = createSenderConnectionFactory();
receiveFactory = createReceiverConnectionFactory(); receiveFactory = createReceiverConnectionFactory();
@ -63,19 +64,22 @@ public class TwoBrokerTopicSendReceiveTest extends JmsTopicSendReceiveWithTwoCon
return createConnectionFactory("org/apache/activemq/usecases/sender.xml", "sender", "vm://sender"); return createConnectionFactory("org/apache/activemq/usecases/sender.xml", "sender", "vm://sender");
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
super.tearDown(); super.tearDown();
for (Iterator iter = brokers.values().iterator(); iter.hasNext();) { for (Iterator<BrokerService> iter = brokers.values().iterator(); iter.hasNext();) {
BrokerService broker = (BrokerService)iter.next(); BrokerService broker = iter.next();
ServiceSupport.dispose(broker); ServiceSupport.dispose(broker);
iter.remove(); iter.remove();
} }
} }
@Override
protected Connection createReceiveConnection() throws JMSException { protected Connection createReceiveConnection() throws JMSException {
return receiveFactory.createConnection(); return receiveFactory.createConnection();
} }
@Override
protected Connection createSendConnection() throws JMSException { protected Connection createSendConnection() throws JMSException {
return sendFactory.createConnection(); return sendFactory.createConnection();
} }

View File

@ -24,8 +24,7 @@ import javax.jms.JMSException;
import javax.jms.Message; import javax.jms.Message;
import javax.jms.MessageListener; import javax.jms.MessageListener;
import junit.framework.Assert; import org.junit.Assert;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -44,8 +43,8 @@ public class MessageIdList extends Assert implements MessageListener {
private static final Logger LOG = LoggerFactory.getLogger(MessageIdList.class); private static final Logger LOG = LoggerFactory.getLogger(MessageIdList.class);
private List<String> messageIds = new ArrayList<String>(); private final List<String> messageIds = new ArrayList<String>();
private Object semaphore; private final Object semaphore;
private boolean verbose; private boolean verbose;
private MessageListener parent; private MessageListener parent;
private long maximumDuration = 15000L; private long maximumDuration = 15000L;
@ -61,6 +60,7 @@ public class MessageIdList extends Assert implements MessageListener {
this.semaphore = semaphore; this.semaphore = semaphore;
} }
@Override
public boolean equals(Object that) { public boolean equals(Object that) {
if (that instanceof MessageIdList) { if (that instanceof MessageIdList) {
MessageIdList thatList = (MessageIdList)that; MessageIdList thatList = (MessageIdList)that;
@ -69,12 +69,14 @@ public class MessageIdList extends Assert implements MessageListener {
return false; return false;
} }
@Override
public int hashCode() { public int hashCode() {
synchronized (semaphore) { synchronized (semaphore) {
return messageIds.hashCode() + 1; return messageIds.hashCode() + 1;
} }
} }
@Override
public String toString() { public String toString() {
synchronized (semaphore) { synchronized (semaphore) {
return messageIds.toString(); return messageIds.toString();
@ -98,6 +100,7 @@ public class MessageIdList extends Assert implements MessageListener {
} }
} }
@Override
public void onMessage(Message message) { public void onMessage(Message message) {
String id = null; String id = null;
try { try {

View File

@ -32,6 +32,7 @@ import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector; import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.network.NetworkConnector; import org.apache.activemq.network.NetworkConnector;
@ -48,20 +49,19 @@ public class ConnectorXBeanConfigTest extends TestCase {
public void testConnectorConfiguredCorrectly() throws Exception { public void testConnectorConfiguredCorrectly() throws Exception {
TransportConnector connector = (TransportConnector)brokerService.getTransportConnectors().get(0); TransportConnector connector = brokerService.getTransportConnectors().get(0);
assertEquals(new URI("tcp://localhost:61636"), connector.getUri()); assertEquals(new URI("tcp://localhost:61636"), connector.getUri());
assertTrue(connector.getTaskRunnerFactory() == brokerService.getTaskRunnerFactory()); assertTrue(connector.getTaskRunnerFactory() == brokerService.getTaskRunnerFactory());
NetworkConnector netConnector = (NetworkConnector)brokerService.getNetworkConnectors().get(0); NetworkConnector netConnector = brokerService.getNetworkConnectors().get(0);
List excludedDestinations = netConnector.getExcludedDestinations(); List<ActiveMQDestination> excludedDestinations = netConnector.getExcludedDestinations();
assertEquals(new ActiveMQQueue("exclude.test.foo"), excludedDestinations.get(0)); assertEquals(new ActiveMQQueue("exclude.test.foo"), excludedDestinations.get(0));
assertEquals(new ActiveMQTopic("exclude.test.bar"), excludedDestinations.get(1)); assertEquals(new ActiveMQTopic("exclude.test.bar"), excludedDestinations.get(1));
List dynamicallyIncludedDestinations = netConnector.getDynamicallyIncludedDestinations(); List<ActiveMQDestination> dynamicallyIncludedDestinations = netConnector.getDynamicallyIncludedDestinations();
assertEquals(new ActiveMQQueue("include.test.foo"), dynamicallyIncludedDestinations.get(0)); assertEquals(new ActiveMQQueue("include.test.foo"), dynamicallyIncludedDestinations.get(0));
assertEquals(new ActiveMQTopic("include.test.bar"), dynamicallyIncludedDestinations.get(1)); assertEquals(new ActiveMQTopic("include.test.bar"), dynamicallyIncludedDestinations.get(1));
} }
public void testBrokerRestartIsAllowed() throws Exception { public void testBrokerRestartIsAllowed() throws Exception {
@ -93,12 +93,13 @@ public class ConnectorXBeanConfigTest extends TestCase {
assertEquals("test", msg.getText()); assertEquals("test", msg.getText());
} }
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
brokerService = createBroker(); brokerService = createBroker();
brokerService.start(); brokerService.start();
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
if (brokerService != null) { if (brokerService != null) {
brokerService.stop(); brokerService.stop();
@ -109,5 +110,4 @@ public class ConnectorXBeanConfigTest extends TestCase {
String uri = "org/apache/activemq/xbean/connector-test.xml"; String uri = "org/apache/activemq/xbean/connector-test.xml";
return BrokerFactory.createBroker(new URI("xbean:" + uri)); return BrokerFactory.createBroker(new URI("xbean:" + uri));
} }
} }

View File

@ -27,7 +27,9 @@ import javax.management.ObjectName;
import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL; import javax.management.remote.JMXServiceURL;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.jmx.BrokerViewMBean; import org.apache.activemq.broker.jmx.BrokerViewMBean;
@ -57,7 +59,7 @@ public class ManagementContextXBeanConfigTest extends TestCase {
public void testSuccessAuthentication() throws Exception { public void testSuccessAuthentication() throws Exception {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:2011/jmxrmi"); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:2011/jmxrmi");
Map env = new HashMap(); Map<String, Object> env = new HashMap<String, Object>();
env.put(JMXConnector.CREDENTIALS, new String[]{"admin", "activemq"}); env.put(JMXConnector.CREDENTIALS, new String[]{"admin", "activemq"});
JMXConnector connector = JMXConnectorFactory.connect(url, env); JMXConnector connector = JMXConnectorFactory.connect(url, env);
assertAuthentication(connector); assertAuthentication(connector);
@ -78,16 +80,18 @@ public class ManagementContextXBeanConfigTest extends TestCase {
connector.connect(); connector.connect();
MBeanServerConnection connection = connector.getMBeanServerConnection(); MBeanServerConnection connection = connector.getMBeanServerConnection();
ObjectName name = new ObjectName("test.domain:type=Broker,brokerName=localhost"); ObjectName name = new ObjectName("test.domain:type=Broker,brokerName=localhost");
BrokerViewMBean mbean = (BrokerViewMBean) MBeanServerInvocationHandler BrokerViewMBean mbean = MBeanServerInvocationHandler
.newProxyInstance(connection, name, BrokerViewMBean.class, true); .newProxyInstance(connection, name, BrokerViewMBean.class, true);
LOG.info("Broker " + mbean.getBrokerId() + " - " + mbean.getBrokerName()); LOG.info("Broker " + mbean.getBrokerId() + " - " + mbean.getBrokerName());
} }
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
brokerService = createBroker(); brokerService = createBroker();
brokerService.start(); brokerService.start();
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
if (brokerService != null) { if (brokerService != null) {
brokerService.stop(); brokerService.stop();

View File

@ -19,13 +19,10 @@ package org.apache.activemq.xbean;
import javax.jms.Connection; import javax.jms.Connection;
import org.apache.activemq.EmbeddedBrokerTestSupport; import org.apache.activemq.EmbeddedBrokerTestSupport;
import org.apache.activemq.test.retroactive.RetroactiveConsumerWithMessageQueryTest;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
*
* @author Neil Clayton
* *
*/ */
public class MultipleTestsWithEmbeddedBrokerTest extends EmbeddedBrokerTestSupport { public class MultipleTestsWithEmbeddedBrokerTest extends EmbeddedBrokerTestSupport {
@ -39,6 +36,7 @@ public class MultipleTestsWithEmbeddedBrokerTest extends EmbeddedBrokerTestSuppo
public void test2() throws Exception { public void test2() throws Exception {
} }
@Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
LOG.info("### starting up the test case: " + getName()); LOG.info("### starting up the test case: " + getName());
@ -48,6 +46,7 @@ public class MultipleTestsWithEmbeddedBrokerTest extends EmbeddedBrokerTestSuppo
LOG.info("### started up the test case: " + getName()); LOG.info("### started up the test case: " + getName());
} }
@Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
connection.close(); connection.close();