From c1ebe66bfab328c5192a35c21ea290b5c45f40f5 Mon Sep 17 00:00:00 2001 From: Aidan Skinner Date: Wed, 9 Sep 2009 13:05:43 +0000 Subject: Merge from trunk git-svn-id: https://svn.apache.org/repos/asf/qpid/branches/java-network-refactor@812936 13f79535-47bb-0310-9956-ffa450edef68 --- .../management/jmx/ManagementActorLoggingTest.java | 28 ++++- .../server/logging/SubscriptionLoggingTest.java | 65 ++++++----- .../client/DynamicQueueExchangeCreateTest.java | 88 +++++++++++++++ .../close/JavaServerCloseRaceConditionTest.java | 119 +++++++++++++++++++++ .../test/unit/topic/DurableSubscriptionTest.java | 59 +++++----- .../test/unit/transacted/CommitRollbackTest.java | 2 +- .../apache/qpid/test/utils/FailoverBaseCase.java | 4 +- .../main/java/org/apache/qpid/util/LogMonitor.java | 20 +++- .../java/org/apache/qpid/util/LogMonitorTest.java | 73 +++++-------- 9 files changed, 353 insertions(+), 105 deletions(-) create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/DynamicQueueExchangeCreateTest.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/close/JavaServerCloseRaceConditionTest.java (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java index 7a2266902b..b4ba6e8156 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java @@ -29,6 +29,8 @@ import org.apache.qpid.server.logging.AbstractTestLogging; import org.apache.qpid.server.logging.subjects.AbstractTestLogSubject; import javax.jms.Connection; +import javax.jms.ExceptionListener; +import javax.jms.JMSException; import javax.management.JMException; import javax.management.MBeanException; import javax.management.MBeanServerConnection; @@ -38,6 +40,8 @@ import javax.management.remote.JMXConnector; import java.io.IOException; import java.util.List; import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; /** * Test class to test if any change in the broker JMX code is affesting the management console @@ -161,6 +165,23 @@ public class ManagementActorLoggingTest extends AbstractTestLogging //Create a connection to the broker Connection connection = getConnection(); + // Monitor the connection for an exception being thrown + // this should be a DisconnectionException but it is not this tests + // job to valiate that. Only use the exception as a synchronisation + // to check the log file for the Close message + final CountDownLatch exceptionReceived = new CountDownLatch(1); + connection.setExceptionListener(new ExceptionListener() + { + public void onException(JMSException e) + { + //Failover being attempted. + exceptionReceived.countDown(); + } + }); + + //Remove the connection close from any 0-10 connections + _monitor.reset(); + // Get all active AMQP connections AllObjects allObject = new AllObjects(_mbsc); allObject.querystring = "org.apache.qpid:type=VirtualHost.Connection,*"; @@ -175,16 +196,17 @@ public class ManagementActorLoggingTest extends AbstractTestLogging newProxyInstance(_mbsc, connectionName, ManagedConnection.class, false); - //Remove the connection close from any 0-10 connections - _monitor.reset(); //Close the connection mangedConnection.closeConnection(); + //Wait for the connection to close + assertTrue("Timed out waiting for conneciton to report close", + exceptionReceived.await(2, TimeUnit.SECONDS)); + //Validate results List results = _monitor.findMatches("CON-1002"); - assertEquals("Unexpected Connection Close count", 1, results.size()); } } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/SubscriptionLoggingTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/SubscriptionLoggingTest.java index d7209c5660..5dd56fb0f9 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/SubscriptionLoggingTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/SubscriptionLoggingTest.java @@ -29,6 +29,7 @@ import javax.jms.MessageConsumer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.Topic; +import javax.jms.Message; import java.io.IOException; import java.util.List; @@ -327,22 +328,45 @@ public class SubscriptionLoggingTest extends AbstractTestLogging int PREFETCH = 15; //Create new session with small prefetch - _session = ((AMQConnection) _connection).createSession(true, Session.AUTO_ACKNOWLEDGE, PREFETCH); + _session = ((AMQConnection) _connection).createSession(true, Session.SESSION_TRANSACTED, PREFETCH); MessageConsumer consumer = _session.createConsumer(_queue); _connection.start(); + //Start the dispatcher & Unflow the channel. + consumer.receiveNoWait(); + //Fill the prefetch and two extra so that our receive bellow allows the - // subscription to become active then return to a suspended state. - sendMessage(_session, _queue, 17); + // subscription to become active + // Previously we set this to 17 so that it would return to a suspended + // state. However, testing has shown that the state change can occur + // sufficiently quickly that logging does not occur consistently enough + // for testing. + int SEND_COUNT = 16; + sendMessage(_session, _queue, SEND_COUNT); _session.commit(); // Retreive the first message, and start the flow of messages - assertNotNull("First message not retreived", consumer.receive(1000)); + Message msg = consumer.receive(1000); + assertNotNull("First message not retreived", msg); _session.commit(); - - _connection.close(); + // Drain the queue to ensure there is time for the ACTIVE log message + // Check that we can received all the messages + int receivedCount = 0; + while (msg != null) + { + receivedCount++; + msg = consumer.receive(1000); + _session.commit(); + } + + //Validate we received all the messages + assertEquals("Not all sent messages received.", SEND_COUNT, receivedCount); + + // Fill the queue again to suspend the consumer + sendMessage(_session, _queue, SEND_COUNT); + _session.commit(); //Validate List results = _monitor.findMatches("SUB-1003"); @@ -350,15 +374,13 @@ public class SubscriptionLoggingTest extends AbstractTestLogging try { // Validation expects three messages. - // The first will be logged by the QueueActor as part of the processQueue thread -// INFO - MESSAGE [vh(/test)/qu(example.queue)] [sub:6(qu(example.queue))] SUB-1003 : State : SUSPENDED - // The second will be by the connnection as it acknowledges and activates the subscription -// INFO - MESSAGE [con:6(guest@anonymous(26562441)/test)/ch:3] [sub:6(qu(example.queue))] SUB-1003 : State : ACTIVE - // The final one can be the subscription suspending as part of the SubFlushRunner or the processQueue thread - // As a result validating the actor is more complicated and doesn't add anything. The goal of this test is - // to ensure the State is correct not that a particular Actor performs the logging. -// INFO - MESSAGE [sub:6(vh(test)/qu(example.queue))] [sub:6(qu(example.queue))] SUB-1003 : State : SUSPENDED -// INFO - MESSAGE [vh(/test)/qu(example.queue)] [sub:6(qu(example.queue))] SUB-1003 : State : SUSPENDED + // The Actor can be any one of the following depending on the exactly what is going on on the broker. + // Ideally we would test that we can get all of them but setting up + // the timing to do this in a consistent way is not benefitial. + // Ensuring the State is as expected is sufficient. +// INFO - MESSAGE [vh(/test)/qu(example.queue)] [sub:6(qu(example.queue))] SUB-1003 : State : +// INFO - MESSAGE [con:6(guest@anonymous(26562441)/test)/ch:3] [sub:6(qu(example.queue))] SUB-1003 : State : +// INFO - MESSAGE [sub:6(vh(test)/qu(example.queue))] [sub:6(qu(example.queue))] SUB-1003 : State : assertEquals("Result set not expected size:", 3, results.size()); @@ -367,19 +389,10 @@ public class SubscriptionLoggingTest extends AbstractTestLogging String log = getLog(results.get(0)); validateSubscriptionState(log, expectedState); - // Validate that the logActor is the the queue - String actor = fromActor(log); - assertTrue("Actor string does not contain expected queue(" - + _queue.getQueueName() + ") name." + actor, - actor.contains("qu(" + _queue.getQueueName() + ")")); - // After being suspended the subscription should become active. expectedState = "ACTIVE"; log = getLog(results.get(1)); validateSubscriptionState(log, expectedState); - // Validate we have a connection Actor - actor = fromActor(log); - assertTrue("The actor is not a connection actor:" + actor, actor.startsWith("con:")); // Validate that it was re-suspended expectedState = "SUSPENDED"; @@ -396,6 +409,10 @@ public class SubscriptionLoggingTest extends AbstractTestLogging } throw afe; } + _connection.close(); + + //Ensure the queue is drained before the test ends + drainQueue(_queue); } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/DynamicQueueExchangeCreateTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/DynamicQueueExchangeCreateTest.java new file mode 100644 index 0000000000..c9810e7304 --- /dev/null +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/DynamicQueueExchangeCreateTest.java @@ -0,0 +1,88 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.test.unit.client; + +import org.apache.qpid.test.utils.QpidTestCase; + +import javax.jms.Connection; +import javax.jms.JMSException; +import javax.jms.Queue; +import javax.jms.Session; + +/** + * QPID-155 + * + * Test to validate that setting the respective qpid.declare_queues, + * qpid.declare_exchanges system properties functions as expected. + * + */ +public class DynamicQueueExchangeCreateTest extends QpidTestCase +{ + + public void testQueueDeclare() throws Exception + { + setSystemProperty("qpid.declare_queues", "false"); + + Connection connection = getConnection(); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + Queue queue = session.createQueue(getTestQueueName()); + + try + { + session.createConsumer(queue); + fail("JMSException should be thrown as the queue does not exist"); + } + catch (JMSException e) + { + assertTrue("Exception should be that the queue does not exist :" + + e.getMessage(), + e.getMessage().contains("does not exist")); + + } + } + + public void testExchangeDeclare() throws Exception + { + setSystemProperty("qpid.declare_exchanges", "false"); + + Connection connection = getConnection(); + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + String EXCHANGE_TYPE = "test.direct"; + Queue queue = session.createQueue("direct://" + EXCHANGE_TYPE + "/queue/queue"); + + try + { + session.createConsumer(queue); + fail("JMSException should be thrown as the exchange does not exist"); + } + catch (JMSException e) + { + assertTrue("Exception should be that the exchange does not exist :" + + e.getMessage(), + e.getMessage().contains("Exchange " + EXCHANGE_TYPE + " does not exist")); + } + } + +} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/close/JavaServerCloseRaceConditionTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/close/JavaServerCloseRaceConditionTest.java new file mode 100644 index 0000000000..3fb6cd3526 --- /dev/null +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/close/JavaServerCloseRaceConditionTest.java @@ -0,0 +1,119 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.test.unit.close; + +import org.apache.qpid.client.AMQConnection; +import org.apache.qpid.client.AMQDestination; +import org.apache.qpid.client.AMQSession; +import org.apache.qpid.framing.AMQFrame; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.ExchangeDeclareBody; +import org.apache.qpid.framing.ExchangeDeclareOkBody; +import org.apache.qpid.test.utils.QpidTestCase; + +import javax.jms.Session; + +/** QPID-1809 + * + * Race condition on error handling and close logic. + * + * See most often with SimpleACLTest as this test is the expects the server to + * shut the connection/channels. This sort of testing is not performed by many, + * if any, of the other system tests. + * + * The problem is that we have two threads + * + * MainThread Exception(Mina)Thread + * | | + * Performs | + * ACtion | + * | Receives Server + * | Close + * Blocks for | + * Response | + * | Starts To Notify + * | client + * | | + * | <----- Notify Main Thread + * Notification | + * wakes client | + * | | + * Client then | + * processes Error. | + * | | + * Potentially Attempting Close Channel/Connection + * Connection Close + * + * The two threads both attempt to close the connection but the main thread does + * so assuming that the connection is open and valid. + * + * The Exception thread must modify the connection so that no furter syncWait + * commands are performed. + * + * This test sends an ExchangeDeclare that is Asynchronous and will fail and + * so cause a ChannelClose error but we perform a syncWait so that we can be + * sure to test that the BlockingWaiter is correctly awoken. + * + */ +public class JavaServerCloseRaceConditionTest extends QpidTestCase +{ + private static final String EXCHANGE_NAME = "NewExchangeNametoFailLookup"; + + public void test() throws Exception + { + + AMQConnection connection = (AMQConnection) getConnection(); + + AMQSession session = (AMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + // Set no wait true so that we block the connection + // Also set a different exchange class string so the attempt to declare + // the exchange causes an exchange. + ExchangeDeclareBody body = session.getMethodRegistry().createExchangeDeclareBody(session.getTicket(), new AMQShortString(EXCHANGE_NAME), null, + true, false, false, false, true, null); + + AMQFrame exchangeDeclare = body.generateFrame(session.getChannelId()); + + try + { + // block our thread so that can times out + connection.getProtocolHandler().syncWrite(exchangeDeclare, ExchangeDeclareOkBody.class); + } + catch (Exception e) + { + assertTrue("Exception should say the exchange is not known.", e.getMessage().contains("Unknown exchange: " + EXCHANGE_NAME)); + } + + try + { + // Depending on if the notification thread has closed the connection + // or not we may get an exception here when we attempt to close the + // connection. If we do get one then it should be the same as above + // an AMQAuthenticationException. + connection.close(); + } + catch (Exception e) + { + assertTrue("Exception should say the exchange is not known.", e.getMessage().contains("Unknown exchange: " + EXCHANGE_NAME)); + } + + } +} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/topic/DurableSubscriptionTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/topic/DurableSubscriptionTest.java index c5cdb83bbf..2a44413ac8 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/topic/DurableSubscriptionTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/topic/DurableSubscriptionTest.java @@ -51,7 +51,13 @@ import javax.jms.TopicSubscriber; public class DurableSubscriptionTest extends QpidTestCase { private static final Logger _logger = LoggerFactory.getLogger(DurableSubscriptionTest.class); - + + /** Timeout for receive() if we are expecting a message */ + private static final long POSITIVE_RECEIVE_TIMEOUT = 2000; + + /** Timeout for receive() if we are not expecting a message */ + private static final long NEGATIVE_RECEIVE_TIMEOUT = 1000; + public void testUnsubscribe() throws Exception { AMQConnection con = (AMQConnection) getConnection("guest", "guest"); @@ -76,16 +82,18 @@ public class DurableSubscriptionTest extends QpidTestCase Message msg; _logger.info("Receive message on consumer 1:expecting A"); - msg = consumer1.receive(); + msg = consumer1.receive(POSITIVE_RECEIVE_TIMEOUT); + assertNotNull("Message should have been received",msg); assertEquals("A", ((TextMessage) msg).getText()); _logger.info("Receive message on consumer 1 :expecting null"); - msg = consumer1.receive(1000); + msg = consumer1.receive(NEGATIVE_RECEIVE_TIMEOUT); assertEquals(null, msg); - _logger.info("Receive message on consumer 1:expecting A"); - msg = consumer2.receive(); + _logger.info("Receive message on consumer 2:expecting A"); + msg = consumer2.receive(POSITIVE_RECEIVE_TIMEOUT); + assertNotNull("Message should have been received",msg); assertEquals("A", ((TextMessage) msg).getText()); - msg = consumer2.receive(1000); + msg = consumer2.receive(NEGATIVE_RECEIVE_TIMEOUT); _logger.info("Receive message on consumer 1 :expecting null"); assertEquals(null, msg); @@ -96,14 +104,15 @@ public class DurableSubscriptionTest extends QpidTestCase producer.send(session1.createTextMessage("B")); _logger.info("Receive message on consumer 1 :expecting B"); - msg = consumer1.receive(); + msg = consumer1.receive(POSITIVE_RECEIVE_TIMEOUT); + assertNotNull("Message should have been received",msg); assertEquals("B", ((TextMessage) msg).getText()); _logger.info("Receive message on consumer 1 :expecting null"); - msg = consumer1.receive(1000); + msg = consumer1.receive(NEGATIVE_RECEIVE_TIMEOUT); assertEquals(null, msg); _logger.info("Receive message on consumer 2 :expecting null"); - msg = consumer2.receive(1000); + msg = consumer2.receive(NEGATIVE_RECEIVE_TIMEOUT); assertEquals(null, msg); _logger.info("Close connection"); @@ -143,14 +152,16 @@ public class DurableSubscriptionTest extends QpidTestCase producer.send(session1.createTextMessage("A")); Message msg; - msg = consumer1.receive(); + msg = consumer1.receive(POSITIVE_RECEIVE_TIMEOUT); + assertNotNull("Message should have been received",msg); assertEquals("A", ((TextMessage) msg).getText()); - msg = consumer1.receive(1000); + msg = consumer1.receive(NEGATIVE_RECEIVE_TIMEOUT); assertEquals(null, msg); - msg = consumer2.receive(); + msg = consumer2.receive(POSITIVE_RECEIVE_TIMEOUT); + assertNotNull("Message should have been received",msg); assertEquals("A", ((TextMessage) msg).getText()); - msg = consumer2.receive(1000); + msg = consumer2.receive(NEGATIVE_RECEIVE_TIMEOUT); assertEquals(null, msg); consumer2.close(); @@ -220,8 +231,8 @@ public class DurableSubscriptionTest extends QpidTestCase msg = consumer1.receive(500); assertNull("There should be no more messages for consumption on consumer1.", msg); - msg = consumer2.receive(); - assertNotNull(msg); + msg = consumer2.receive(POSITIVE_RECEIVE_TIMEOUT); + assertNotNull("Message should have been received",msg); assertEquals("Consumer 2 should also received the first msg.", "A", ((TextMessage) msg).getText()); msg = consumer2.receive(500); assertNull("There should be no more messages for consumption on consumer2.", msg); @@ -235,10 +246,10 @@ public class DurableSubscriptionTest extends QpidTestCase producer.send(session0.createTextMessage("B")); _logger.info("Receive message on consumer 1 :expecting B"); - msg = consumer1.receive(1000); + msg = consumer1.receive(NEGATIVE_RECEIVE_TIMEOUT); assertEquals("B", ((TextMessage) msg).getText()); _logger.info("Receive message on consumer 1 :expecting null"); - msg = consumer1.receive(1000); + msg = consumer1.receive(NEGATIVE_RECEIVE_TIMEOUT); assertEquals(null, msg); // Re-attach a new consumer to the durable subscription, and check that it gets the message that it missed. @@ -296,7 +307,7 @@ public class DurableSubscriptionTest extends QpidTestCase producer.send(session.createTextMessage("testDurableWithInvalidSelector2")); - Message msg = liveSubscriber.receive(); + Message msg = liveSubscriber.receive(POSITIVE_RECEIVE_TIMEOUT); assertNotNull ("Message should have been received", msg); assertEquals ("testDurableWithInvalidSelector2", ((TextMessage) msg).getText()); assertNull("Should not receive subsequent message", liveSubscriber.receive(200)); @@ -331,7 +342,7 @@ public class DurableSubscriptionTest extends QpidTestCase assertNotNull("Subscriber should have been created", liveSubscriber); producer.send(session.createTextMessage("testDurableWithInvalidSelector2")); - Message msg = liveSubscriber.receive(); + Message msg = liveSubscriber.receive(POSITIVE_RECEIVE_TIMEOUT); assertNotNull ("Message should have been received", msg); assertEquals ("testDurableWithInvalidSelector2", ((TextMessage) msg).getText()); assertNull("Should not receive subsequent message", liveSubscriber.receive(200)); @@ -360,13 +371,13 @@ public class DurableSubscriptionTest extends QpidTestCase // Send 1 matching message and 1 non-matching message sendMatchingAndNonMatchingMessage(session, producer); - Message rMsg = subA.receive(1000); + Message rMsg = subA.receive(NEGATIVE_RECEIVE_TIMEOUT); assertNotNull(rMsg); assertEquals("Content was wrong", "testResubscribeWithChangedSelector1", ((TextMessage) rMsg).getText()); - rMsg = subA.receive(1000); + rMsg = subA.receive(NEGATIVE_RECEIVE_TIMEOUT); assertNull(rMsg); // Disconnect subscriber @@ -379,13 +390,13 @@ public class DurableSubscriptionTest extends QpidTestCase // Check messages are recieved properly sendMatchingAndNonMatchingMessage(session, producer); - rMsg = subB.receive(1000); + rMsg = subB.receive(NEGATIVE_RECEIVE_TIMEOUT); assertNotNull(rMsg); assertEquals("Content was wrong", "testResubscribeWithChangedSelector2", ((TextMessage) rMsg).getText()); - rMsg = subB.receive(1000); + rMsg = subB.receive(NEGATIVE_RECEIVE_TIMEOUT); assertNull(rMsg); session.unsubscribe("testResubscribeWithChangedSelector"); } @@ -429,5 +440,5 @@ public class DurableSubscriptionTest extends QpidTestCase public static junit.framework.Test suite() { return new junit.framework.TestSuite(DurableSubscriptionTest.class); - } + } } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/CommitRollbackTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/CommitRollbackTest.java index 9c755fcb41..b603455644 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/CommitRollbackTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/CommitRollbackTest.java @@ -479,7 +479,7 @@ public class CommitRollbackTest extends QpidTestCase _publisher.send(_pubSession.createTextMessage(MESSAGE_TEXT)); _pubSession.commit(); - assertNotNull(_consumer.receive(100)); + assertNotNull(_consumer.receive(1000)); _publisher.send(_pubSession.createTextMessage(MESSAGE_TEXT)); diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java index cc9cfce34b..1bef07fcd5 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java @@ -55,7 +55,7 @@ public class FailoverBaseCase extends QpidTestCase { super.setUp(); setSystemProperty("QPID_WORK", System.getProperty("java.io.tmpdir")+"/"+getFailingPort()); - startBroker(FAILING_PORT); + startBroker(failingPort); } /** @@ -76,7 +76,7 @@ public class FailoverBaseCase extends QpidTestCase public void tearDown() throws Exception { - stopBroker(FAILING_PORT); + stopBroker(_broker.equals(VM)?FAILING_PORT:FAILING_PORT); super.tearDown(); FileUtils.deleteDirectory(System.getProperty("java.io.tmpdir")+"/"+getFailingPort()); } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitor.java b/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitor.java index df8dd0b85b..44ac5b4838 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitor.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitor.java @@ -31,6 +31,7 @@ import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; +import java.util.ArrayList; import java.util.List; /** @@ -118,7 +119,7 @@ public class LogMonitor * @throws java.io.FileNotFoundException if the Log file can nolonger be found * @throws IOException thrown when reading the log file */ - public boolean waitForMessage(String message, long wait) + public boolean waitForMessage(String message, long wait, boolean printFileOnFailure) throws FileNotFoundException, IOException { // Loop through alerts until we're done or wait ms seconds have passed, @@ -126,20 +127,35 @@ public class LogMonitor BufferedReader reader = new BufferedReader(new FileReader(_logfile)); boolean found = false; long endtime = System.currentTimeMillis() + wait; + ArrayList contents = new ArrayList(); while (!found && System.currentTimeMillis() < endtime) { while (reader.ready()) { String line = reader.readLine(); + contents.add(line); if (line.contains(message)) { found = true; } } } - + if (!found && printFileOnFailure) + { + for (String line : contents) + { + System.out.println(line); + } + } return found; } + + + public boolean waitForMessage(String messageCountAlert, long alertLogWaitPeriod) throws FileNotFoundException, IOException + { + return waitForMessage(messageCountAlert, alertLogWaitPeriod, true); + } + /** * Read the log file in to memory as a String diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitorTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitorTest.java index d1a0df30a9..2b9fe8e039 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitorTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitorTest.java @@ -30,25 +30,25 @@ import java.util.List; public class LogMonitorTest extends TestCase { + private LogMonitor _monitor; + + @Override + public void setUp() throws Exception + { + _monitor = new LogMonitor(); + _monitor.getMonitoredFile().deleteOnExit(); // Make sure we clean up + } + /** * Test that a new file is created when attempting to set up a monitor with * the default constructor. */ public void testMonitor() { - // Validate that a NPE is thrown with null input - try - { - LogMonitor montior = new LogMonitor(); - //Validte that the monitor is now running on a new file - assertTrue("New file does not have correct name:" + montior. - getMonitoredFile().getName(), - montior.getMonitoredFile().getName().contains("LogMonitor")); - } - catch (IOException ioe) - { - fail("IOE thrown:" + ioe); - } + //Validate that the monitor is now running on a new file + assertTrue("New file does not have correct name:" + _monitor. + getMonitoredFile().getName(), + _monitor.getMonitoredFile().getName().contains("LogMonitor")); } /** @@ -63,13 +63,11 @@ public class LogMonitorTest extends TestCase File testFile = File.createTempFile("testMonitorFile", ".log"); testFile.deleteOnExit(); - LogMonitor monitor; - //Ensure that we can create a monitor on a file try { - monitor = new LogMonitor(testFile); - assertEquals(testFile, monitor.getMonitoredFile()); + _monitor = new LogMonitor(testFile); + assertEquals(testFile, _monitor.getMonitoredFile()); } catch (IOException ioe) { @@ -136,13 +134,12 @@ public class LogMonitorTest extends TestCase */ public void testFindMatches_Match() throws IOException { - LogMonitor monitor = new LogMonitor(); String message = getName() + ": Test Message"; Logger.getRootLogger().warn(message); - validateLogContainsMessage(monitor, message); + validateLogContainsMessage(_monitor, message); } /** @@ -152,35 +149,17 @@ public class LogMonitorTest extends TestCase */ public void testFindMatches_NoMatch() throws IOException { - LogMonitor monitor = new LogMonitor(); - String message = getName() + ": Test Message"; Logger.getRootLogger().warn(message); String notLogged = "This text was not logged"; - validateLogDoesNotContainsMessage(monitor, notLogged); - } - - public void testWaitForMessage_Found() throws IOException - { - LogMonitor monitor = new LogMonitor(); - - String message = getName() + ": Test Message"; - - long TIME_OUT = 2000; - - logMessageWithDelay(message, TIME_OUT / 2); - - assertTrue("Message was not logged ", - monitor.waitForMessage(message, TIME_OUT)); + validateLogDoesNotContainsMessage(_monitor, notLogged); } public void testWaitForMessage_Timeout() throws IOException { - LogMonitor monitor = new LogMonitor(); - String message = getName() + ": Test Message"; long TIME_OUT = 2000; @@ -189,41 +168,37 @@ public class LogMonitorTest extends TestCase // Verify that we can time out waiting for a message assertFalse("Message was logged ", - monitor.waitForMessage(message, TIME_OUT / 2)); + _monitor.waitForMessage(message, TIME_OUT / 2, false)); // Verify that the message did eventually get logged. assertTrue("Message was never logged.", - monitor.waitForMessage(message, TIME_OUT)); + _monitor.waitForMessage(message, TIME_OUT)); } public void testReset() throws IOException { - LogMonitor monitor = new LogMonitor(); - String message = getName() + ": Test Message"; Logger.getRootLogger().warn(message); - validateLogContainsMessage(monitor, message); + validateLogContainsMessage(_monitor, message); String LOG_RESET_TEXT = "Log Monitor Reset"; - validateLogDoesNotContainsMessage(monitor, LOG_RESET_TEXT); + validateLogDoesNotContainsMessage(_monitor, LOG_RESET_TEXT); - monitor.reset(); + _monitor.reset(); - assertEquals("", monitor.readFile()); + assertEquals("", _monitor.readFile()); } public void testRead() throws IOException { - LogMonitor monitor = new LogMonitor(); - String message = getName() + ": Test Message"; Logger.getRootLogger().warn(message); - String fileContents = monitor.readFile(); + String fileContents = _monitor.readFile(); assertTrue("Logged message not found when reading file.", fileContents.contains(message)); -- cgit v1.2.1 From 9c4ecc45da929750ff7f0e0a5d7ada4e674b9105 Mon Sep 17 00:00:00 2001 From: Aidan Skinner Date: Wed, 16 Sep 2009 10:06:55 +0000 Subject: QPID-2105: Make NetworkDriver.open use a SSLContextFactory, not an SSLEngine. Allow an existing SocketConnector to be passed into a MINANetworkDriver, for use with the ExistingSocket bit of TransportConnection. Move the ExistingSocket stuff to one place, use MINANetworkDriver in TransportConnection and make AMQProtocolHandler implement ProtocolEngine. Remove MINA specific gubbins from AMQProtocolHandler and AMQProtocolSession. Move fireAsynchEvent to Job Add getLocalAddress to AMQProtocolEngine Move TestNetworkDriver to common Use correct class for logger in AMQProtocolEngine Check the exception is thrown properly in SimpleACLTest, make it a little less prone to obscure race conditions. git-svn-id: https://svn.apache.org/repos/asf/qpid/branches/java-network-refactor@815704 13f79535-47bb-0310-9956-ffa450edef68 --- .../qpid/server/security/acl/SimpleACLTest.java | 54 +++++++++++++--------- .../client/protocol/AMQProtocolSessionTest.java | 29 ++++++------ 2 files changed, 49 insertions(+), 34 deletions(-) (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java index b5c0a87b0f..f402522a19 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java @@ -22,6 +22,9 @@ package org.apache.qpid.server.security.acl; import junit.framework.TestCase; + +import org.apache.log4j.BasicConfigurator; +import org.apache.log4j.Logger; import org.apache.qpid.client.transport.TransportConnection; import org.apache.qpid.client.*; import org.apache.qpid.framing.AMQShortString; @@ -34,11 +37,17 @@ import org.apache.qpid.url.URLSyntaxException; import javax.jms.*; import javax.jms.IllegalStateException; + import java.io.File; +import java.util.ArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; -public class SimpleACLTest extends QpidTestCase implements ConnectionListener +public class SimpleACLTest extends QpidTestCase implements ConnectionListener, ExceptionListener { private String BROKER = "vm://:"+ApplicationRegistry.DEFAULT_INSTANCE;//"tcp://localhost:5672"; + private ArrayList _thrownExceptions = new ArrayList(); + private CountDownLatch _awaitError = new CountDownLatch(51); public void setUp() throws Exception { @@ -268,7 +277,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener } } - public void testClientPublishInvalidQueueSuccess() throws AMQException, URLSyntaxException, JMSException + public void testClientPublishInvalidQueueSuccess() throws AMQException, URLSyntaxException, JMSException, InterruptedException { try { @@ -276,41 +285,38 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener ((AMQConnection) conn).setConnectionListener(this); - Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE); conn.start(); - + conn.setExceptionListener(this); MessageProducer sender = ((AMQSession) session).createProducer(null); - Queue queue = session.createQueue("Invalid"); - + Queue queue = session.createQueue("NewQueueThatIDoNotHaveRightsToPublishToo"); + // Send a message that we will wait to be sent, this should give the broker time to close the connection // before we finish this test. Message is set !immed !mand as the queue is invalid so want to test ACLs not // queue existence. ((org.apache.qpid.jms.MessageProducer) sender).send(queue, session.createTextMessage("test"), DeliveryMode.NON_PERSISTENT, 0, 0L, false, false, true); - // Test the connection with a valid consumer - // This may fail as the session may be closed before the queue or the consumer created. - Queue temp = session.createTemporaryQueue(); - - session.createConsumer(temp).close(); - - //Connection should now be closed and will throw the exception caused by the above send - conn.close(); - - fail("Close is not expected to succeed."); + _awaitError.await(1, TimeUnit.SECONDS); } catch (JMSException e) { - Throwable cause = e.getLinkedException(); - if (!(cause instanceof AMQAuthenticationException)) + fail("Unknown exception thrown:" + e.getMessage()); + } + boolean foundCorrectException = false; + for (Exception cause : _thrownExceptions) + { + if (cause instanceof JMSException) { - e.printStackTrace(); + if (((JMSException) cause).getLinkedException() instanceof AMQAuthenticationException) + { + foundCorrectException = true; + } } - assertEquals("Incorrect exception", AMQAuthenticationException.class, cause.getClass()); - assertEquals("Incorrect error code thrown", 403, ((AMQAuthenticationException) cause).getErrorCode().getCode()); } + assertTrue("Did not get AMQAuthenticationException thrown", foundCorrectException); } public void testServerConsumeFromNamedQueueValid() throws AMQException, URLSyntaxException @@ -657,4 +663,10 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener public void failoverComplete() { } + + public void onException(JMSException arg0) + { + _thrownExceptions.add(arg0); + _awaitError.countDown(); + } } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java index 91cb37e455..b99cd239d3 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java @@ -20,27 +20,27 @@ */ package org.apache.qpid.test.unit.client.protocol; -import org.apache.mina.common.IoSession; import org.apache.qpid.client.AMQConnection; import org.apache.qpid.client.protocol.AMQProtocolHandler; import org.apache.qpid.client.protocol.AMQProtocolSession; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.protocol.TestIoSession; +import org.apache.qpid.transport.TestNetworkDriver; +import org.apache.qpid.transport.NetworkDriver; public class AMQProtocolSessionTest extends QpidTestCase { private static class AMQProtSession extends AMQProtocolSession { - public AMQProtSession(AMQProtocolHandler protocolHandler, IoSession protocolSession, AMQConnection connection) + public AMQProtSession(AMQProtocolHandler protocolHandler, AMQConnection connection) { - super(protocolHandler,protocolSession,connection); + super(protocolHandler,connection); } - public TestIoSession getMinaProtocolSession() + public TestNetworkDriver getNetworkDriver() { - return (TestIoSession) _minaProtocolSession; + return (TestNetworkDriver) _protocolHandler.getNetworkDriver(); } public AMQShortString genQueueName() @@ -63,8 +63,11 @@ public class AMQProtocolSessionTest extends QpidTestCase { super.setUp(); + AMQConnection con = (AMQConnection) getConnection("guest", "guest"); + AMQProtocolHandler protocolHandler = new AMQProtocolHandler(con); + protocolHandler.setNetworkDriver(new TestNetworkDriver()); //don't care about the values set here apart from the dummy IoSession - _testSession = new AMQProtSession(null,new TestIoSession(), (AMQConnection) getConnection("guest", "guest")); + _testSession = new AMQProtSession(protocolHandler , con); //initialise addresses for test and expected results _port = 123; @@ -75,32 +78,32 @@ public class AMQProtocolSessionTest extends QpidTestCase _validAddress = "abc"; _generatedAddress_3 = "tmp_abc123_3"; } - +/* public void testGenerateQueueName() { AMQShortString testAddress; //test address with / and ; chars which generateQueueName should removeKey - _testSession.getMinaProtocolSession().setStringLocalAddress(_brokenAddress); - _testSession.getMinaProtocolSession().setLocalPort(_port); + _testSession.getNetworkDriver().setLocalAddress(_brokenAddress); + _testSession.getNetworkDriver().setPort(_port); testAddress = _testSession.genQueueName(); assertEquals("Failure when generating a queue exchange from an address with special chars",_generatedAddress,testAddress.toString()); //test empty address - _testSession.getMinaProtocolSession().setStringLocalAddress(_emptyAddress); + _testSession.getNetworkDriver().setLocalAddress(_emptyAddress); testAddress = _testSession.genQueueName(); assertEquals("Failure when generating a queue exchange from an empty address",_generatedAddress_2,testAddress.toString()); //test address with no special chars - _testSession.getMinaProtocolSession().setStringLocalAddress(_validAddress); + _testSession.getNetworkDriver().setStringLocalAddress(_validAddress); testAddress = _testSession.genQueueName(); assertEquals("Failure when generating a queue exchange from an address with no special chars",_generatedAddress_3,testAddress.toString()); } - +*/ protected void tearDown() throws Exception { _testSession = null; -- cgit v1.2.1 From e2318508673d16d54b544ca589357003b7cfecc1 Mon Sep 17 00:00:00 2001 From: Aidan Skinner Date: Wed, 16 Sep 2009 10:17:20 +0000 Subject: QPID-2105: Merging the patch didn't uncomment this test, stoopid git. git-svn-id: https://svn.apache.org/repos/asf/qpid/branches/java-network-refactor@815708 13f79535-47bb-0310-9956-ffa450edef68 --- .../qpid/test/unit/client/protocol/AMQProtocolSessionTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java index b99cd239d3..7a27925a36 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java @@ -78,7 +78,7 @@ public class AMQProtocolSessionTest extends QpidTestCase _validAddress = "abc"; _generatedAddress_3 = "tmp_abc123_3"; } -/* + public void testGenerateQueueName() { AMQShortString testAddress; @@ -97,13 +97,13 @@ public class AMQProtocolSessionTest extends QpidTestCase assertEquals("Failure when generating a queue exchange from an empty address",_generatedAddress_2,testAddress.toString()); //test address with no special chars - _testSession.getNetworkDriver().setStringLocalAddress(_validAddress); + _testSession.getNetworkDriver().setLocalAddress(_validAddress); testAddress = _testSession.genQueueName(); assertEquals("Failure when generating a queue exchange from an address with no special chars",_generatedAddress_3,testAddress.toString()); } -*/ + protected void tearDown() throws Exception { _testSession = null; -- cgit v1.2.1 From 7d6a028be9f6c47418e98a6fa74a359864428150 Mon Sep 17 00:00:00 2001 From: Aidan Skinner Date: Thu, 17 Sep 2009 16:21:13 +0000 Subject: Merge from trunk git-svn-id: https://svn.apache.org/repos/asf/qpid/branches/java-network-refactor@816261 13f79535-47bb-0310-9956-ffa450edef68 --- .../management/jmx/ManagementActorLoggingTest.java | 527 +++++++-------------- .../configuration/ServerConfigurationFileTest.java | 2 + .../apache/qpid/server/logging/AlertingTest.java | 14 +- .../logging/DerbyMessageStoreLoggingTest.java | 43 +- .../qpid/server/logging/ManagementLoggingTest.java | 6 +- .../logging/MemoryMessageStoreLoggingTest.java | 12 +- .../server/logging/VirtualHostLoggingTest.java | 8 +- .../org/apache/qpid/server/queue/ModelTest.java | 299 ++++++++++++ .../qpid/server/security/acl/SimpleACLTest.java | 134 +++--- .../test/client/timeouts/SyncWaitDelayTest.java | 21 +- .../apache/qpid/test/utils/FailoverBaseCase.java | 4 +- .../org/apache/qpid/test/utils/JMXTestUtils.java | 208 ++++++++ .../org/apache/qpid/test/utils/QpidTestCase.java | 139 +++--- 13 files changed, 872 insertions(+), 545 deletions(-) create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/server/queue/ModelTest.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/utils/JMXTestUtils.java (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java index b4ba6e8156..2e107ada34 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/management/jmx/ManagementActorLoggingTest.java @@ -20,26 +20,19 @@ */ package org.apache.qpid.management.jmx; -import org.apache.qpid.commands.objects.AllObjects; -import org.apache.qpid.management.common.JMXConnnectionFactory; import org.apache.qpid.management.common.mbeans.ManagedBroker; import org.apache.qpid.management.common.mbeans.ManagedConnection; import org.apache.qpid.management.common.mbeans.ManagedExchange; import org.apache.qpid.server.logging.AbstractTestLogging; import org.apache.qpid.server.logging.subjects.AbstractTestLogSubject; +import org.apache.qpid.test.utils.JMXTestUtils; import javax.jms.Connection; import javax.jms.ExceptionListener; import javax.jms.JMSException; import javax.management.JMException; -import javax.management.MBeanException; -import javax.management.MBeanServerConnection; -import javax.management.MBeanServerInvocationHandler; -import javax.management.ObjectName; -import javax.management.remote.JMXConnector; import java.io.IOException; import java.util.List; -import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -50,33 +43,21 @@ import java.util.concurrent.TimeUnit; */ public class ManagementActorLoggingTest extends AbstractTestLogging { - MBeanServerConnection _mbsc; - JMXConnector _jmxc; + private JMXTestUtils _jmxUtils; private static final String USER = "admin"; @Override public void setUp() throws Exception { - setConfigurationProperty("management.enabled", "true"); + _jmxUtils = new JMXTestUtils(this, USER, USER); + _jmxUtils.setUp(); super.setUp(); - - if (isExternalBroker()) - { - _jmxc = JMXConnnectionFactory.getJMXConnection( - 5000, "127.0.0.1", - getManagementPort(getPort()), USER, USER); - - _mbsc = _jmxc.getMBeanServerConnection(); - } } @Override public void tearDown() throws Exception { - if (isExternalBroker()) - { - _jmxc.close(); - } + _jmxUtils.close(); super.tearDown(); } @@ -107,34 +88,31 @@ public class ManagementActorLoggingTest extends AbstractTestLogging */ public void testJMXManagementConsoleConnection() throws IOException { - if (isExternalBroker()) - { - List results = _monitor.findMatches("MNG-1007"); + List results = _monitor.findMatches("MNG-1007"); - assertEquals("Unexpected Management Connection count", 1, results.size()); + assertEquals("Unexpected Management Connection count", 1, results.size()); - String log = getLog(results.get(0)); + String log = getLog(results.get(0)); - validateMessageID("MNG-1007", log); + validateMessageID("MNG-1007", log); - assertTrue("User not in log message:" + log, log.endsWith(USER)); - // Extract the id from the log string - // MESSAGE [mng:1(rmi://169.24.29.116)] MNG-1007 : Open : User admin - int connectionID = Integer.parseInt(fromActor(getLog(results.get(0))).charAt(4) + ""); + assertTrue("User not in log message:" + log, log.endsWith(USER)); + // Extract the id from the log string + // MESSAGE [mng:1(rmi://169.24.29.116)] MNG-1007 : Open : User admin + int connectionID = Integer.parseInt(fromActor(getLog(results.get(0))).charAt(4) + ""); - results = _monitor.findMatches("MNG-1008"); + results = _monitor.findMatches("MNG-1008"); - assertEquals("Unexpected Management Connection close count", 0, results.size()); + assertEquals("Unexpected Management Connection close count", 0, results.size()); - _jmxc.close(); + _jmxUtils.close(); - results = _monitor.findMatches("MNG-1008"); + results = _monitor.findMatches("MNG-1008"); - assertEquals("Unexpected Management Connection count", 1, results.size()); + assertEquals("Unexpected Management Connection count", 1, results.size()); - assertEquals("Close does not have same id as open,", connectionID, - Integer.parseInt(fromActor(getLog(results.get(0))).charAt(4) + "")); - } + assertEquals("Close does not have same id as open,", connectionID, + Integer.parseInt(fromActor(getLog(results.get(0))).charAt(4) + "")); } /** @@ -159,56 +137,40 @@ public class ManagementActorLoggingTest extends AbstractTestLogging */ public void testConnectionCloseViaManagement() throws IOException, Exception { - if (isExternalBroker()) + //Create a connection to the broker + Connection connection = getConnection(); + + // Monitor the connection for an exception being thrown + // this should be a DisconnectionException but it is not this tests + // job to valiate that. Only use the exception as a synchronisation + // to check the log file for the Close message + final CountDownLatch exceptionReceived = new CountDownLatch(1); + connection.setExceptionListener(new ExceptionListener() { - - //Create a connection to the broker - Connection connection = getConnection(); - - // Monitor the connection for an exception being thrown - // this should be a DisconnectionException but it is not this tests - // job to valiate that. Only use the exception as a synchronisation - // to check the log file for the Close message - final CountDownLatch exceptionReceived = new CountDownLatch(1); - connection.setExceptionListener(new ExceptionListener() + public void onException(JMSException e) { - public void onException(JMSException e) - { - //Failover being attempted. - exceptionReceived.countDown(); - } - }); - - //Remove the connection close from any 0-10 connections - _monitor.reset(); + //Failover being attempted. + exceptionReceived.countDown(); + } + }); - // Get all active AMQP connections - AllObjects allObject = new AllObjects(_mbsc); - allObject.querystring = "org.apache.qpid:type=VirtualHost.Connection,*"; + //Remove the connection close from any 0-10 connections + _monitor.reset(); - Set objectNames = allObject.returnObjects(); + // Get a managedConnection + ManagedConnection mangedConnection = _jmxUtils.getManagedObject(ManagedConnection.class, "org.apache.qpid:type=VirtualHost.Connection,*"); - assertEquals("More than one test connection returned", 1, objectNames.size()); + //Close the connection + mangedConnection.closeConnection(); - ObjectName connectionName = objectNames.iterator().next(); + //Wait for the connection to close + assertTrue("Timed out waiting for conneciton to report close", + exceptionReceived.await(2, TimeUnit.SECONDS)); - ManagedConnection mangedConnection = MBeanServerInvocationHandler. - newProxyInstance(_mbsc, connectionName, - ManagedConnection.class, false); + //Validate results + List results = _monitor.findMatches("CON-1002"); - - //Close the connection - mangedConnection.closeConnection(); - - //Wait for the connection to close - assertTrue("Timed out waiting for conneciton to report close", - exceptionReceived.await(2, TimeUnit.SECONDS)); - - //Validate results - List results = _monitor.findMatches("CON-1002"); - - assertEquals("Unexpected Connection Close count", 1, results.size()); - } + assertEquals("Unexpected Connection Close count", 1, results.size()); } /** @@ -234,114 +196,100 @@ public class ManagementActorLoggingTest extends AbstractTestLogging */ public void testCreateExchangeDirectTransientViaManagementConsole() throws IOException, JMException { - if (isExternalBroker()) - { - //Remove any previous exchange declares - _monitor.reset(); - - createExchange("direct"); + _monitor.reset(); - // Validate + _jmxUtils.createExchange("test", "direct", null, false); - //1 - ID is correct - List results = _monitor.findMatches("EXH-1001"); + // Validate - assertEquals("More than one exchange creation found", 1, results.size()); + //1 - ID is correct + List results = _monitor.findMatches("EXH-1001"); - String log = getLog(results.get(0)); + assertEquals("More than one exchange creation found", 1, results.size()); - // Validate correct exchange name - assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName())); + String log = getLog(results.get(0)); - // Validate it was a management actor. - String actor = fromActor(log); - assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); + // Validate correct exchange name + assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName())); - } + // Validate it was a management actor. + String actor = fromActor(log); + assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); } public void testCreateExchangeTopicTransientViaManagementConsole() throws IOException, JMException { - if (isExternalBroker()) - { - //Remove any previous exchange declares - _monitor.reset(); + //Remove any previous exchange declares + _monitor.reset(); - createExchange("topic"); + _jmxUtils.createExchange("test", "topic", null, false); - // Validate + // Validate - //1 - ID is correct - List results = _monitor.findMatches("EXH-1001"); + //1 - ID is correct + List results = _monitor.findMatches("EXH-1001"); - assertEquals("More than one exchange creation found", 1, results.size()); + assertEquals("More than one exchange creation found", 1, results.size()); - String log = getLog(results.get(0)); + String log = getLog(results.get(0)); - // Validate correct exchange name - assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName())); + // Validate correct exchange name + assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName())); - // Validate it was a management actor. - String actor = fromActor(log); - assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); + // Validate it was a management actor. + String actor = fromActor(log); + assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); - } } public void testCreateExchangeFanoutTransientViaManagementConsole() throws IOException, JMException { - if (isExternalBroker()) - { - //Remove any previous exchange declares - _monitor.reset(); + //Remove any previous exchange declares + _monitor.reset(); - createExchange("fanout"); + _jmxUtils.createExchange("test", "fanout", null, false); - // Validate + // Validate - //1 - ID is correct - List results = _monitor.findMatches("EXH-1001"); + //1 - ID is correct + List results = _monitor.findMatches("EXH-1001"); - assertEquals("More than one exchange creation found", 1, results.size()); + assertEquals("More than one exchange creation found", 1, results.size()); - String log = getLog(results.get(0)); + String log = getLog(results.get(0)); - // Validate correct exchange name - assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName())); + // Validate correct exchange name + assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName())); - // Validate it was a management actor. - String actor = fromActor(log); - assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); + // Validate it was a management actor. + String actor = fromActor(log); + assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); - } } public void testCreateExchangeHeadersTransientViaManagementConsole() throws IOException, JMException { - if (isExternalBroker()) - { - //Remove any previous exchange declares - _monitor.reset(); + //Remove any previous exchange declares + _monitor.reset(); - createExchange("headers"); + _jmxUtils.createExchange("test", "headers", null, false); - // Validate + // Validate - //1 - ID is correct - List results = _monitor.findMatches("EXH-1001"); + //1 - ID is correct + List results = _monitor.findMatches("EXH-1001"); - assertEquals("More than one exchange creation found", 1, results.size()); + assertEquals("More than one exchange creation found", 1, results.size()); - String log = getLog(results.get(0)); + String log = getLog(results.get(0)); - // Validate correct exchange name - assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName())); + // Validate correct exchange name + assertTrue("Incorrect exchange name created:" + log, log.endsWith(getName())); - // Validate it was a management actor. - String actor = fromActor(log); - assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); + // Validate it was a management actor. + String actor = fromActor(log); + assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); - } } /** @@ -365,29 +313,26 @@ public class ManagementActorLoggingTest extends AbstractTestLogging */ public void testCreateQueueTransientViaManagementConsole() throws IOException, JMException { - if (isExternalBroker()) - { - //Remove any previous queue declares - _monitor.reset(); + //Remove any previous queue declares + _monitor.reset(); - createQueue(); + _jmxUtils.createQueue("test", getName(), null, false); - // Validate + // Validate - List results = _monitor.findMatches("QUE-1001"); + List results = _monitor.findMatches("QUE-1001"); - assertEquals("More than one queue creation found", 1, results.size()); + assertEquals("More than one queue creation found", 1, results.size()); - String log = getLog(results.get(0)); + String log = getLog(results.get(0)); - // Validate correct queue name - String subject = fromSubject(log); - assertEquals("Incorrect queue name created", getName(), AbstractTestLogSubject.getSlice("qu", subject)); + // Validate correct queue name + String subject = fromSubject(log); + assertEquals("Incorrect queue name created", getName(), AbstractTestLogSubject.getSlice("qu", subject)); - // Validate it was a management actor. - String actor = fromActor(log); - assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); - } + // Validate it was a management actor. + String actor = fromActor(log); + assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); } /** @@ -411,34 +356,29 @@ public class ManagementActorLoggingTest extends AbstractTestLogging */ public void testQueueDeleteViaManagementConsole() throws IOException, JMException { - if (isExternalBroker()) - { - //Remove any previous queue declares - _monitor.reset(); + //Remove any previous queue declares + _monitor.reset(); - createQueue(); + _jmxUtils.createQueue("test", getName(), null, false); - ManagedBroker managedBroker = MBeanServerInvocationHandler. - newProxyInstance(_mbsc, getVirtualHostManagerObjectName(), - ManagedBroker.class, false); + ManagedBroker managedBroker = _jmxUtils.getManagedBroker("test"); - managedBroker.deleteQueue(getName()); + managedBroker.deleteQueue(getName()); - List results = _monitor.findMatches("QUE-1002"); + List results = _monitor.findMatches("QUE-1002"); - assertEquals("More than one queue deletion found", 1, results.size()); + assertEquals("More than one queue deletion found", 1, results.size()); - String log = getLog(results.get(0)); + String log = getLog(results.get(0)); - // Validate correct binding - String subject = fromSubject(log); - assertEquals("Incorrect queue named in delete", getName(), AbstractTestLogSubject.getSlice("qu", subject)); + // Validate correct binding + String subject = fromSubject(log); + assertEquals("Incorrect queue named in delete", getName(), AbstractTestLogSubject.getSlice("qu", subject)); - // Validate it was a management actor. - String actor = fromActor(log); - assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); + // Validate it was a management actor. + String actor = fromActor(log); + assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); - } } /** @@ -462,98 +402,83 @@ public class ManagementActorLoggingTest extends AbstractTestLogging */ public void testBindingCreateOnDirectViaManagementConsole() throws IOException, JMException { - if (isExternalBroker()) - { - //Remove any previous queue declares - _monitor.reset(); + //Remove any previous queue declares + _monitor.reset(); - createQueue(); + _jmxUtils.createQueue("test", getName(), null, false); - ManagedExchange managedExchange = MBeanServerInvocationHandler. - newProxyInstance(_mbsc, getExchange("amq.direct"), - ManagedExchange.class, false); + ManagedExchange managedExchange = _jmxUtils.getManagedExchange("amq.direct"); - managedExchange.createNewBinding(getName(), getName()); + managedExchange.createNewBinding(getName(), getName()); - List results = _monitor.findMatches("BND-1001"); + List results = _monitor.findMatches("BND-1001"); - assertEquals("More than one bind creation found", 1, results.size()); + assertEquals("More than one bind creation found", 1, results.size()); - String log = getLog(results.get(0)); + String log = getLog(results.get(0)); - // Validate correct binding - String subject = fromSubject(log); - assertEquals("Incorrect queue named in create", getName(), AbstractTestLogSubject.getSlice("qu", subject)); - assertEquals("Incorrect routing key in create", getName(), AbstractTestLogSubject.getSlice("rk", subject)); + // Validate correct binding + String subject = fromSubject(log); + assertEquals("Incorrect queue named in create", getName(), AbstractTestLogSubject.getSlice("qu", subject)); + assertEquals("Incorrect routing key in create", getName(), AbstractTestLogSubject.getSlice("rk", subject)); - // Validate it was a management actor. - String actor = fromActor(log); - assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); - } + // Validate it was a management actor. + String actor = fromActor(log); + assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); } public void testBindingCreateOnTopicViaManagementConsole() throws IOException, JMException { - if (isExternalBroker()) - { - //Remove any previous queue declares - _monitor.reset(); + //Remove any previous queue declares + _monitor.reset(); - createQueue(); + _jmxUtils.createQueue("test", getName(), null, false); - ManagedExchange managedExchange = MBeanServerInvocationHandler. - newProxyInstance(_mbsc, getExchange("amq.topic"), - ManagedExchange.class, false); + ManagedExchange managedExchange = _jmxUtils.getManagedExchange("amq.topic"); - managedExchange.createNewBinding(getName(), getName()); + managedExchange.createNewBinding(getName(), getName()); - List results = _monitor.findMatches("BND-1001"); + List results = _monitor.findMatches("BND-1001"); - assertEquals("More than one bind creation found", 1, results.size()); + assertEquals("More than one bind creation found", 1, results.size()); - String log = getLog(results.get(0)); + String log = getLog(results.get(0)); - // Validate correct binding - String subject = fromSubject(log); - assertEquals("Incorrect queue named in create", getName(), AbstractTestLogSubject.getSlice("qu", subject)); - assertEquals("Incorrect routing key in create", getName(), AbstractTestLogSubject.getSlice("rk", subject)); + // Validate correct binding + String subject = fromSubject(log); + assertEquals("Incorrect queue named in create", getName(), AbstractTestLogSubject.getSlice("qu", subject)); + assertEquals("Incorrect routing key in create", getName(), AbstractTestLogSubject.getSlice("rk", subject)); - // Validate it was a management actor. - String actor = fromActor(log); - assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); - } + // Validate it was a management actor. + String actor = fromActor(log); + assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); } public void testBindingCreateOnFanoutViaManagementConsole() throws IOException, JMException { - if (isExternalBroker()) - { - //Remove any previous queue declares - _monitor.reset(); + //Remove any previous queue declares + _monitor.reset(); - createQueue(); + _jmxUtils.createQueue("test", getName(), null, false); - ManagedExchange managedExchange = MBeanServerInvocationHandler. - newProxyInstance(_mbsc, getExchange("amq.fanout"), - ManagedExchange.class, false); + ManagedExchange managedExchange = _jmxUtils.getManagedExchange("amq.fanout"); - managedExchange.createNewBinding(getName(), getName()); + managedExchange.createNewBinding(getName(), getName()); - List results = _monitor.findMatches("BND-1001"); + List results = _monitor.findMatches("BND-1001"); - assertEquals("More than one bind creation found", 1, results.size()); + assertEquals("More than one bind creation found", 1, results.size()); - String log = getLog(results.get(0)); + String log = getLog(results.get(0)); - // Validate correct binding - String subject = fromSubject(log); - assertEquals("Incorrect queue named in create", getName(), AbstractTestLogSubject.getSlice("qu", subject)); - assertEquals("Incorrect routing key in create", "*", AbstractTestLogSubject.getSlice("rk", subject)); + // Validate correct binding + String subject = fromSubject(log); + assertEquals("Incorrect queue named in create", getName(), AbstractTestLogSubject.getSlice("qu", subject)); + assertEquals("Incorrect routing key in create", "*", AbstractTestLogSubject.getSlice("rk", subject)); - // Validate it was a management actor. - String actor = fromActor(log); - assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); - } + // Validate it was a management actor. + String actor = fromActor(log); + assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); } /** @@ -578,114 +503,28 @@ public class ManagementActorLoggingTest extends AbstractTestLogging */ public void testUnRegisterExchangeViaManagementConsole() throws IOException, JMException { - if (isExternalBroker()) - { + //Remove any previous queue declares + _monitor.reset(); - //Remove any previous queue declares - _monitor.reset(); + _jmxUtils.createExchange("test", "direct", null, false); - createExchange("direct"); + ManagedBroker managedBroker = _jmxUtils.getManagedBroker("test"); - ManagedBroker managedBroker = MBeanServerInvocationHandler. - newProxyInstance(_mbsc, getVirtualHostManagerObjectName(), - ManagedBroker.class, false); + managedBroker.unregisterExchange(getName()); - managedBroker.unregisterExchange(getName()); + List results = _monitor.findMatches("EXH-1002"); - List results = _monitor.findMatches("EXH-1002"); - - assertEquals("More than one exchange deletion found", 1, results.size()); - - String log = getLog(results.get(0)); - - // Validate correct binding - String subject = fromSubject(log); - assertEquals("Incorrect exchange named in delete", "direct/" + getName(), AbstractTestLogSubject.getSlice("ex", subject)); - - // Validate it was a management actor. - String actor = fromActor(log); - assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); - } - } - - /** - * Create a non-durable test exchange with the current test name - * - * @throws JMException - is thrown if a exchange with this testName already exists - * @throws IOException - if there is a problem with the JMX Connection - * @throws javax.management.MBeanException - * - if there is another problem creating the exchange - */ - private void createExchange(String type) - throws JMException, IOException, MBeanException - { - ManagedBroker managedBroker = MBeanServerInvocationHandler. - newProxyInstance(_mbsc, getVirtualHostManagerObjectName(), - ManagedBroker.class, false); - - managedBroker.createNewExchange(getName(), type, false); - } - - /** - * Create a non-durable queue (with no owner) that is named after the - * creating test. - * - * @throws JMException - is thrown if a queue with this testName already exists - * @throws IOException - if there is a problem with the JMX Connection - */ - private void createQueue() - throws JMException, IOException - { - ManagedBroker managedBroker = MBeanServerInvocationHandler. - newProxyInstance(_mbsc, getVirtualHostManagerObjectName(), - ManagedBroker.class, false); - - managedBroker.createNewQueue(getName(), null, false); - } - - /** - * Retrive the ObjectName for the test Virtualhost. - * - * This is then use to create aproxy to the ManagedBroker MBean. - * - * @return the ObjectName for the 'test' VirtualHost. - */ - private ObjectName getVirtualHostManagerObjectName() - { - // Get the name of the test manager - AllObjects allObject = new AllObjects(_mbsc); - allObject.querystring = "org.apache.qpid:type=VirtualHost.VirtualHostManager,VirtualHost=test,*"; - - Set objectNames = allObject.returnObjects(); - - assertEquals("Incorrect number test vhosts returned", 1, objectNames.size()); - - // We have verified we have only one value in objectNames so return it - return objectNames.iterator().next(); - } - - /** - * Retrive the ObjectName for the given Exchange on the test Virtualhost. - * - * This is then use to create aproxy to the ManagedExchange MBean. - * - * @param exchange The exchange to retireve e.g. 'direct' - * - * @return the ObjectName for the given exchange on the test VirtualHost. - */ - private ObjectName getExchange(String exchange) - { - // Get the name of the test manager - AllObjects allObject = new AllObjects(_mbsc); - allObject.querystring = "org.apache.qpid:type=VirtualHost.Exchange,VirtualHost=test,name=" + exchange + ",*"; + assertEquals("More than one exchange deletion found", 1, results.size()); - Set objectNames = allObject.returnObjects(); + String log = getLog(results.get(0)); - assertEquals("Incorrect number of exchange with name '" + exchange + - "' returned", 1, objectNames.size()); + // Validate correct binding + String subject = fromSubject(log); + assertEquals("Incorrect exchange named in delete", "direct/" + getName(), AbstractTestLogSubject.getSlice("ex", subject)); - // We have verified we have only one value in objectNames so return it - return objectNames.iterator().next(); + // Validate it was a management actor. + String actor = fromActor(log); + assertTrue("Actor is not a manangement actor:" + actor, actor.startsWith("mng")); } } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/configuration/ServerConfigurationFileTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/configuration/ServerConfigurationFileTest.java index c4803e121e..0a88ef391c 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/server/configuration/ServerConfigurationFileTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/configuration/ServerConfigurationFileTest.java @@ -40,6 +40,8 @@ public class ServerConfigurationFileTest extends QpidTestCase { fail("Unable to test without config file:" + _configFile); } + + saveTestConfiguration(); _serverConfig = new ServerConfiguration(_configFile); } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/AlertingTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/AlertingTest.java index 620b2a5161..683abee4da 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/AlertingTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/AlertingTest.java @@ -94,7 +94,7 @@ public class AlertingTest extends AbstractTestLogging { _connection = getConnection(); _session = _connection.createSession(true, Session.SESSION_TRANSACTED); - _destination = _session.createQueue("testQueue"); + _destination = _session.createQueue(getTestQueueName()); // Consumer is only used to actually create the destination _session.createConsumer(_destination).close(); @@ -116,14 +116,12 @@ public class AlertingTest extends AbstractTestLogging // Add the current contents of the log file to test output message.append(_monitor.readFile()); - // Write the server config file to test output - message.append("Server configuration file in use:\n"); - message.append(FileUtils.readFileAsString(_configFile)); + // Write the test config file to test output + message.append("Server configuration overrides in use:\n"); + message.append(FileUtils.readFileAsString(getTestConfigFile())); - // Write the virtualhost config file to test output - message.append("\nVirtualhost configuration file in use:\n"); - message.append(FileUtils.readFileAsString(ServerConfiguration. - flatConfig(_configFile).getString("virtualhosts"))); + message.append("\nVirtualhost maxMessageCount:\n"); + message.append((new ServerConfiguration(_configFile)).getConfig().getString("virtualhosts.virtualhost." + VIRTUALHOST + ".queues.maximumMessageCount")); fail(message.toString()); } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/DerbyMessageStoreLoggingTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/DerbyMessageStoreLoggingTest.java index 254ec9693d..cc3993249c 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/DerbyMessageStoreLoggingTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/DerbyMessageStoreLoggingTest.java @@ -28,6 +28,7 @@ import javax.jms.Connection; import javax.jms.Queue; import javax.jms.Session; import java.util.List; +import java.io.File; /** * The MessageStore test suite validates that the follow log messages as @@ -56,9 +57,9 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest //We call super.setUp but this will not start the broker as that is //part of the test case. - // Load current configuration file to get the list of defined vhosts - Configuration configuration = ServerConfiguration.flatConfig(_configFile); - List vhosts = configuration.getList("virtualhosts.virtualhost.name"); + // Load the default configuration file to get the list of defined vhosts + ServerConfiguration configuration = new ServerConfiguration(new File(_configFile.getParent() + "/config.xml")); + List vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name"); // Make them all persistent i.e. Use DerbyMessageStore and // test that it logs correctly. @@ -97,8 +98,8 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest assertTrue("MST messages not logged", results.size() > 0); // Load VirtualHost list from file. - Configuration configuration = ServerConfiguration.flatConfig(_configFile); - List vhosts = configuration.getList("virtualhosts.virtualhost.name"); + ServerConfiguration configuration = new ServerConfiguration(_configFile); + List vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name"); //Validate each vhost logs a creation results = _monitor.findMatches("MST-1002"); @@ -117,7 +118,7 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest // the virtualhost name, found above. AND // the index that the virtualhost is within the configuration. // we can retrive that from the vhosts list previously extracted. - String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); + String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); // Get the Simple class name from the expected class name of o.a.q.s.s.MMS String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1); @@ -160,8 +161,8 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest assertTrue("MST messages not logged", results.size() > 0); // Load VirtualHost list from file. - Configuration configuration = ServerConfiguration.flatConfig(_configFile); - List vhosts = configuration.getList("virtualhosts.virtualhost.name"); + ServerConfiguration configuration = new ServerConfiguration(_configFile); + List vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name"); //Validate each vhost logs a creation results = _monitor.findMatches("MST-1004"); @@ -186,7 +187,7 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest // the virtualhost name, found above. AND // the index that the virtualhost is within the configuration. // we can retrive that from the vhosts list previously extracted. - String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); + String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); // Get the Simple class name from the expected class name of o.a.q.s.s.MMS String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1); @@ -227,8 +228,8 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest assertTrue("MST messages not logged", results.size() > 0); // Load VirtualHost list from file. - Configuration configuration = ServerConfiguration.flatConfig(_configFile); - List vhosts = configuration.getList("virtualhosts.virtualhost.name"); + ServerConfiguration configuration = new ServerConfiguration(_configFile); + List vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name"); //Validate each vhost logs a creation results = _monitor.findMatches("MST-1006"); @@ -253,7 +254,7 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest // the virtualhost name, found above. AND // the index that the virtualhost is within the configuration. // we can retrive that from the vhosts list previously extracted. - String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); + String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); // Get the Simple class name from the expected class name of o.a.q.s.s.MMS String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1); @@ -293,8 +294,8 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest assertTrue("MST messages not logged", results.size() > 0); // Load VirtualHost list from file. - Configuration configuration = ServerConfiguration.flatConfig(_configFile); - List vhosts = configuration.getList("virtualhosts.virtualhost.name"); + ServerConfiguration configuration = new ServerConfiguration(_configFile); + List vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name"); //Validate each vhost logs a creation results = _monitor.findMatches("MST-1004 : Recovery Start :"); @@ -316,7 +317,7 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest // the virtualhost name, found above. AND // the index that the virtualhost is within the configuration. // we can retrive that from the vhosts list previously extracted. - String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); + String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); // Get the Simple class name from the expected class name of o.a.q.s.s.MMS String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1); @@ -358,8 +359,8 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest assertTrue("MST messages not logged", results.size() > 0); // Load VirtualHost list from file. - Configuration configuration = ServerConfiguration.flatConfig(_configFile); - List vhosts = configuration.getList("virtualhosts.virtualhost.name"); + ServerConfiguration configuration = new ServerConfiguration(_configFile); + List vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name"); //Validate each vhost logs a creation results = _monitor.findMatches("MST-1006 : Recovery Complete :"); @@ -381,7 +382,7 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest // the virtualhost name, found above. AND // the index that the virtualhost is within the configuration. // we can retrive that from the vhosts list previously extracted. - String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); + String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); // Get the Simple class name from the expected class name of o.a.q.s.s.MMS String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1); @@ -500,8 +501,8 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest assertTrue("MST messages not logged", results.size() > 0); // Load VirtualHost list from file. - Configuration configuration = ServerConfiguration.flatConfig(_configFile); - List vhosts = configuration.getList("virtualhosts.virtualhost.name"); + ServerConfiguration configuration = new ServerConfiguration(_configFile); + List vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name"); //Validate each vhost logs a creation results = _monitor.findMatches("MST-1004 : Recovery Start : " + queueName); @@ -542,7 +543,7 @@ public class DerbyMessageStoreLoggingTest extends MemoryMessageStoreLoggingTest // the virtualhost name, found above. AND // the index that the virtualhost is within the configuration. // we can retrive that from the vhosts list previously extracted. - String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); + String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); // Get the Simple class name from the expected class name of o.a.q.s.s.MMS String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1); diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/ManagementLoggingTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/ManagementLoggingTest.java index 11c003a2a7..8b7c881a32 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/ManagementLoggingTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/ManagementLoggingTest.java @@ -24,6 +24,7 @@ import junit.framework.AssertionFailedError; import org.apache.qpid.util.LogMonitor; import java.util.List; +import java.io.File; /** * Management Console Test Suite @@ -308,9 +309,8 @@ public class ManagementLoggingTest extends AbstractTestLogging // We expect the RMIConnector Server port to be 100 higher than // the RMI Server Port - int mPort = getPort() + (DEFAULT_MANAGEMENT_PORT - DEFAULT_PORT) + 100; - assertTrue("SSL Keystore entry expected(" + mPort + ").:" + getMessageString(log), - getMessageString(log).endsWith(getConfigurationStringProperty("management.ssl.keyStorePath"))); + assertTrue("SSL Keystore entry expected.:" + getMessageString(log), + getMessageString(log).endsWith(new File(getConfigurationStringProperty("management.ssl.keyStorePath")).getName())); } catch (AssertionFailedError afe) { diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/MemoryMessageStoreLoggingTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/MemoryMessageStoreLoggingTest.java index a1cbeca6de..2298ba4da0 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/MemoryMessageStoreLoggingTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/MemoryMessageStoreLoggingTest.java @@ -89,8 +89,8 @@ public class MemoryMessageStoreLoggingTest extends AbstractTestLogging assertEquals("MST-1001 is not the first MST message", "MST-1001", getMessageID(fromMessage(log))); // Load VirtualHost list from file. - Configuration configuration = ServerConfiguration.flatConfig(_configFile); - List vhosts = configuration.getList("virtualhosts.virtualhost.name"); + ServerConfiguration configuration = new ServerConfiguration(_configFile); + List vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name"); //Validate each vhost logs a creation results = _monitor.findMatches("MST-1001"); @@ -109,7 +109,7 @@ public class MemoryMessageStoreLoggingTest extends AbstractTestLogging // the virtualhost name, found above. AND // the index that the virtualhost is within the configuration. // we can retrive that from the vhosts list previously extracted. - String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); + String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); // Get the Simple class name from the expected class name of o.a.q.s.s.MMS String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1); @@ -156,8 +156,8 @@ public class MemoryMessageStoreLoggingTest extends AbstractTestLogging assertTrue("MST messages not logged", results.size() > 0); // Load VirtualHost list from file. - Configuration configuration = ServerConfiguration.flatConfig(_configFile); - List vhosts = configuration.getList("virtualhosts.virtualhost.name"); + ServerConfiguration configuration = new ServerConfiguration(_configFile); + List vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name"); //Validate each vhost logs a creation results = _monitor.findMatches("MST-1003"); @@ -176,7 +176,7 @@ public class MemoryMessageStoreLoggingTest extends AbstractTestLogging // the virtualhost name, found above. AND // the index that the virtualhost is within the configuration. // we can retrive that from the vhosts list previously extracted. - String fullStoreName = configuration.getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); + String fullStoreName = configuration.getConfig().getString("virtualhosts.virtualhost(" + vhosts.indexOf(vhostName) + ")." + vhostName + ".store.class"); // Get the Simple class name from the expected class name of o.a.q.s.s.MMS String storeName = fullStoreName.substring(fullStoreName.lastIndexOf(".") + 1); diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java index 7bf644508e..f4a0c8b27d 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java @@ -64,8 +64,8 @@ public class VirtualHostLoggingTest extends AbstractTestLogging try { // Validation - Configuration configuration = ServerConfiguration.flatConfig(_configFile); - List vhosts = configuration.getList("virtualhosts.virtualhost.name"); + ServerConfiguration configuration = new ServerConfiguration(_configFile); + List vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name"); //Validate each vhost logs a creation results = _monitor.findMatches("VHT-1001"); @@ -117,8 +117,8 @@ public class VirtualHostLoggingTest extends AbstractTestLogging { // Validation - Configuration configuration = ServerConfiguration.flatConfig(_configFile); - List vhosts = configuration.getList("virtualhosts.virtualhost.name"); + ServerConfiguration configuration = new ServerConfiguration(_configFile); + List vhosts = configuration.getConfig().getList("virtualhosts.virtualhost.name"); //Validate each vhost logs a creation results = _monitor.findMatches("VHT-1002"); diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/queue/ModelTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/queue/ModelTest.java new file mode 100644 index 0000000000..078b8f43ce --- /dev/null +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/queue/ModelTest.java @@ -0,0 +1,299 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.queue; + +import org.apache.qpid.AMQException; +import org.apache.qpid.client.AMQConnection; +import org.apache.qpid.client.AMQSession; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.management.common.mbeans.ManagedBroker; +import org.apache.qpid.management.common.mbeans.ManagedQueue; +import org.apache.qpid.test.utils.JMXTestUtils; +import org.apache.qpid.test.utils.QpidTestCase; + +import javax.jms.Connection; +import javax.jms.JMSException; +import javax.jms.Session; +import javax.management.JMException; +import javax.management.MBeanException; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.UndeclaredThrowableException; + +/** + * This Test validates the Queue Model on the broker. + * Currently it has some basic queue creation / deletion tests. + * However, it should be expanded to include other tests that relate to the + * model. i.e. + * + * The Create and Delete tests should ensure that the requisite logging is + * performed. + * + * Additions to this suite would be to complete testing of creations, validating + * fields such as owner/exclusive, autodelete and priority are correctly set. + * + * Currently this test uses the JMX interface to validate that the queue has + * been declared as expected so these tests cannot run against a CPP broker. + * + * + * Tests should ensure that they clean up after themselves. + * e,g. Durable queue creation test should perform a queue delete. + */ +public class ModelTest extends QpidTestCase +{ + + private static final String USER = "admin"; + private JMXTestUtils _jmxUtils; + private static final String VIRTUALHOST_NAME = "test"; + + @Override + public void setUp() throws Exception + { + // Create a JMX Helper + _jmxUtils = new JMXTestUtils(this, USER, USER); + _jmxUtils.setUp(); + super.setUp(); + + // Open the JMX Connection + _jmxUtils.open(); + } + + @Override + public void tearDown() throws Exception + { + // Close the JMX Connection + _jmxUtils.close(); + super.tearDown(); + } + + /** + * Test that a transient queue can be created via AMQP. + * + * @throws Exception On unexpected error + */ + public void testQueueCreationTransientViaAMQP() throws Exception + { + Connection connection = getConnection(); + + String queueName = getTestQueueName(); + boolean durable = false; + boolean autoDelete = false; + boolean exclusive = false; + + createViaAMQPandValidateViaJMX(connection, queueName, durable, + autoDelete, exclusive); + } + + /** + * Test that a durable queue can be created via AMQP. + * + * @throws Exception On unexpected error + */ + + public void testQueueCreationDurableViaAMQP() throws Exception + { + Connection connection = getConnection(); + + String queueName = getTestQueueName(); + boolean durable = true; + boolean autoDelete = false; + boolean exclusive = false; + + createViaAMQPandValidateViaJMX(connection, queueName, durable, + autoDelete, exclusive); + + // Clean up + ManagedBroker managedBroker = + _jmxUtils.getManagedBroker(VIRTUALHOST_NAME); + managedBroker.deleteQueue(queueName); + } + + /** + * Test that a transient queue can be created via JMX. + * + * @throws IOException if there is a problem via the JMX connection + * @throws javax.management.JMException if there is a problem with the JMX command + */ + public void testCreationTransientViaJMX() throws IOException, JMException + { + String name = getName(); + String owner = null; + boolean durable = false; + + createViaJMXandValidateViaJMX(name, owner, durable, durable); + } + + /** + * Test that a durable queue can be created via JMX. + * + * @throws IOException if there is a problem via the JMX connection + * @throws javax.management.JMException if there is a problem with the JMX command + */ + public void testCreationDurableViaJMX() throws IOException, JMException + { + String name = getName(); + String owner = null; + boolean durable = true; + + createViaJMXandValidateViaJMX(name, owner, durable, durable); + + // Clean up + ManagedBroker managedBroker = + _jmxUtils.getManagedBroker(VIRTUALHOST_NAME); + managedBroker.deleteQueue(name); + } + + /** + * Test that a transient queue can be deleted via JMX. + * + * @throws IOException if there is a problem via the JMX connection + * @throws javax.management.JMException if there is a problem with the JMX command + */ + public void testDeletionTransientViaJMX() throws IOException, JMException + { + String name = getName(); + + _jmxUtils.createQueue(VIRTUALHOST_NAME, name, null, false); + + ManagedBroker managedBroker = _jmxUtils. + getManagedBroker(VIRTUALHOST_NAME); + + try + { + managedBroker.deleteQueue(name); + } + catch (UndeclaredThrowableException e) + { + fail(((MBeanException) ((InvocationTargetException) + e.getUndeclaredThrowable()).getTargetException()).getTargetException().getMessage()); + } + } + + /** + * Test that a durable queue can be created via JMX. + * + * @throws IOException if there is a problem via the JMX connection + * @throws javax.management.JMException if there is a problem with the JMX command + */ + public void testDeletionDurableViaJMX() throws IOException, JMException + { + String name = getName(); + + _jmxUtils.createQueue(VIRTUALHOST_NAME, name, null, true); + + ManagedBroker managedBroker = _jmxUtils. + getManagedBroker(VIRTUALHOST_NAME); + + try + { + managedBroker.deleteQueue(name); + } + catch (UndeclaredThrowableException e) + { + fail(((MBeanException) ((InvocationTargetException) + e.getUndeclaredThrowable()).getTargetException()).getTargetException().getMessage()); + } + } + + /* + * Helper Methods + */ + + /** + * Using the provided JMS Connection create a queue using the AMQP extension + * with the given properties and then validate it was created correctly via + * the JMX Connection + * + * @param connection Qpid JMS Connection + * @param queueName String the desired QueueName + * @param durable boolean if the queue should be durable + * @param autoDelete boolean if the queue is an autoDelete queue + * @param exclusive boolean if the queue is exclusive + * + * @throws AMQException if there is a problem with the createQueue call + * @throws JMException if there is a problem with the JMX validatation + * @throws IOException if there is a problem with the JMX connection + * @throws JMSException if there is a problem creating the JMS Session + */ + private void createViaAMQPandValidateViaJMX(Connection connection, + String queueName, + boolean durable, + boolean autoDelete, + boolean exclusive) + throws AMQException, JMException, IOException, JMSException + { + AMQSession session = (AMQSession) connection.createSession(false, + Session.AUTO_ACKNOWLEDGE); + + session.createQueue(new AMQShortString(queueName), + autoDelete, durable, exclusive); + + validateQueueViaJMX(queueName, exclusive ? ((AMQConnection) connection). + getUsername() : null, durable, autoDelete); + } + + /** + * Use the JMX Helper to create a queue with the given properties and then + * validate it was created correctly via the JMX Connection + * + * @param queueName String the desired QueueName + * @param owner String the owner value that should be set + * @param durable boolean if the queue should be durable + * @param autoDelete boolean if the queue is an autoDelete queue + * + * @throws JMException if there is a problem with the JMX validatation + * @throws IOException if there is a problem with the JMX connection + */ + private void createViaJMXandValidateViaJMX(String queueName, String owner, + boolean durable, boolean autoDelete) + throws JMException, IOException + { + _jmxUtils.createQueue(VIRTUALHOST_NAME, queueName, owner, durable); + + validateQueueViaJMX(queueName, owner, durable, autoDelete); + } + + /** + * Validate that a queue with the given properties exists on the broker + * + * @param queueName String the desired QueueName + * @param owner String the owner value that should be set + * @param durable boolean if the queue should be durable + * @param autoDelete boolean if the queue is an autoDelete queue + * + * @throws JMException if there is a problem with the JMX validatation + * @throws IOException if there is a problem with the JMX connection + */ + private void validateQueueViaJMX(String queueName, String owner, boolean durable, boolean autoDelete) + throws JMException, IOException + { + ManagedQueue managedQueue = _jmxUtils. + getManagedObject(ManagedQueue.class, + _jmxUtils.getQueueObjectName(VIRTUALHOST_NAME, + queueName)); + + assertEquals(queueName, managedQueue.getName()); + assertEquals(String.valueOf(owner), managedQueue.getOwner()); + assertEquals(durable, managedQueue.isDurable()); + assertEquals(autoDelete, managedQueue.isAutoDelete()); + } + +} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java index f402522a19..bb7b5efc75 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java @@ -21,6 +21,7 @@ package org.apache.qpid.server.security.acl; + import junit.framework.TestCase; import org.apache.log4j.BasicConfigurator; @@ -30,6 +31,7 @@ import org.apache.qpid.client.*; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry; +import org.apache.qpid.AMQConnectionFailureException; import org.apache.qpid.AMQException; import org.apache.qpid.test.utils.QpidTestCase; import org.apache.qpid.jms.ConnectionListener; @@ -37,6 +39,7 @@ import org.apache.qpid.url.URLSyntaxException; import javax.jms.*; import javax.jms.IllegalStateException; +import javax.naming.NamingException; import java.io.File; import java.util.ArrayList; @@ -51,46 +54,30 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E public void setUp() throws Exception { - //Shutdown the QTC broker - stopBroker(); - - // Initialise ACLs. - final String QpidExampleHome = System.getProperty("QPID_EXAMPLE_HOME"); - final File defaultaclConfigFile = new File(QpidExampleHome, "etc/acl.config.xml"); - - if (!defaultaclConfigFile.exists()) - { - System.err.println("Configuration file not found:" + defaultaclConfigFile); - fail("Configuration file not found:" + defaultaclConfigFile); - } + final String QPID_HOME = System.getProperty("QPID_HOME"); - if (System.getProperty("QPID_HOME") == null) + if (QPID_HOME == null) { fail("QPID_HOME not set"); } - ConfigurationFileApplicationRegistry config = new ConfigurationFileApplicationRegistry(defaultaclConfigFile); - ApplicationRegistry.initialise(config, ApplicationRegistry.DEFAULT_INSTANCE); - TransportConnection.createVMBroker(ApplicationRegistry.DEFAULT_INSTANCE); - } + // Initialise ACLs. + _configFile = new File(QPID_HOME, "etc/config-systests-acl.xml"); - public void tearDown() - { - TransportConnection.killVMBroker(ApplicationRegistry.DEFAULT_INSTANCE); - ApplicationRegistry.remove(ApplicationRegistry.DEFAULT_INSTANCE); + super.setUp(); } - public String createConnectionString(String username, String password, String broker) + public String createConnectionString(String username, String password) { - return "amqp://" + username + ":" + password + "@clientid/test?brokerlist='" + broker + "?retries='0''"; + return "amqp://" + username + ":" + password + "@clientid/test?brokerlist='" + getBroker() + "?retries='0''"; } public void testAccessAuthorized() throws AMQException, URLSyntaxException { try { - Connection conn = createConnection("client", "guest"); + Connection conn = getConnection("client", "guest"); Session sesh = conn.createSession(true, Session.SESSION_TRANSACTED); @@ -103,28 +90,32 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } catch (Exception e) { - fail("Connection was not created due to:" + e.getMessage()); + fail("Connection was not created due to:" + e); } } - public void testAccessNoRights() throws URLSyntaxException, JMSException + public void testAccessNoRights() throws Exception { try { - Connection conn = createConnection("guest", "guest"); + Connection conn = getConnection("guest", "guest"); //Attempt to do do things to test connection. Session sesh = conn.createSession(true, Session.SESSION_TRANSACTED); conn.start(); sesh.rollback(); - conn.close(); fail("Connection was created."); } - catch (AMQException amqe) + catch (JMSException jmse) { - Throwable cause = amqe.getCause(); - assertEquals("Exception was wrong type", AMQAuthenticationException.class, cause.getClass()); + Throwable linkedException = jmse.getLinkedException(); + assertNotNull("Cause was null", linkedException); + + assertEquals("Linked Exception was wrong type", AMQConnectionFailureException.class, linkedException.getClass()); + + Throwable cause = linkedException.getCause(); + assertEquals("Cause was wrong type", AMQAuthenticationException.class, cause.getClass()); assertEquals("Incorrect error code thrown", 403, ((AMQAuthenticationException) cause).getErrorCode().getCode()); } } @@ -133,7 +124,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E { try { - Connection conn = createConnection("client", "guest"); + Connection conn = getConnection("client", "guest"); Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -149,11 +140,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } } - public void testClientConsumeFromNamedQueueInvalid() throws AMQException, URLSyntaxException + public void testClientConsumeFromNamedQueueInvalid() throws NamingException, Exception { try { - Connection conn = createConnection("client", "guest"); + Connection conn = getConnection("client", "guest"); //Prevent Failover ((AMQConnection) conn).setConnectionListener(this); @@ -180,7 +171,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E { try { - Connection conn = createConnection("client", "guest"); + Connection conn = getConnection("client", "guest"); Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -198,11 +189,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } } - public void testClientCreateNamedQueue() throws JMSException, URLSyntaxException, AMQException + public void testClientCreateNamedQueue() throws NamingException, JMSException, AMQException, Exception { try { - Connection conn = createConnection("client", "guest"); + Connection conn = getConnection("client", "guest"); Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -216,6 +207,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } catch (AMQAuthenticationException amqe) { + amqe.printStackTrace(); assertEquals("Incorrect error code thrown", 403, ((AMQAuthenticationException) amqe).getErrorCode().getCode()); } } @@ -224,7 +216,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E { try { - Connection conn = createConnection("client", "guest"); + Connection conn = getConnection("client", "guest"); ((AMQConnection) conn).setConnectionListener(this); @@ -251,7 +243,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E { try { - Connection conn = createConnection("client", "guest"); + Connection conn = getConnection("client", "guest"); ((AMQConnection) conn).setConnectionListener(this); @@ -277,11 +269,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } } - public void testClientPublishInvalidQueueSuccess() throws AMQException, URLSyntaxException, JMSException, InterruptedException + public void testClientPublishInvalidQueueSuccess() throws AMQException, URLSyntaxException, JMSException, NamingException, Exception { try { - Connection conn = createConnection("client", "guest"); + Connection conn = getConnection("client", "guest"); ((AMQConnection) conn).setConnectionListener(this); @@ -323,7 +315,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E { try { - Connection conn = createConnection("server", "guest"); + Connection conn = getConnection("server", "guest"); Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -339,11 +331,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } } - public void testServerConsumeFromNamedQueueInvalid() throws AMQException, URLSyntaxException + public void testServerConsumeFromNamedQueueInvalid() throws AMQException, URLSyntaxException, NamingException, Exception { try - { - Connection conn = createConnection("client", "guest"); + { + Connection conn = getConnection("client", "guest"); Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -364,11 +356,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } } - public void testServerConsumeFromTemporaryQueue() throws AMQException, URLSyntaxException + public void testServerConsumeFromTemporaryQueue() throws AMQException, URLSyntaxException, NamingException, Exception { try { - Connection conn = createConnection("server","guest"); + Connection conn = getConnection("server", "guest"); Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -388,30 +380,22 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } } - private Connection createConnection(String username, String password) throws AMQException + @Override + public Connection getConnection(String username, String password) throws NamingException, JMSException { - AMQConnection connection = null; - try - { - connection = new AMQConnection(createConnectionString(username, password, BROKER)); - } - catch (URLSyntaxException e) - { - // This should never happen as we generate the URLs. - fail(e.getMessage()); - } + AMQConnection connection = (AMQConnection) super.getConnection(username, password); //Prevent Failover connection.setConnectionListener(this); - return (Connection)connection; + return (Connection) connection; } public void testServerCreateNamedQueueValid() throws JMSException, URLSyntaxException { try { - Connection conn = createConnection("server", "guest"); + Connection conn = getConnection("server", "guest"); Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -428,11 +412,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } } - public void testServerCreateNamedQueueInvalid() throws JMSException, URLSyntaxException, AMQException + public void testServerCreateNamedQueueInvalid() throws JMSException, URLSyntaxException, AMQException, NamingException, Exception { try { - Connection conn = createConnection("server", "guest"); + Connection conn = getConnection("server", "guest"); Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -450,18 +434,18 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } } - public void testServerCreateTemporaryQueueInvalid() throws JMSException, URLSyntaxException, AMQException + public void testServerCreateTemporaryQueueInvalid() throws NamingException, Exception { try { - Connection conn = createConnection("server", "guest"); + Connection conn = getConnection("server", "guest"); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); conn.start(); session.createTemporaryQueue(); - + fail("Test failed as creation succeded."); //conn will be automatically closed } @@ -475,19 +459,19 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } } - public void testServerCreateAutoDeleteQueueInvalid() throws JMSException, URLSyntaxException, AMQException + public void testServerCreateAutoDeleteQueueInvalid() throws NamingException, JMSException, AMQException, Exception { Connection connection = null; try { - connection = createConnection("server", "guest"); + connection = getConnection("server", "guest"); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); ((AMQSession) session).createQueue(new AMQShortString("again_ensure_auto_delete_queue_for_temporary"), - true, false, false); + true, false, false); fail("Test failed as creation succeded."); //connection will be automatically closed @@ -495,7 +479,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E catch (AMQAuthenticationException amqe) { assertEquals("Incorrect error code thrown", 403, amqe.getErrorCode().getCode()); - } + } } /** @@ -506,10 +490,10 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E * @throws URLSyntaxException * @throws JMSException */ - public void testServerPublishUsingTransactionSuccess() throws AMQException, URLSyntaxException, JMSException + public void testServerPublishUsingTransactionSuccess() throws AMQException, URLSyntaxException, JMSException, NamingException, Exception { //Set up the Server - Connection serverConnection = createConnection("server", "guest"); + Connection serverConnection = getConnection("server", "guest"); ((AMQConnection) serverConnection).setConnectionListener(this); @@ -522,7 +506,7 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E serverConnection.start(); //Set up the consumer - Connection clientConnection = createConnection("client", "guest"); + Connection clientConnection = getConnection("client", "guest"); //Send a test mesage Session clientSession = clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -563,8 +547,6 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E //Send the message using a transaction as this will allow us to retrieve any errors that occur on the broker. serverSession.commit(); - - //Ensure Response is received. Message clientResponseMsg = clientResponse.receive(2000); assertNotNull("Client did not receive response message,", clientResponseMsg); @@ -588,11 +570,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } } - public void testServerPublishInvalidQueueSuccess() throws AMQException, URLSyntaxException, JMSException + public void testServerPublishInvalidQueueSuccess() throws AMQException, URLSyntaxException, JMSException, NamingException, Exception { try { - Connection conn = createConnection("server", "guest"); + Connection conn = getConnection("server", "guest"); ((AMQConnection) conn).setConnectionListener(this); diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitDelayTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitDelayTest.java index b13170efc9..a123fb290c 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitDelayTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/client/timeouts/SyncWaitDelayTest.java @@ -57,26 +57,13 @@ public class SyncWaitDelayTest extends QpidTestCase public void setUp() throws Exception { - super.setUp(); - stopBroker(); - if (!_configFile.exists()) - { - fail("Unable to test without config file:" + _configFile); - } - XMLConfiguration configuration = new XMLConfiguration(_configFile); - configuration.setProperty("virtualhosts.virtualhost." + VIRTUALHOST+".store.class", "org.apache.qpid.server.store.SlowMessageStore"); - configuration.setProperty("virtualhosts.virtualhost." + VIRTUALHOST+".store.delays.commitTran.post", POST_COMMIT_DELAY); - configuration.setProperty("management.enabled", "false"); + setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST+".store.class", "org.apache.qpid.server.store.SlowMessageStore"); + setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST+".store.delays.commitTran.post", String.valueOf(POST_COMMIT_DELAY)); + setConfigurationProperty("management.enabled", "false"); - File tmpFile = File.createTempFile("configFile", "test"); - tmpFile.deleteOnExit(); - configuration.save(tmpFile); - - _configFile = tmpFile; - - startBroker(1); + super.setUp(); //Set the syncWrite timeout to be just larger than the delay on the commitTran. setSystemProperty("amqj.default_syncwrite_timeout", String.valueOf(SYNC_WRITE_TIMEOUT)); diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java index 1bef07fcd5..64bd1503ba 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java @@ -21,6 +21,8 @@ package org.apache.qpid.test.utils; import javax.jms.Connection; +import javax.jms.JMSException; +import javax.naming.NamingException; import org.apache.qpid.util.FileUtils; @@ -64,7 +66,7 @@ public class FailoverBaseCase extends QpidTestCase * @return a connection * @throws Exception */ - public Connection getConnection() throws Exception + public Connection getConnection() throws JMSException, NamingException { Connection conn = (Boolean.getBoolean("profile.use_ssl"))? diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/JMXTestUtils.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/JMXTestUtils.java new file mode 100644 index 0000000000..3f8cdb9c25 --- /dev/null +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/JMXTestUtils.java @@ -0,0 +1,208 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.test.utils; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.qpid.commands.objects.AllObjects; +import org.apache.qpid.management.common.JMXConnnectionFactory; +import org.apache.qpid.management.common.mbeans.ManagedBroker; +import org.apache.qpid.management.common.mbeans.ManagedExchange; + +import javax.management.JMException; +import javax.management.MBeanException; +import javax.management.MBeanServerConnection; +import javax.management.MBeanServerInvocationHandler; +import javax.management.ObjectName; +import javax.management.remote.JMXConnector; +import java.io.IOException; +import java.util.Set; + +/** + * + */ +public class JMXTestUtils +{ + QpidTestCase _test; + MBeanServerConnection _mbsc; + JMXConnector _jmxc; + + private String USER; + private String PASSWORD; + + public JMXTestUtils(QpidTestCase test, String user, String password) + { + _test = test; + USER = user; + PASSWORD = password; + } + + public void setUp() throws IOException, ConfigurationException, Exception + { + _test.setConfigurationProperty("management.enabled", "true"); + } + + public void open() throws Exception + { + _jmxc = JMXConnnectionFactory.getJMXConnection( + 5000, "127.0.0.1", + _test.getManagementPort(_test.getPort()), USER, PASSWORD); + + _mbsc = _jmxc.getMBeanServerConnection(); + } + + public void close() throws IOException + { + _jmxc.close(); + } + + /** + * Create a non-durable test exchange with the current test name + * + * @throws javax.management.JMException - is thrown if a exchange with this testName already exists + * @throws java.io.IOException - if there is a problem with the JMX Connection + * @throws javax.management.MBeanException + * - if there is another problem creating the exchange + */ + public void createExchange(String virtualHostName, String name, String type, boolean durable) + throws JMException, IOException, MBeanException + { + ManagedBroker managedBroker = getManagedBroker(virtualHostName); + + managedBroker.createNewExchange(name, type, durable); + } + + /** + * Create a non-durable queue (with no owner) that is named after the + * creating test. + * + * @throws JMException - is thrown if a queue with this testName already exists + * @throws IOException - if there is a problem with the JMX Connection + */ + public void createQueue(String virtualHostName, String name, String owner, boolean durable) + throws JMException, IOException + { + ManagedBroker managedBroker = getManagedBroker(virtualHostName); + + managedBroker.createNewQueue(name, owner, durable); + } + + /** + * Retrive the ObjectName for the test Virtualhost. + * + * This is then use to create aproxy to the ManagedBroker MBean. + * + * @return the ObjectName for the 'test' VirtualHost. + */ + public ObjectName getVirtualHostManagerObjectName(String vhostName) + { + // Get the name of the test manager + AllObjects allObject = new AllObjects(_mbsc); + allObject.querystring = "org.apache.qpid:type=VirtualHost.VirtualHostManager,VirtualHost=" + vhostName + ",*"; + + Set objectNames = allObject.returnObjects(); + + _test.assertEquals("Incorrect number test vhosts returned", 1, objectNames.size()); + + // We have verified we have only one value in objectNames so return it + return objectNames.iterator().next(); + } + + /** + * Retrive the ObjectName for the given Exchange on the test Virtualhost. + * + * This is then use to create aproxy to the ManagedExchange MBean. + * + * @param queue The exchange to retireve e.g. 'direct' + * + * @return the ObjectName for the given exchange on the test VirtualHost. + */ + public ObjectName getQueueObjectName(String virtualHostName, String queue) + { + // Get the name of the test manager + AllObjects allObject = new AllObjects(_mbsc); + allObject.querystring = "org.apache.qpid:type=VirtualHost.Queue,VirtualHost=" + virtualHostName + ",name=" + queue + ",*"; + + Set objectNames = allObject.returnObjects(); + + _test.assertEquals("Incorrect number of exchange with name '" + queue + + "' returned", 1, objectNames.size()); + + // We have verified we have only one value in objectNames so return it + return objectNames.iterator().next(); + } + + /** + * Retrive the ObjectName for the given Exchange on the test Virtualhost. + * + * This is then use to create aproxy to the ManagedExchange MBean. + * + * @param virtualHostName + * @param exchange The exchange to retireve e.g. 'direct' + * + * @return the ObjectName for the given exchange on the test VirtualHost. + */ + public ObjectName getExchangeObjectName(String virtualHostName, String exchange) + { + // Get the name of the test manager + AllObjects allObject = new AllObjects(_mbsc); + allObject.querystring = "org.apache.qpid:type=VirtualHost.Exchange,VirtualHost=" + virtualHostName + ",name=" + exchange + ",*"; + + Set objectNames = allObject.returnObjects(); + + _test.assertEquals("Incorrect number of exchange with name '" + exchange + + "' returned", 1, objectNames.size()); + + // We have verified we have only one value in objectNames so return it + return objectNames.iterator().next(); + } + + public T getManagedObject(Class managedClass, String queryString) + { + AllObjects allObject = new AllObjects(_mbsc); + allObject.querystring = queryString; + + Set objectNames = allObject.returnObjects(); + + _test.assertEquals("More than one " + managedClass + " returned", 1, objectNames.size()); + + ObjectName objectName = objectNames.iterator().next(); + + return getManagedObject(managedClass, objectName); + } + + public T getManagedObject(Class managedClass, ObjectName objectName) + { + return MBeanServerInvocationHandler. + newProxyInstance(_mbsc, objectName, managedClass, false); + } + + public ManagedBroker getManagedBroker(String virtualHost) + { + return getManagedObject(ManagedBroker.class, getVirtualHostManagerObjectName(virtualHost).toString()); + } + + public ManagedExchange getManagedExchange(String exchangeName) + { + return MBeanServerInvocationHandler. + newProxyInstance(_mbsc, getExchangeObjectName("test", exchangeName), + ManagedExchange.class, false); + } +} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidTestCase.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidTestCase.java index db096710dc..76e4118c96 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidTestCase.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidTestCase.java @@ -21,6 +21,7 @@ import junit.framework.TestCase; import junit.framework.TestResult; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; +import org.apache.qpid.AMQException; import org.apache.qpid.client.AMQConnection; import org.apache.qpid.client.AMQConnectionFactory; import org.apache.qpid.client.transport.TransportConnection; @@ -30,6 +31,7 @@ import org.apache.qpid.server.configuration.ServerConfiguration; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry; import org.apache.qpid.server.store.DerbyMessageStore; +import org.apache.qpid.url.URLSyntaxException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -73,6 +75,7 @@ public class QpidTestCase extends TestCase protected long RECEIVE_TIMEOUT = 1000l; private Map _setProperties = new HashMap(); + private XMLConfiguration _testConfiguration = new XMLConfiguration(); /** * Some tests are excluded when the property test.excludes is set to true. @@ -183,8 +186,7 @@ public class QpidTestCase extends TestCase public static final String QUEUE = "queue"; public static final String TOPIC = "topic"; /** Map to hold test defined environment properties */ - private Map _env; - + private Map _env; public QpidTestCase(String name) { @@ -335,7 +337,7 @@ public class QpidTestCase extends TestCase latch.countDown(); } - if (latch != null && line.contains(stopped)) + if (!seenReady && line.contains(stopped)) { stopLine = line; } @@ -368,7 +370,9 @@ public class QpidTestCase extends TestCase /** * Return the management portin use by the broker on this main port + * * @param mainPort the broker's main port. + * * @return the management port that corresponds to the broker on the given port */ protected int getManagementPort(int mainPort) @@ -415,9 +419,14 @@ public class QpidTestCase extends TestCase { port = getPort(port); + // Save any configuratio changes that have been made + saveTestConfiguration(); + Process process = null; if (_broker.equals(VM)) { + setConfigurationProperty("management.jmxport", String.valueOf(getManagementPort(port))); + saveTestConfiguration(); // create an in_VM broker ApplicationRegistry.initialise(new ConfigurationFileApplicationRegistry(_configFile), port); TransportConnection.createVMBroker(port); @@ -438,15 +447,35 @@ public class QpidTestCase extends TestCase env.put("PATH", env.get("PATH").concat(File.pathSeparator + qpidHome + "/bin")); //Add the test name to the broker run. - env.put("QPID_PNAME", "-DPNAME=\"" + _testName + "\""); + // DON'T change PNAME, qpid.stop needs this value. + env.put("QPID_PNAME", "-DPNAME=QPBRKR -DTNAME=\"" + _testName + "\""); env.put("QPID_WORK", System.getProperty("QPID_WORK")); // Add all the environment settings the test requested if (!_env.isEmpty()) { - for(Map.Entry entry : _env.entrySet()) + for (Map.Entry entry : _env.entrySet()) + { + env.put(entry.getKey(), entry.getValue()); + } + } + + String QPID_OPTS = " "; + // Add all the specified system properties to QPID_OPTS + if (!_setProperties.isEmpty()) + { + for (String key : _setProperties.keySet()) + { + QPID_OPTS += "-D" + key + "=" + System.getProperty(key) + " "; + } + + if (env.containsKey("QPID_OPTS")) { - env.put(entry.getKey() ,entry.getValue()); + env.put("QPID_OPTS", env.get("QPID_OPTS") + QPID_OPTS); + } + else + { + env.put("QPID_OPTS", QPID_OPTS); } } @@ -484,6 +513,27 @@ public class QpidTestCase extends TestCase _brokers.put(port, process); } + public String getTestConfigFile() + { + String path = _output == null ? System.getProperty("java.io.tmpdir") : _output; + return path + "/" + getTestQueueName() + ".xml"; + } + + protected void saveTestConfiguration() throws ConfigurationException + { + String testConfig = getTestConfigFile(); + //Specifiy the test configuration + setSystemProperty("test.config", testConfig); + + // This is a work + if (_testConfiguration.isEmpty()) + { + _testConfiguration.addProperty("test", getTestQueueName()); + } + + _testConfiguration.save(getTestConfigFile()); + } + public void cleanBroker() { if (_brokerClean != null) @@ -565,18 +615,12 @@ public class QpidTestCase extends TestCase storeClass = bdb; } - // First we munge the config file and, if we're in a VM, set up an additional logfile - XMLConfiguration configuration = new XMLConfiguration(_configFile); - configuration.setProperty("virtualhosts.virtualhost." + virtualhost + + + _testConfiguration.setProperty("virtualhosts.virtualhost." + virtualhost + ".store.class", storeClass.getName()); - configuration.setProperty("virtualhosts.virtualhost." + virtualhost + + _testConfiguration.setProperty("virtualhosts.virtualhost." + virtualhost + ".store." + DerbyMessageStore.ENVIRONMENT_PATH_PROPERTY, - "${work}/" + virtualhost); - - File tmpFile = File.createTempFile("configFile", "test"); - tmpFile.deleteOnExit(); - configuration.save(tmpFile); - _configFile = tmpFile; + "${QPID_WORK}/" + virtualhost); } /** @@ -591,6 +635,10 @@ public class QpidTestCase extends TestCase */ protected String getConfigurationStringProperty(String property) throws ConfigurationException { + // Call save Configuration to be sure we have saved the test specific + // file. As the optional status + saveTestConfiguration(); + ServerConfiguration configuration = new ServerConfiguration(_configFile); return configuration.getConfig().getString(property); } @@ -613,48 +661,9 @@ public class QpidTestCase extends TestCase protected void setConfigurationProperty(String property, String value) throws ConfigurationException, IOException { - XMLConfiguration configuration = new XMLConfiguration(_configFile); - - // If we are modifying a virtualhost value then we need to do so in - // the virtualhost.xml file as these values overwrite the values in - // the main config.xml file - if (property.startsWith("virtualhosts")) - { - // So locate the virtualhost.xml file and use the ServerConfiguration - // flatConfig method to get the interpolated value. - String vhostConfigFile = ServerConfiguration. - flatConfig(_configFile).getString("virtualhosts"); - - // Load the vhostConfigFile - XMLConfiguration vhostConfiguration = new XMLConfiguration(vhostConfigFile); - - // Set the value specified in to the vhostConfig. - // Remembering that property will be 'virtualhosts.virtulhost....' - // so we need to take off the 'virtualhosts.' from the start. - vhostConfiguration.setProperty(property.substring(property.indexOf(".") + 1), value); - - // Write out the new virtualhost config file - File tmpFile = File.createTempFile("virtualhost-configFile", ".xml"); - tmpFile.deleteOnExit(); - vhostConfiguration.save(tmpFile); - - // Change the property and value to be the new virtualhosts file - // so that then update the value in the main config file. - property = "virtualhosts"; - value = tmpFile.getAbsolutePath(); - } - - configuration.setProperty(property, value); - - // Write the new server config file - File tmpFile = File.createTempFile("configFile", ".xml"); - tmpFile.deleteOnExit(); - configuration.save(tmpFile); - - _logger.info("Qpid Test Case now using configuration File:" - + tmpFile.getAbsolutePath()); - - _configFile = tmpFile; + //Write the value in to this configuration file which will override the + // defaults. + _testConfiguration.setProperty(property, value); } /** @@ -695,14 +704,13 @@ public class QpidTestCase extends TestCase * Add an environtmen variable for the external broker environment * * @param property the property to set - * @param value the value to set it to + * @param value the value to set it to */ protected void setBrokerEnvironment(String property, String value) { - _env.put(property,value); + _env.put(property, value); } - /** * Check whether the broker is an 0.8 * @@ -720,7 +728,7 @@ public class QpidTestCase extends TestCase protected boolean isJavaBroker() { - return _brokerLanguage.equals("java"); + return _brokerLanguage.equals("java") || _broker.equals("vm"); } protected boolean isCppBroker() @@ -807,7 +815,7 @@ public class QpidTestCase extends TestCase return (AMQConnectionFactory) getInitialContext().lookup(factoryName); } - public Connection getConnection() throws Exception + public Connection getConnection() throws JMSException, NamingException { return getConnection("guest", "guest"); } @@ -831,7 +839,7 @@ public class QpidTestCase extends TestCase * * @throws Exception if there is an error getting the connection */ - public Connection getConnection(String username, String password) throws Exception + public Connection getConnection(String username, String password) throws JMSException, NamingException { _logger.info("get Connection"); Connection con = getConnectionFactory().createConnection(username, password); @@ -840,7 +848,7 @@ public class QpidTestCase extends TestCase return con; } - public Connection getConnection(String username, String password, String id) throws Exception + public Connection getConnection(String username, String password, String id) throws JMSException, URLSyntaxException, AMQException, NamingException { _logger.info("get Connection"); Connection con; @@ -860,6 +868,7 @@ public class QpidTestCase extends TestCase /** * Return a uniqueName for this test. * In this case it returns a queue Named by the TestCase and TestName + * * @return String name for a queue */ protected String getTestQueueName() -- cgit v1.2.1 From 98cc985dbd81a84cd0b0a969c57cb941680ec81f Mon Sep 17 00:00:00 2001 From: Aidan Skinner Date: Sun, 11 Oct 2009 23:22:08 +0000 Subject: Merge from trunk git-svn-id: https://svn.apache.org/repos/asf/qpid/branches/java-network-refactor@824198 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpid/server/BrokerStartupTest.java | 22 +- .../MessageDisappearWithIOExceptionTest.java | 330 +++++++++++++++++ .../qpid/server/logging/BrokerLoggingTest.java | 2 +- .../server/queue/DeepQueueConsumeWithSelector.java | 5 +- .../qpid/server/queue/ProducerFlowControlTest.java | 393 ++++++++++++++++++++ .../qpid/server/security/acl/SimpleACLTest.java | 123 +++++-- .../qpid/test/client/QueueBrowserAutoAckTest.java | 6 +- .../apache/qpid/test/client/RollbackOrderTest.java | 170 +++++++-- .../qpid/test/client/failover/FailoverTest.java | 22 +- .../qpid/test/client/message/SelectorTest.java | 271 +++++++++++++- .../test/unit/ack/Acknowledge2ConsumersTest.java | 193 ++++++++++ .../ack/AcknowledgeAfterFailoverOnMessageTest.java | 356 ++++++++++++++++++ .../unit/ack/AcknowledgeAfterFailoverTest.java | 306 ++++++++++++++++ .../test/unit/ack/AcknowledgeOnMessageTest.java | 170 +++++++++ .../apache/qpid/test/unit/ack/AcknowledgeTest.java | 179 ++++----- .../ack/FailoverBeforeConsumingRecoverTest.java | 40 ++ .../org/apache/qpid/test/unit/ack/QuickAcking.java | 148 ++++++++ .../org/apache/qpid/test/unit/ack/RecoverTest.java | 253 ++++++------- .../apache/qpid/test/unit/basic/SelectorTest.java | 306 ---------------- .../qpid/test/unit/message/JMSPropertiesTest.java | 4 +- .../unit/publish/DirtyTrasactedPubilshTest.java | 403 +++++++++++++++++++++ .../apache/qpid/test/utils/FailoverBaseCase.java | 83 +++-- .../org/apache/qpid/test/utils/QpidTestCase.java | 221 +++++++++-- 23 files changed, 3320 insertions(+), 686 deletions(-) create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/server/failover/MessageDisappearWithIOExceptionTest.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/server/queue/ProducerFlowControlTest.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/Acknowledge2ConsumersTest.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverOnMessageTest.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverTest.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeOnMessageTest.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/FailoverBeforeConsumingRecoverTest.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/QuickAcking.java delete mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/basic/SelectorTest.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/publish/DirtyTrasactedPubilshTest.java (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/BrokerStartupTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/BrokerStartupTest.java index 52120019f5..e7975f8d24 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/server/BrokerStartupTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/BrokerStartupTest.java @@ -78,15 +78,23 @@ public class BrokerStartupTest extends AbstractTestLogging // Add an invalid value _broker += " -l invalid"; - // The release-bin build of the broker uses this log4j configuration - // so set up the broker environment to use it for this test. - // Also include -Dlog4j.debug so we can validate that it picked up this config - setBrokerEnvironment("QPID_OPTS", "-Dlog4j.debug -Dlog4j.configuration=file:" + System.getProperty(QPID_HOME) + "/../broker/src/main/java/log4j.properties"); + // The broker has a built in default log4j configuration set up + // so if the the broker cannot load the -l value it will use default + // use this default. Test that this is correctly loaded, by + // including -Dlog4j.debug so we can validate. + setBrokerEnvironment("QPID_OPTS", "-Dlog4j.debug"); // Disable all client logging so we can test for broker DEBUG only. - Logger.getRootLogger().setLevel(Level.WARN); - Logger.getLogger("qpid.protocol").setLevel(Level.WARN); - Logger.getLogger("org.apache.qpid").setLevel(Level.WARN); + setLoggerLevel(Logger.getRootLogger(), Level.WARN); + setLoggerLevel(Logger.getLogger("qpid.protocol"), Level.WARN); + setLoggerLevel(Logger.getLogger("org.apache.qpid"), Level.WARN); + + // Set the broker to use info level logging, which is the qpid-server + // default. Rather than debug which is the test default. + setBrokerOnlySystemProperty("amqj.server.logging.level", "info"); + // Set the logging defaults to info for this test. + setBrokerOnlySystemProperty("amqj.logging.level", "info"); + setBrokerOnlySystemProperty("root.logging.level", "info"); startBroker(); diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/failover/MessageDisappearWithIOExceptionTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/failover/MessageDisappearWithIOExceptionTest.java new file mode 100644 index 0000000000..f1a1c1a9a8 --- /dev/null +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/failover/MessageDisappearWithIOExceptionTest.java @@ -0,0 +1,330 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.failover; + +import org.apache.mina.common.WriteTimeoutException; +import org.apache.qpid.client.AMQConnection; +import org.apache.qpid.client.protocol.AMQProtocolSession; +import org.apache.qpid.jms.ConnectionListener; +import org.apache.qpid.test.utils.QpidTestCase; +import org.apache.qpid.test.utils.FailoverBaseCase; +import org.apache.qpid.AMQConnectionClosedException; + +import javax.jms.Destination; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Queue; +import javax.jms.Session; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * Test case based on user reported error. + * + * Summary: + * A user has reported message loss from their application. On bouncing of + * the broker the 'lost' messages are delivered to the broker. + * + * Note: + * The client was using Spring so that may influence the situation. + * + * Issue: + * The log files show 7 instances of the following which result in 7 + * missing messages. + * + * The client log files show: + * + * The broker log file show: + * + * + * 7 missing messages have delivery tags 5-11. Which says that they are + * sequentially the next message from the broker. + * + * The only way for the 'without a handler' log to occur is if the consumer + * has been removed from the look up table of the dispatcher. + * And the only way for the 'null message' log to occur on the broker is is + * if the message does not exist in the unacked-map + * + * The consumer is only removed from the list during session + * closure and failover. + * + * If the session was closed then the broker would requeue the unacked + * messages so the potential exists to have an empty map but the broker + * will not send a message out after the unacked map has been cleared. + * + * When failover occurs the _consumer map is cleared and the consumers are + * resubscribed. This is down without first stopping any existing + * dispatcher so there exists the potential to receive a message after + * the _consumer map has been cleared which is how the 'without a handler' + * log statement occurs. + * + * Scenario: + * + * Looking over logs the sequence that best fits the events is as follows: + * - Something causes Mina to be delayed causing the WriteTimoutException. + * - This exception is recevied by AMQProtocolHandler#exceptionCaught + * - As the WriteTimeoutException is an IOException this will cause + * sessionClosed to be called to start failover. + * + This is potentially the issues here. All IOExceptions are treated + * as connection failure events. + * - Failover Runs + * + Failover assumes that the previous connection has been closed. + * + Failover binds the existing objects (AMQConnection/Session) to the + * new connection objects. + * - Everything is reported as being successfully failed over. + * However, what is neglected is that the original connection has not + * been closed. + * + So what occurs is that the broker sends a message to the consumer on + * the original connection, as it was not notified of the client + * failing over. + * As the client failover reuses the original AMQSession and Dispatcher + * the new messages the broker sends to the old consumer arrives at the + * client and is processed by the same AMQSession and Dispatcher. + * However, as the failover process cleared the _consumer map and + * resubscribe the consumers the Dispatcher does not recognise the + * delivery tag and so logs the 'without a handler' message. + * - The Dispatcher then attempts to reject the message, however, + * + The AMQSession/Dispatcher pair have been swapped to using a new Mina + * ProtocolSession as part of the failover process so the reject is + * sent down the second connection. The broker receives the Reject + * request but as the Message was sent on a different connection the + * unacknowledgemap is empty and a 'message is null' log message + * produced. + * + * Test Strategy: + * + * It should be easy to demonstrate if we can send an IOException to + * AMQProtocolHandler#exceptionCaught and then try sending a message. + * + * The current unknowns here are the type of consumers that are in use. + * If it was an exclusive queue(Durable Subscription) then why did the + * resubscribe not fail. + * + * If it was not exclusive then why did the messages not round robin? + */ +public class MessageDisappearWithIOExceptionTest extends FailoverBaseCase implements ConnectionListener +{ + private CountDownLatch _failoverOccured = new CountDownLatch(1); + AMQConnection _connection; + Session _session; + Queue _queue; + MessageConsumer _consumer; + + public void setUp() throws Exception + { + super.setUp(); + stopBroker(getFailingPort()); + + } + + /** + * Test Summary: + * + * Create a queue consumer and send 10 messages to the broker. + * + * Consume the first message. + * This will pull the rest into the prefetch + * + * Send an IOException to the MinaProtocolHandler. + * + * This will force failover to occur. + * + * 9 messages would normally be expected but it is expected that none will + * arrive. As they are still in the prefetch of the first session. + * + * To free the messages we need to close all connections. + * - Simply doing connection.close() and retesting will not be enough as + * the original connection's IO layer will still exist and is nolonger + * connected to the connection object as a result of failover. + * + * - Test will need to retain a reference to the original connection IO so + * that it can be closed releasing the messages to validate that the + * messages have indeed been 'lost' on that sesssion. + */ + public void test() throws Exception + { + initialiseConnection(); + + // Create Producer + // Send 10 messages + List messages = sendNumberedBytesMessage(_session, _queue, 10); + + // Consume first messasge + Message received = _consumer.receive(2000); + + // Verify received messages + assertNotNull("First message not received.", received); + assertEquals("Incorrect message Received", + messages.remove(0).getIntProperty("count"), + received.getIntProperty("count")); + + // Allow ack to be sent to broker, by performing a synchronous command + // along the session. +// _session.createConsumer(_session.createTemporaryQueue()).close(); + + //Retain IO Layer + AMQProtocolSession protocolSession = _connection.getProtocolHandler().getProtocolSession(); + + // Send IO Exception - causing failover + _connection.getProtocolHandler(). + exception(new WriteTimeoutException("WriteTimeoutException to cause failover.")); + + // Verify Failover occured through ConnectionListener + assertTrue("Failover did not occur", + _failoverOccured.await(4000, TimeUnit.MILLISECONDS)); + + //Verify new protocolSession is not the same as the original + assertNotSame("Protocol Session has not changed", + protocolSession, + _connection.getProtocolHandler().getProtocolSession()); + + /***********************************/ + // This verifies that the bug has been resolved + + // Attempt to consume again. Expect 9 messages + for (int count = 1; count < 10; count++) + { + received = _consumer.receive(2000); + assertNotNull("Expected message not received:" + count, received); + assertEquals(messages.remove(0).getIntProperty("count"), + received.getIntProperty("count")); + } + + //Verify there are no more messages + received = _consumer.receive(1000); + assertNull("Message receieved when there should be none:" + received, + received); + +// /***********************************/ +// // This verifies that the bug exists +// +// // Attempt to consume remaining 9 messages.. Expecting NONE. +// // receiving just one message should fail so no need to fail 9 times +// received = _consumer.receive(1000); +// assertNull("Message receieved when it should be null:" + received, received); +// +//// //Close the Connection which you would assume would free the messages +//// _connection.close(); +//// +//// // Reconnect +//// initialiseConnection(); +//// +//// // We should still be unable to receive messages +//// received = _consumer.receive(1000); +//// assertNull("Message receieved when it should be null:" + received, received); +//// +//// _connection.close(); +// +// // Close original IO layer. Expecting messages to be released +// protocolSession.closeProtocolSession(); +// +// // Reconnect and all should be good. +//// initialiseConnection(); +// +// // Attempt to consume again. Expect 9 messages +// for (int count = 1; count < 10; count++) +// { +// received = _consumer.receive(2000); +// assertNotNull("Expected message not received:" + count, received); +// assertEquals(messages.remove(0).getIntProperty("count"), +// received.getIntProperty("count")); +// } +// +// //Verify there are no more messages +// received = _consumer.receive(1000); +// assertNull("Message receieved when there should be none:" + received, +// received); + } + + private void initialiseConnection() + throws Exception + { + //Create Connection + _connection = (AMQConnection) getConnection(); + _connection.setConnectionListener(this); + + _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + _queue = _session.createQueue(getTestQueueName()); + + // Create Consumer + _consumer = _session.createConsumer(_queue); + + //Start connection + _connection.start(); + } + + /** QpidTestCase back port to this release */ + + // modified from QTC as sendMessage is not testable. + // - should be renamed sendBlankBytesMessage + // - should be renamed sendNumberedBytesMessage + public List sendNumberedBytesMessage(Session session, Destination destination, + int count) throws Exception + { + List messages = new ArrayList(count); + + MessageProducer producer = session.createProducer(destination); + + for (int i = 0; i < count; i++) + { + Message next = session.createMessage(); + + next.setIntProperty("count", i); + + producer.send(next); + + messages.add(next); + } + + producer.close(); + return messages; + } + + public void bytesSent(long count) + { + //To change body of implemented methods use File | Settings | File Templates. + } + + public void bytesReceived(long count) + { + } + + public boolean preFailover(boolean redirect) + { + //Allow failover to occur + return true; + } + + public boolean preResubscribe() + { + //Allow failover to occur + return true; + } + + public void failoverComplete() + { + _failoverOccured.countDown(); + } +} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/BrokerLoggingTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/BrokerLoggingTest.java index 4f50aba61d..b00a71315e 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/BrokerLoggingTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/logging/BrokerLoggingTest.java @@ -160,7 +160,7 @@ public class BrokerLoggingTest extends AbstractTestLogging // Set the broker.ready string to check for the _log4j default that // is still present on standard out. - System.setProperty(BROKER_READY, "Qpid Broker Ready"); + setTestClientSystemProperty(BROKER_READY, "Qpid Broker Ready"); startBroker(); diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/queue/DeepQueueConsumeWithSelector.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/queue/DeepQueueConsumeWithSelector.java index dfb5cde247..83f0f87bc5 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/server/queue/DeepQueueConsumeWithSelector.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/queue/DeepQueueConsumeWithSelector.java @@ -63,7 +63,6 @@ import java.util.concurrent.TimeUnit; */ public class DeepQueueConsumeWithSelector extends QpidTestCase implements MessageListener { - private static final String INDEX = "index"; private static final int MESSAGE_COUNT = 10000; private static final int BATCH_SIZE = MESSAGE_COUNT / 10; @@ -129,9 +128,7 @@ public class DeepQueueConsumeWithSelector extends QpidTestCase implements Messag @Override public Message createNextMessage(Session session, int msgCount) throws JMSException { - Message message = session.createTextMessage("Message :" + msgCount); - - message.setIntProperty(INDEX, msgCount); + Message message = super.createNextMessage(session,msgCount); if ((msgCount % BATCH_SIZE) == 0 ) { diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/queue/ProducerFlowControlTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/queue/ProducerFlowControlTest.java new file mode 100644 index 0000000000..f220760511 --- /dev/null +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/queue/ProducerFlowControlTest.java @@ -0,0 +1,393 @@ +/* +* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +* +*/ +package org.apache.qpid.server.queue; + +import org.apache.log4j.Logger; +import org.apache.qpid.client.AMQSession; +import org.apache.qpid.client.AMQQueue; +import org.apache.qpid.client.AMQDestination; +import org.apache.qpid.test.utils.QpidTestCase; +import org.apache.qpid.AMQException; +import org.apache.qpid.server.logging.AbstractTestLogging; +import org.apache.qpid.framing.AMQShortString; + +import javax.jms.*; +import javax.naming.NamingException; +import java.util.HashMap; +import java.util.Map; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.io.IOException; + +public class ProducerFlowControlTest extends AbstractTestLogging +{ + private static final int TIMEOUT = 1500; + + + private static final Logger _logger = Logger.getLogger(ProducerFlowControlTest.class); + + protected final String QUEUE = "ProducerFlowControl"; + + private static final int MSG_COUNT = 50; + + private Connection producerConnection; + private MessageProducer producer; + private Session producerSession; + private Queue queue; + private Connection consumerConnection; + private Session consumerSession; + + + private MessageConsumer consumer; + private final AtomicInteger _sentMessages = new AtomicInteger(); + + public void setUp() throws Exception + { + super.setUp(); + + _monitor.reset(); + + producerConnection = getConnection(); + producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + producerConnection.start(); + + consumerConnection = getConnection(); + consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + } + + public void tearDown() throws Exception + { + producerConnection.close(); + consumerConnection.close(); + super.tearDown(); + } + + public void testCapacityExceededCausesBlock() + throws JMSException, NamingException, AMQException, InterruptedException + { + final Map arguments = new HashMap(); + arguments.put("x-qpid-capacity",1000); + arguments.put("x-qpid-flow-resume-capacity",800); + ((AMQSession) producerSession).createQueue(new AMQShortString(QUEUE), true, false, false, arguments); + queue = new AMQQueue("amq.direct",QUEUE); + ((AMQSession) producerSession).declareAndBind((AMQDestination)queue); + producer = producerSession.createProducer(queue); + + _sentMessages.set(0); + + + // try to send 5 messages (should block after 4) + sendMessagesAsync(producer, producerSession, 5, 50L); + + Thread.sleep(5000); + + assertEquals("Incorrect number of message sent before blocking", 4, _sentMessages.get()); + + consumer = consumerSession.createConsumer(queue); + consumerConnection.start(); + + + consumer.receive(); + + Thread.sleep(1000); + + assertEquals("Message incorrectly sent after one message received", 4, _sentMessages.get()); + + + consumer.receive(); + + Thread.sleep(1000); + + assertEquals("Message not sent after two messages received", 5, _sentMessages.get()); + + } + + public void testBrokerLogMessages() + throws JMSException, NamingException, AMQException, InterruptedException, IOException + { + final Map arguments = new HashMap(); + arguments.put("x-qpid-capacity",1000); + arguments.put("x-qpid-flow-resume-capacity",800); + ((AMQSession) producerSession).createQueue(new AMQShortString(QUEUE), true, false, false, arguments); + queue = new AMQQueue("amq.direct",QUEUE); + ((AMQSession) producerSession).declareAndBind((AMQDestination)queue); + producer = producerSession.createProducer(queue); + + _sentMessages.set(0); + + + // try to send 5 messages (should block after 4) + sendMessagesAsync(producer, producerSession, 5, 50L); + + Thread.sleep(5000); + List results = _monitor.findMatches("QUE-1003"); + + assertEquals("Did not find correct number of QUE-1003 queue overfull messages", 1, results.size()); + + consumer = consumerSession.createConsumer(queue); + consumerConnection.start(); + + + while(consumer.receive(1000) != null); + + results = _monitor.findMatches("QUE-1004"); + + assertEquals("Did not find correct number of QUE_1004 queue underfull messages", 1, results.size()); + + + + } + + + public void testClientLogMessages() + throws JMSException, NamingException, AMQException, InterruptedException, IOException + { + setTestClientSystemProperty("qpid.flow_control_wait_failure","3000"); + setTestClientSystemProperty("qpid.flow_control_wait_notify_period","1000"); + + Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + + final Map arguments = new HashMap(); + arguments.put("x-qpid-capacity",1000); + arguments.put("x-qpid-flow-resume-capacity",800); + ((AMQSession) session).createQueue(new AMQShortString(QUEUE), true, false, false, arguments); + queue = new AMQQueue("amq.direct",QUEUE); + ((AMQSession) session).declareAndBind((AMQDestination)queue); + producer = session.createProducer(queue); + + _sentMessages.set(0); + + + // try to send 5 messages (should block after 4) + MessageSender sender = sendMessagesAsync(producer, producerSession, 5, 50L); + + Thread.sleep(10000); + List results = _monitor.findMatches("Message send delayed by"); + assertEquals("Incorrect number of delay messages logged by client",3,results.size()); + results = _monitor.findMatches("Message send failed due to timeout waiting on broker enforced flow control"); + assertEquals("Incorrect number of send failure messages logged by client",1,results.size()); + + + + } + + + public void testFlowControlOnCapacityResumeEqual() + throws JMSException, NamingException, AMQException, InterruptedException + { + final Map arguments = new HashMap(); + arguments.put("x-qpid-capacity",1000); + arguments.put("x-qpid-flow-resume-capacity",1000); + ((AMQSession) producerSession).createQueue(new AMQShortString(QUEUE), true, false, false, arguments); + queue = new AMQQueue("amq.direct",QUEUE); + ((AMQSession) producerSession).declareAndBind((AMQDestination)queue); + producer = producerSession.createProducer(queue); + + _sentMessages.set(0); + + // try to send 5 messages (should block after 4) + sendMessagesAsync(producer, producerSession, 5, 50L); + + Thread.sleep(5000); + + assertEquals("Incorrect number of message sent before blocking", 4, _sentMessages.get()); + + consumer = consumerSession.createConsumer(queue); + consumerConnection.start(); + + + consumer.receive(); + + Thread.sleep(1000); + + assertEquals("Message incorrectly sent after one message received", 5, _sentMessages.get()); + + + } + + + public void testFlowControlSoak() + throws Exception, NamingException, AMQException, InterruptedException + { + _sentMessages.set(0); + final int numProducers = 10; + final int numMessages = 100; + + final Map arguments = new HashMap(); + arguments.put("x-qpid-capacity",6000); + arguments.put("x-qpid-flow-resume-capacity",3000); + + ((AMQSession) consumerSession).createQueue(new AMQShortString(QUEUE), false, false, false, arguments); + + queue = new AMQQueue("amq.direct",QUEUE); + ((AMQSession) consumerSession).declareAndBind((AMQDestination)queue); + consumerConnection.start(); + + Connection[] producers = new Connection[numProducers]; + for(int i = 0 ; i < numProducers; i ++) + { + + producers[i] = getConnection(); + producers[i].start(); + Session session = producers[i].createSession(false, Session.AUTO_ACKNOWLEDGE); + + MessageProducer myproducer = session.createProducer(queue); + MessageSender sender = sendMessagesAsync(myproducer, session, numMessages, 50L); + } + + consumer = consumerSession.createConsumer(queue); + consumerConnection.start(); + + for(int j = 0; j < numProducers * numMessages; j++) + { + + Message msg = consumer.receive(5000); + Thread.sleep(50L); + assertNotNull("Message not received("+j+"), sent: "+_sentMessages.get(), msg); + + } + + + + Message msg = consumer.receive(500); + assertNull("extra message received", msg); + + + for(int i = 0; i < numProducers; i++) + { + producers[i].close(); + } + + } + + + + public void testSendTimeout() + throws JMSException, NamingException, AMQException, InterruptedException + { + setTestClientSystemProperty("qpid.flow_control_wait_failure","3000"); + Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + + final Map arguments = new HashMap(); + arguments.put("x-qpid-capacity",1000); + arguments.put("x-qpid-flow-resume-capacity",800); + ((AMQSession) session).createQueue(new AMQShortString(QUEUE), true, false, false, arguments); + queue = new AMQQueue("amq.direct",QUEUE); + ((AMQSession) session).declareAndBind((AMQDestination)queue); + producer = session.createProducer(queue); + + _sentMessages.set(0); + + + // try to send 5 messages (should block after 4) + MessageSender sender = sendMessagesAsync(producer, producerSession, 5, 50L); + + Thread.sleep(10000); + + Exception e = sender.getException(); + + assertNotNull("No timeout exception on sending", e); + + } + + private MessageSender sendMessagesAsync(final MessageProducer producer, + final Session producerSession, + final int numMessages, + long sleepPeriod) + { + MessageSender sender = new MessageSender(producer, producerSession, numMessages,sleepPeriod); + new Thread(sender).start(); + return sender; + } + + private void sendMessages(MessageProducer producer, Session producerSession, int numMessages, long sleepPeriod) + throws JMSException + { + + for (int msg = 0; msg < numMessages; msg++) + { + producer.send(nextMessage(msg, producerSession)); + _sentMessages.incrementAndGet(); + + try + { + Thread.sleep(sleepPeriod); + } + catch (InterruptedException e) + { + } + } + } + + private static final byte[] BYTE_300 = new byte[300]; + + + private Message nextMessage(int msg, Session producerSession) throws JMSException + { + BytesMessage send = producerSession.createBytesMessage(); + send.writeBytes(BYTE_300); + send.setIntProperty("msg", msg); + + return send; + } + + + private class MessageSender implements Runnable + { + private final MessageProducer _producer; + private final Session _producerSession; + private final int _numMessages; + + + + private JMSException _exception; + private long _sleepPeriod; + + public MessageSender(MessageProducer producer, Session producerSession, int numMessages, long sleepPeriod) + { + _producer = producer; + _producerSession = producerSession; + _numMessages = numMessages; + _sleepPeriod = sleepPeriod; + } + + public void run() + { + try + { + sendMessages(_producer, _producerSession, _numMessages, _sleepPeriod); + } + catch (JMSException e) + { + _exception = e; + } + } + + public JMSException getException() + { + return _exception; + } + } +} \ No newline at end of file diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java index bb7b5efc75..3e5470d5cb 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java @@ -21,27 +21,34 @@ package org.apache.qpid.server.security.acl; - -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; -import org.apache.log4j.Logger; -import org.apache.qpid.client.transport.TransportConnection; -import org.apache.qpid.client.*; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry; -import org.apache.qpid.AMQConnectionFailureException; +import org.apache.commons.configuration.ConfigurationException; import org.apache.qpid.AMQException; -import org.apache.qpid.test.utils.QpidTestCase; +import org.apache.qpid.AMQConnectionFailureException; +import org.apache.qpid.client.AMQAuthenticationException; +import org.apache.qpid.client.AMQConnection; +import org.apache.qpid.client.AMQSession; +import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.jms.ConnectionListener; +import org.apache.qpid.test.utils.QpidTestCase; import org.apache.qpid.url.URLSyntaxException; +import org.apache.qpid.server.registry.ApplicationRegistry; +import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry; + -import javax.jms.*; +import javax.jms.Connection; +import javax.jms.DeliveryMode; +import javax.jms.ExceptionListener; import javax.jms.IllegalStateException; +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 javax.jms.TextMessage; import javax.naming.NamingException; - import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -53,6 +60,14 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E private CountDownLatch _awaitError = new CountDownLatch(51); public void setUp() throws Exception + { + //Performing setUp here would result in a broker with the default ACL test config + + //Each test now calls the private setUpACLTest to allow them to make + //individual customisations to the base ACL settings + } + + private void setUpACLTest() throws Exception { final String QPID_HOME = System.getProperty("QPID_HOME"); @@ -73,8 +88,10 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E return "amqp://" + username + ":" + password + "@clientid/test?brokerlist='" + getBroker() + "?retries='0''"; } - public void testAccessAuthorized() throws AMQException, URLSyntaxException + public void testAccessAuthorized() throws AMQException, URLSyntaxException, Exception { + setUpACLTest(); + try { Connection conn = getConnection("client", "guest"); @@ -96,6 +113,8 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E public void testAccessNoRights() throws Exception { + setUpACLTest(); + try { Connection conn = getConnection("guest", "guest"); @@ -120,8 +139,40 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } } - public void testClientConsumeFromTempQueueValid() throws AMQException, URLSyntaxException + public void testGuestConsumeWithCreateRightsAndWithoutConsumeRights() throws NamingException, ConfigurationException, IOException, Exception + { + //Customise the ACL config to give the guest user some create (could be any, non-consume) rights to + //force creation of a PrincipalPermissions instance to perform the consume rights check against. + setConfigurationProperty("virtualhosts.virtualhost.test.security.access_control_list.create.queues.queue.users.user", "guest"); + + setUpACLTest(); + + try + { + Connection conn = getConnection("guest", "guest"); + + Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + + conn.start(); + + sesh.createConsumer(sesh.createQueue("example.RequestQueue")); + + conn.close(); + } + catch (JMSException e) + { + Throwable cause = e.getLinkedException(); + + assertNotNull("There was no liked exception", cause); + assertEquals("Wrong linked exception type", AMQAuthenticationException.class, cause.getClass()); + assertEquals("Incorrect error code received", 403, ((AMQAuthenticationException) cause).getErrorCode().getCode()); + } + } + + public void testClientConsumeFromTempQueueValid() throws AMQException, URLSyntaxException, Exception { + setUpACLTest(); + try { Connection conn = getConnection("client", "guest"); @@ -142,6 +193,8 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E public void testClientConsumeFromNamedQueueInvalid() throws NamingException, Exception { + setUpACLTest(); + try { Connection conn = getConnection("client", "guest"); @@ -167,8 +220,10 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } } - public void testClientCreateTemporaryQueue() throws JMSException, URLSyntaxException + public void testClientCreateTemporaryQueue() throws JMSException, URLSyntaxException, Exception { + setUpACLTest(); + try { Connection conn = getConnection("client", "guest"); @@ -191,6 +246,8 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E public void testClientCreateNamedQueue() throws NamingException, JMSException, AMQException, Exception { + setUpACLTest(); + try { Connection conn = getConnection("client", "guest"); @@ -212,8 +269,10 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } } - public void testClientPublishUsingTransactionSuccess() throws AMQException, URLSyntaxException + public void testClientPublishUsingTransactionSuccess() throws AMQException, URLSyntaxException, Exception { + setUpACLTest(); + try { Connection conn = getConnection("client", "guest"); @@ -239,8 +298,10 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E } } - public void testClientPublishValidQueueSuccess() throws AMQException, URLSyntaxException + public void testClientPublishValidQueueSuccess() throws AMQException, URLSyntaxException, Exception { + setUpACLTest(); + try { Connection conn = getConnection("client", "guest"); @@ -271,6 +332,8 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E public void testClientPublishInvalidQueueSuccess() throws AMQException, URLSyntaxException, JMSException, NamingException, Exception { + setUpACLTest(); + try { Connection conn = getConnection("client", "guest"); @@ -311,8 +374,10 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E assertTrue("Did not get AMQAuthenticationException thrown", foundCorrectException); } - public void testServerConsumeFromNamedQueueValid() throws AMQException, URLSyntaxException + public void testServerConsumeFromNamedQueueValid() throws AMQException, URLSyntaxException, Exception { + setUpACLTest(); + try { Connection conn = getConnection("server", "guest"); @@ -333,6 +398,8 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E public void testServerConsumeFromNamedQueueInvalid() throws AMQException, URLSyntaxException, NamingException, Exception { + setUpACLTest(); + try { Connection conn = getConnection("client", "guest"); @@ -358,6 +425,8 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E public void testServerConsumeFromTemporaryQueue() throws AMQException, URLSyntaxException, NamingException, Exception { + setUpACLTest(); + try { Connection conn = getConnection("server", "guest"); @@ -391,8 +460,10 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E return (Connection) connection; } - public void testServerCreateNamedQueueValid() throws JMSException, URLSyntaxException + public void testServerCreateNamedQueueValid() throws JMSException, URLSyntaxException, Exception { + setUpACLTest(); + try { Connection conn = getConnection("server", "guest"); @@ -414,6 +485,8 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E public void testServerCreateNamedQueueInvalid() throws JMSException, URLSyntaxException, AMQException, NamingException, Exception { + setUpACLTest(); + try { Connection conn = getConnection("server", "guest"); @@ -436,6 +509,8 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E public void testServerCreateTemporaryQueueInvalid() throws NamingException, Exception { + setUpACLTest(); + try { Connection conn = getConnection("server", "guest"); @@ -461,6 +536,8 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E public void testServerCreateAutoDeleteQueueInvalid() throws NamingException, JMSException, AMQException, Exception { + setUpACLTest(); + Connection connection = null; try { @@ -492,6 +569,8 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E */ public void testServerPublishUsingTransactionSuccess() throws AMQException, URLSyntaxException, JMSException, NamingException, Exception { + setUpACLTest(); + //Set up the Server Connection serverConnection = getConnection("server", "guest"); @@ -572,6 +651,8 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E public void testServerPublishInvalidQueueSuccess() throws AMQException, URLSyntaxException, JMSException, NamingException, Exception { + setUpACLTest(); + try { Connection conn = getConnection("server", "guest"); diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserAutoAckTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserAutoAckTest.java index 62b54d3086..f9cf48a2b1 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserAutoAckTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/client/QueueBrowserAutoAckTest.java @@ -61,7 +61,7 @@ public class QueueBrowserAutoAckTest extends FailoverBaseCase setupSession(); - _queue = _clientSession.createQueue(getName()+System.currentTimeMillis()); + _queue = _clientSession.createQueue(getTestQueueName()); _clientSession.createConsumer(_queue).close(); //Ensure there are no messages on the queue to start with. @@ -497,7 +497,7 @@ public class QueueBrowserAutoAckTest extends FailoverBaseCase if (msgCount == failPoint) { - failBroker(); + failBroker(getFailingPort()); } } @@ -529,7 +529,7 @@ public class QueueBrowserAutoAckTest extends FailoverBaseCase sendMessages("connection2", messages); } - failBroker(); + failBroker(getFailingPort()); checkQueueDepth(messages); diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/client/RollbackOrderTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/client/RollbackOrderTest.java index 39e2b892a9..ff766c907d 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/client/RollbackOrderTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/client/RollbackOrderTest.java @@ -22,64 +22,172 @@ package org.apache.qpid.test.client; import org.apache.qpid.test.utils.*; import javax.jms.*; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; +import junit.framework.ComparisonFailure; +import junit.framework.AssertionFailedError; /** - * RollbackOrderTest + * RollbackOrderTest, QPID-1864, QPID-1871 + * + * Description: + * + * The problem that this test is exposing is that the dispatcher used to be capable + * of holding on to a message when stopped. This ment that when the rollback was + * called and the dispatcher stopped it may have hold of a message. So after all + * the local queues(preDeliveryQueue, SynchronousQueue, PostDeliveryTagQueue) + * have been cleared the client still had a single message, the one the + * dispatcher was holding on to. + * + * As a result the TxRollback operation would run and then release the dispatcher. + * Whilst the dispatcher would then proceed to reject the message it was holiding + * the Broker would already have resent that message so the rejection would silently + * fail. + * + * And the client would receieve that single message 'early', depending on the + * number of messages already recevied when rollback was called. + * + * + * Aims: + * + * The tests puts 50 messages on to the queue. + * + * The test then tries to cause the dispatcher to stop whilst it is in the process + * of moving a message from the preDeliveryQueue to a consumers sychronousQueue. + * + * To exercise this path we have 50 message flowing to the client to give the + * dispatcher a bit of work to do moving messages. + * + * Then we loop - 10 times + * - Validating that the first message received is always message 1. + * - Receive a few more so that there are a few messages to reject. + * - call rollback, to try and catch the dispatcher mid process. + * + * Outcome: + * + * The hope is that we catch the dispatcher mid process and cause a BasicReject + * to fail. Which will be indicated in the log but will also cause that failed + * rejected message to be the next to be delivered which will not be message 1 + * as expected. + * + * We are testing a race condition here but we can check through the log file if + * the race condition occured. However, performing that check will only validate + * the problem exists and will not be suitable as part of a system test. * */ - public class RollbackOrderTest extends QpidTestCase { - private Connection conn; - private Queue queue; - private Session ssn; - private MessageProducer prod; - private MessageConsumer cons; + private Connection _connection; + private Queue _queue; + private Session _session; + private MessageConsumer _consumer; @Override public void setUp() throws Exception { super.setUp(); - conn = getConnection(); - conn.start(); - ssn = conn.createSession(true, Session.AUTO_ACKNOWLEDGE); - queue = ssn.createQueue("rollback-order-test-queue"); - prod = ssn.createProducer(queue); - cons = ssn.createConsumer(queue); - for (int i = 0; i < 5; i++) - { - TextMessage msg = ssn.createTextMessage("message " + (i+1)); - prod.send(msg); - } - ssn.commit(); + _connection = getConnection(); + + _session = _connection.createSession(true, Session.SESSION_TRANSACTED); + _queue = _session.createQueue(getTestQueueName()); + _consumer = _session.createConsumer(_queue); + + //Send more messages so it is more likely that the dispatcher is + // processing on rollback. + sendMessage(_session, _queue, 50); + _session.commit(); + } public void testOrderingAfterRollback() throws Exception { - for (int i = 0; i < 10; i++) + //Start the session now so we + _connection.start(); + + for (int i = 0; i < 20; i++) { - TextMessage msg = (TextMessage) cons.receive(); - assertEquals("message 1", msg.getText()); - ssn.rollback(); + Message msg = _consumer.receive(); + assertEquals("Incorrect Message Received", 0, msg.getIntProperty(INDEX)); + + // Pull additional messages through so we have some reject work to do + for (int m=0; m < 5 ; m++) + { + _consumer.receive(); + } + + System.err.println("ROT-Rollback"); + _logger.warn("ROT-Rollback"); + _session.rollback(); } } - @Override public void tearDown() throws Exception + public void testOrderingAfterRollbackOnMessage() throws Exception { - while (true) + final CountDownLatch count= new CountDownLatch(20); + final Exception exceptions[] = new Exception[20]; + final AtomicBoolean failed = new AtomicBoolean(false); + + _consumer.setMessageListener(new MessageListener() { - Message msg = cons.receiveNoWait(); - if (msg == null) + + public void onMessage(Message message) { - break; + + Message msg = message; + try + { + count.countDown(); + assertEquals("Incorrect Message Received", 0, msg.getIntProperty(INDEX)); + + _session.rollback(); + } + catch (JMSException e) + { + System.out.println("Error:" + e.getMessage()); + exceptions[(int)count.getCount()] = e; + } + catch (AssertionFailedError cf) + { + // End Test if Equality test fails + while (count.getCount() != 0) + { + count.countDown(); + } + + System.out.println("Error:" + cf.getMessage()); + System.err.println(cf.getMessage()); + cf.printStackTrace(); + failed.set(true); + } } - else + }); + //Start the session now so we + _connection.start(); + + count.await(); + + for (Exception e : exceptions) + { + if (e != null) { - msg.acknowledge(); + System.err.println(e.getMessage()); + e.printStackTrace(); + failed.set(true); } } - ssn.commit(); + +// _consumer.close(); + _connection.close(); + + assertFalse("Exceptions thrown during test run, Check Std.err.", failed.get()); + } + + @Override public void tearDown() throws Exception + { + + drainQueue(_queue); + super.tearDown(); } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/client/failover/FailoverTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/client/failover/FailoverTest.java index dfc3bb7b42..c307176f3f 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/client/failover/FailoverTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/client/failover/FailoverTest.java @@ -37,7 +37,6 @@ import javax.naming.NamingException; import org.apache.log4j.Logger; import org.apache.qpid.client.AMQConnection; -import org.apache.qpid.client.AMQSession_0_10; import org.apache.qpid.jms.BrokerDetails; import org.apache.qpid.jms.ConnectionListener; import org.apache.qpid.jms.ConnectionURL; @@ -58,13 +57,12 @@ public class FailoverTest extends FailoverBaseCase implements ConnectionListener private Session consumerSession; private MessageConsumer consumer; - private static int usedBrokers = 0; private CountDownLatch failoverComplete; - private static final long DEFAULT_FAILOVER_TIME = 10000L; private boolean CLUSTERED = Boolean.getBoolean("profile.clustered"); private int seed; private Random rand; - + private int _currentPort = getFailingPort(); + @Override protected void setUp() throws Exception { @@ -227,7 +225,7 @@ public class FailoverTest extends FailoverBaseCase implements ConnectionListener _logger.info("Failing over"); - causeFailure(DEFAULT_FAILOVER_TIME); + causeFailure(_currentPort, DEFAULT_FAILOVER_TIME); // Check that you produce and consume the rest of messages. _logger.debug("=================="); @@ -242,10 +240,10 @@ public class FailoverTest extends FailoverBaseCase implements ConnectionListener _logger.debug("=================="); } - private void causeFailure(long delay) + private void causeFailure(int port, long delay) { - failBroker(); + failBroker(port); _logger.info("Awaiting Failover completion"); try @@ -268,7 +266,7 @@ public class FailoverTest extends FailoverBaseCase implements ConnectionListener Message msg = consumer.receive(); assertNotNull("Expected msgs not received", msg); - causeFailure(DEFAULT_FAILOVER_TIME); + causeFailure(getFailingPort(), DEFAULT_FAILOVER_TIME); Exception failure = null; try @@ -314,7 +312,7 @@ public class FailoverTest extends FailoverBaseCase implements ConnectionListener long failTime = System.nanoTime() + FAILOVER_DELAY * 1000000; //Fail the first broker - causeFailure(FAILOVER_DELAY + DEFAULT_FAILOVER_TIME); + causeFailure(getFailingPort(), FAILOVER_DELAY + DEFAULT_FAILOVER_TIME); //Reconnection should occur assertTrue("Failover did not take long enough", System.nanoTime() > failTime); @@ -344,15 +342,15 @@ public class FailoverTest extends FailoverBaseCase implements ConnectionListener _logger.debug("==================================================================="); runP2PFailover(numMessages, false,false, false); - startBroker(getFailingPort()); + startBroker(_currentPort); if (useAltPort) { - setFailingPort(altPort); + _currentPort = altPort; useAltPort = false; } else { - setFailingPort(stdPort); + _currentPort = stdPort; useAltPort = true; } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/client/message/SelectorTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/client/message/SelectorTest.java index 5a5e23baa5..a09589b121 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/client/message/SelectorTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/client/message/SelectorTest.java @@ -1,31 +1,248 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ package org.apache.qpid.test.client.message; -import javax.jms.Connection; -import javax.jms.Destination; +import java.util.concurrent.CountDownLatch; + +import javax.jms.DeliveryMode; +import javax.jms.InvalidSelectorException; +import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; +import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Session; import junit.framework.Assert; -import org.apache.log4j.Logger; +import org.apache.qpid.AMQException; +import org.apache.qpid.client.AMQConnection; +import org.apache.qpid.client.AMQDestination; +import org.apache.qpid.client.AMQQueue; +import org.apache.qpid.client.AMQSession; +import org.apache.qpid.client.BasicMessageProducer; import org.apache.qpid.test.utils.QpidTestCase; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -public class SelectorTest extends QpidTestCase +public class SelectorTest extends QpidTestCase implements MessageListener { - private static final Logger _logger = Logger.getLogger(SelectorTest.class); + private static final Logger _logger = LoggerFactory.getLogger(SelectorTest.class); - public void testSelectorWithJMSMessageID() throws Exception + private AMQConnection _connection; + private AMQDestination _destination; + private int count; + public String _connectionString = "vm://:1"; + private static final String INVALID_SELECTOR = "Cost LIKE 5"; + CountDownLatch _responseLatch = new CountDownLatch(1); + + private static final String BAD_MATHS_SELECTOR = " 1 % 5"; + + private static final long RECIEVE_TIMEOUT = 1000; + + protected void setUp() throws Exception + { + super.setUp(); + init((AMQConnection) getConnection("guest", "guest")); + } + + private void init(AMQConnection connection) throws JMSException + { + init(connection, new AMQQueue(connection, getTestQueueName(), true)); + } + + private void init(AMQConnection connection, AMQDestination destination) throws JMSException + { + _connection = connection; + _destination = destination; + connection.start(); + } + + public void onMessage(Message message) + { + count++; + _logger.info("Got Message:" + message); + _responseLatch.countDown(); + } + + public void testUsingOnMessage() throws Exception + { + String selector = "Cost = 2 AND \"property-with-hyphen\" = 'wibble'"; + // selector = "JMSType = Special AND Cost = 2 AND AMQMessageID > 0 AND JMSDeliveryMode=" + DeliveryMode.NON_PERSISTENT; + + Session session = (AMQSession) _connection.createSession(false, AMQSession.NO_ACKNOWLEDGE); + // _session.createConsumer(destination).setMessageListener(this); + session.createConsumer(_destination, selector).setMessageListener(this); + + try + { + Message msg = session.createTextMessage("Message"); + msg.setJMSPriority(1); + msg.setIntProperty("Cost", 2); + msg.setStringProperty("property-with-hyphen", "wibble"); + msg.setJMSType("Special"); + + _logger.info("Sending Message:" + msg); + + ((BasicMessageProducer) session.createProducer(_destination)).send(msg, DeliveryMode.NON_PERSISTENT); + _logger.info("Message sent, waiting for response..."); + + _responseLatch.await(); + + if (count > 0) + { + _logger.info("Got message"); + } + + if (count == 0) + { + fail("Did not get message!"); + // throw new RuntimeException("Did not get message!"); + } + } + catch (JMSException e) + { + _logger.debug("JMS:" + e.getClass().getSimpleName() + ":" + e.getMessage()); + if (!(e instanceof InvalidSelectorException)) + { + fail("Wrong exception:" + e.getMessage()); + } + else + { + System.out.println("SUCCESS!!"); + } + } + catch (InterruptedException e) + { + _logger.debug("IE :" + e.getClass().getSimpleName() + ":" + e.getMessage()); + } + + } + + public void testUnparsableSelectors() throws Exception { - Connection conn = getConnection(); - conn.start(); - Session session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE); + AMQSession session = (AMQSession) _connection.createSession(false, AMQSession.NO_ACKNOWLEDGE); + boolean caught = false; - Destination dest = session.createQueue("SelectorQueue"); + //Try Creating a Browser + try + { + session.createBrowser(session.createQueue("Ping"), INVALID_SELECTOR); + } + catch (JMSException e) + { + _logger.debug("JMS:" + e.getClass().getSimpleName() + ":" + e.getMessage()); + if (!(e instanceof InvalidSelectorException)) + { + fail("Wrong exception:" + e.getMessage()); + } + caught = true; + } + assertTrue("No exception thrown!", caught); + caught = false; + + //Try Creating a Consumer + try + { + session.createConsumer(session.createQueue("Ping"), INVALID_SELECTOR); + } + catch (JMSException e) + { + _logger.debug("JMS:" + e.getClass().getSimpleName() + ":" + e.getMessage()); + if (!(e instanceof InvalidSelectorException)) + { + fail("Wrong exception:" + e.getMessage()); + } + caught = true; + } + assertTrue("No exception thrown!", caught); + caught = false; + + //Try Creating a Receiever + try + { + session.createReceiver(session.createQueue("Ping"), INVALID_SELECTOR); + } + catch (JMSException e) + { + _logger.debug("JMS:" + e.getClass().getSimpleName() + ":" + e.getMessage()); + if (!(e instanceof InvalidSelectorException)) + { + fail("Wrong exception:" + e.getMessage()); + } + caught = true; + } + assertTrue("No exception thrown!", caught); + caught = false; + + try + { + session.createReceiver(session.createQueue("Ping"), BAD_MATHS_SELECTOR); + } + catch (JMSException e) + { + _logger.debug("JMS:" + e.getClass().getSimpleName() + ":" + e.getMessage()); + if (!(e instanceof InvalidSelectorException)) + { + fail("Wrong exception:" + e.getMessage()); + } + caught = true; + } + assertTrue("No exception thrown!", caught); + caught = false; - MessageProducer prod = session.createProducer(dest); - MessageConsumer consumer = session.createConsumer(dest,"JMSMessageID IS NOT NULL"); + } + + public void testRuntimeSelectorError() throws JMSException + { + Session session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer consumer = session.createConsumer(_destination , "testproperty % 5 = 1"); + MessageProducer producer = session.createProducer(_destination); + Message sentMsg = session.createTextMessage(); + + sentMsg.setIntProperty("testproperty", 1); // 1 % 5 + producer.send(sentMsg); + Message recvd = consumer.receive(RECIEVE_TIMEOUT); + assertNotNull(recvd); + + sentMsg.setStringProperty("testproperty", "hello"); // "hello" % 5 makes no sense + producer.send(sentMsg); + try + { + recvd = consumer.receive(RECIEVE_TIMEOUT); + assertNull(recvd); + } + catch (Exception e) + { + + } + assertTrue("Connection should be closed", _connection.isClosed()); + } + + public void testSelectorWithJMSMessageID() throws Exception + { + Session session = _connection.createSession(true, Session.SESSION_TRANSACTED); + + MessageProducer prod = session.createProducer(_destination); + MessageConsumer consumer = session.createConsumer(_destination,"JMSMessageID IS NOT NULL"); for (int i=0; i<2; i++) { @@ -54,7 +271,7 @@ public class SelectorTest extends QpidTestCase Message msg3 = consumer.receive(1000); Assert.assertNull("Msg3 should be null", msg3); session.commit(); - consumer = session.createConsumer(dest,"JMSMessageID IS NULL"); + consumer = session.createConsumer(_destination,"JMSMessageID IS NULL"); Message msg4 = consumer.receive(1000); Message msg5 = consumer.receive(1000); @@ -62,4 +279,32 @@ public class SelectorTest extends QpidTestCase Assert.assertNotNull("Msg4 should not be null", msg4); Assert.assertNotNull("Msg5 should not be null", msg5); } + + public static void main(String[] argv) throws Exception + { + SelectorTest test = new SelectorTest(); + test._connectionString = (argv.length == 0) ? "localhost:3000" : argv[0]; + + try + { + while (true) + { + if (test._connectionString.contains("vm://:1")) + { + test.setUp(); + } + test.testUsingOnMessage(); + + if (test._connectionString.contains("vm://:1")) + { + test.tearDown(); + } + } + } + catch (Exception e) + { + System.err.println(e.getMessage()); + e.printStackTrace(); + } + } } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/Acknowledge2ConsumersTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/Acknowledge2ConsumersTest.java new file mode 100644 index 0000000000..4b45a96c20 --- /dev/null +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/Acknowledge2ConsumersTest.java @@ -0,0 +1,193 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.qpid.test.unit.ack; + +import org.apache.qpid.client.AMQDestination; +import org.apache.qpid.client.AMQSession; +import org.apache.qpid.test.utils.FailoverBaseCase; + +import javax.jms.Connection; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.Queue; +import javax.jms.Session; + +public class Acknowledge2ConsumersTest extends FailoverBaseCase +{ + protected static int NUM_MESSAGES = 100; + protected Connection _con; + protected Queue _queue; + private Session _producerSession; + private Session _consumerSession; + private MessageConsumer _consumerA; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + + _queue = (Queue) getInitialContext().lookup("queue"); + + //Create Producer put some messages on the queue + _con = getConnection(); + } + + private void init(boolean transacted, int mode) throws JMSException + { + _producerSession = _con.createSession(true, Session.SESSION_TRANSACTED); + _consumerSession = _con.createSession(transacted, mode); + _consumerA = _consumerSession.createConsumer(_queue); + _con.start(); + } + + /** + * Produces Messages that + * + * @param transacted + * @param mode + * + * @throws Exception + */ + private void test2ConsumersAcking(boolean transacted, int mode) throws Exception + { + init(transacted, mode); + + // These should all end up being prefetched by sessionA + sendMessage(_producerSession, _queue, NUM_MESSAGES / 2); + + //Create a second consumer (consumerB) to consume some of the messages + MessageConsumer consumerB = _consumerSession.createConsumer(_queue); + + // These messages should be roundrobined between A and B + sendMessage(_producerSession, _queue, NUM_MESSAGES / 2); + + int count = 0; + //Use consumerB to receive messages it has + Message msg = consumerB.receive(1500); + while (msg != null) + { + if (mode == Session.CLIENT_ACKNOWLEDGE) + { + msg.acknowledge(); + } + count++; + msg = consumerB.receive(1500); + } + if (transacted) + { + _consumerSession.commit(); + } + + // Close the consumers + _consumerA.close(); + consumerB.close(); + + // and close the session to release any prefetched messages. + _consumerSession.close(); + assertEquals("Wrong number of messages on queue", NUM_MESSAGES - count, + ((AMQSession) _producerSession).getQueueDepth((AMQDestination) _queue)); + + // Clean up messages that may be left on the queue + _consumerSession = _con.createSession(transacted, mode); + _consumerA = _consumerSession.createConsumer(_queue); + msg = _consumerA.receive(1500); + while (msg != null) + { + if (mode == Session.CLIENT_ACKNOWLEDGE) + { + msg.acknowledge(); + } + msg = _consumerA.receive(1500); + } + _consumerA.close(); + if (transacted) + { + _consumerSession.commit(); + } + _consumerSession.close(); + } + + public void test2ConsumersAutoAck() throws Exception + { + test2ConsumersAcking(false, Session.AUTO_ACKNOWLEDGE); + } + + public void test2ConsumersClientAck() throws Exception + { + test2ConsumersAcking(false, Session.CLIENT_ACKNOWLEDGE); + } + + public void test2ConsumersTx() throws Exception + { + test2ConsumersAcking(true, Session.SESSION_TRANSACTED); + } + + + +// +// /** +// * Check that session level acknowledge does correctly ack all previous +// * values. Send 3 messages(0,1,2) then ack 1 and 2. If session ack is +// * working correctly then acking 1 will also ack 0. Acking 2 will not +// * attempt to re-ack 0 and 1. +// * +// * @throws Exception +// */ +// public void testSessionAck() throws Exception +// { +// init(false, Session.CLIENT_ACKNOWLEDGE); +// +// sendMessage(_producerSession, _queue, 3); +// Message msg; +// +// // Drop msg 0 +// _consumerA.receive(RECEIVE_TIMEOUT); +// +// // Take msg 1 +// msg = _consumerA.receive(RECEIVE_TIMEOUT); +// +// assertNotNull("Message 1 not correctly received.", msg); +// assertEquals("Incorrect message received", 1, msg.getIntProperty(INDEX)); +// +// // This should also ack msg 0 +// msg.acknowledge(); +// +// // Take msg 2 +// msg = _consumerA.receive(RECEIVE_TIMEOUT); +// +// assertNotNull("Message 2 not correctly received.", msg); +// assertEquals("Incorrect message received", 2, msg.getIntProperty(INDEX)); +// +// // This should just ack msg 2 +// msg.acknowledge(); +// +// _consumerA.close(); +// _consumerSession.close(); +// +// assertEquals("Queue not empty.", 0, +// ((AMQSession) _producerSession).getQueueDepth((AMQDestination) _queue)); +// _con.close(); +// +// +// } +} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverOnMessageTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverOnMessageTest.java new file mode 100644 index 0000000000..f22a405fc3 --- /dev/null +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverOnMessageTest.java @@ -0,0 +1,356 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.test.unit.ack; + +import org.apache.qpid.client.AMQConnection; +import org.apache.qpid.client.AMQDestination; +import org.apache.qpid.client.AMQSession; +import org.apache.qpid.jms.ConnectionListener; + +import javax.jms.Connection; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageListener; +import javax.jms.Session; +import javax.jms.TransactionRolledBackException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +public class AcknowledgeAfterFailoverOnMessageTest extends AcknowledgeOnMessageTest implements ConnectionListener +{ + + protected CountDownLatch _failoverCompleted = new CountDownLatch(1); + private MessageListener _listener = null; + + @Override + public void setUp() throws Exception + { + super.setUp(); + NUM_MESSAGES = 10; + } + + /** + * Override default init to add connectionListener so we can verify that + * failover took place + * + * @param transacted create a transacted session for this test + * @param mode if not transacted what ack mode to use for this test + * + * @throws Exception if a problem occured during test setup. + */ + @Override + public void init(boolean transacted, int mode) throws Exception + { + super.init(transacted, mode); + ((AMQConnection) _connection).setConnectionListener(this); + // Override the listener for the dirtyAck testing. + if (_listener != null) + { + _consumer.setMessageListener(_listener); + } + } + + protected void prepBroker(int count) throws Exception + { + //Stop the connection whilst we repopulate the broker, or the no_ack + // test will drain the msgs before we can check we put the right number + // back on again. +// _connection.stop(); + + Connection connection = getConnection(); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + // ensure destination is created. + session.createConsumer(_queue).close(); + + sendMessage(session, _queue, count, NUM_MESSAGES - count, 0); + + if (_consumerSession.getAcknowledgeMode() != AMQSession.NO_ACKNOWLEDGE) + { + assertEquals("Wrong number of messages on queue", count, + ((AMQSession) session).getQueueDepth((AMQDestination) _queue)); + } + + connection.close(); + +// _connection.start(); + } + + @Override + public void doAcknowlegement(Message msg) throws JMSException + { + //Acknowledge current message + super.doAcknowlegement(msg); + + int msgCount = msg.getIntProperty(INDEX); + + if (msgCount % 2 == 0) + { + failBroker(getFailingPort()); + } + else + { + failBroker(getPort()); + } + + try + { + prepBroker(NUM_MESSAGES - msgCount - 1); + } + catch (Exception e) + { + fail("Unable to prep new broker," + e.getMessage()); + } + + try + { + + if (msgCount % 2 == 0) + { + startBroker(getFailingPort()); + } + else + { + startBroker(getPort()); + } + } + catch (Exception e) + { + fail("Unable to start failover broker," + e.getMessage()); + } + + } + + int msgCount = 0; + boolean cleaned = false; + + class DirtyAckingHandler implements MessageListener + { + /** + * Validate first message but do nothing with it. + * + * Failover + * + * The receive the message again + * + * @param message + */ + public void onMessage(Message message) + { + // Stop processing if we have an error and had to stop running. + if (_receviedAll.getCount() == 0) + { + _logger.debug("Dumping msgs due to error(" + _causeOfFailure.get().getMessage() + "):" + message); + return; + } + + try + { + // Check we have the next message as expected + assertNotNull("Message " + msgCount + " not correctly received.", message); + assertEquals("Incorrect message received", msgCount, message.getIntProperty(INDEX)); + + if (msgCount == 0 && _failoverCompleted.getCount() != 0) + { + // This is the first message we've received so lets fail the broker + + failBroker(getFailingPort()); + + repopulateBroker(); + + _logger.error("Received first msg so failing over"); + + return; + } + + msgCount++; + + // Don't acknowlege the first message after failover so we can commit + // them together + if (msgCount == 1) + { + _logger.error("Received first msg after failover ignoring:" + msgCount); + + // Acknowledge the first message if we are now on the cleaned pass + if (cleaned) + { + _receviedAll.countDown(); + } + + return; + } + + if (_consumerSession.getTransacted()) + { + try + { + _consumerSession.commit(); + if (!cleaned) + { + fail("Session is dirty we should get an TransactionRolledBackException"); + } + } + catch (TransactionRolledBackException trbe) + { + //expected path + } + } + else + { + try + { + message.acknowledge(); + if (!cleaned) + { + fail("Session is dirty we should get an IllegalStateException"); + } + } + catch (javax.jms.IllegalStateException ise) + { + assertEquals("Incorrect Exception thrown", "has failed over", ise.getMessage()); + // Recover the sesion and try again. + _consumerSession.recover(); + } + } + + // Acknowledge the last message if we are in a clean state + // this will then trigger test teardown. + if (cleaned) + { + _receviedAll.countDown(); + } + + //Reset message count so we can try again. + msgCount = 0; + cleaned = true; + } + catch (Exception e) + { + // If something goes wrong stop and notifiy main thread. + fail(e); + } + } + } + + /** + * Test that Acking/Committing a message received before failover causes + * an exception at commit/ack time. + * + * Expected behaviour is that in: + * * tx mode commit() throws a transacted RolledBackException + * * client ack mode throws an IllegalStateException + * + * @param transacted is this session trasacted + * @param mode What ack mode should be used if not trasacted + * + * @throws Exception if something goes wrong. + */ + protected void testDirtyAcking(boolean transacted, int mode) throws Exception + { + NUM_MESSAGES = 2; + _listener = new DirtyAckingHandler(); + + super.testAcking(transacted, mode); + } + + public void testDirtyClientAck() throws Exception + { + testDirtyAcking(false, Session.CLIENT_ACKNOWLEDGE); + } + + public void testDirtyAckingTransacted() throws Exception + { + testDirtyAcking(true, Session.SESSION_TRANSACTED); + } + + private void repopulateBroker() throws Exception + { + // Repopulate this new broker so we can test what happends after failover + + //Get the connection to the first (main port) broker. + Connection connection = getConnection(); + // Use a transaction to send messages so we can be sure they arrive. + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + // ensure destination is created. + session.createConsumer(_queue).close(); + + sendMessage(session, _queue, NUM_MESSAGES); + + assertEquals("Wrong number of messages on queue", NUM_MESSAGES, + ((AMQSession) session).getQueueDepth((AMQDestination) _queue)); + + connection.close(); + } + + // AMQConnectionListener Interface.. used so we can validate that we + // actually failed over. + + public void bytesSent(long count) + { + } + + public void bytesReceived(long count) + { + } + + public boolean preFailover(boolean redirect) + { + //Allow failover + return true; + } + + public boolean preResubscribe() + { + //Allow failover + return true; + } + + public void failoverComplete() + { + _failoverCompleted.countDown(); + } + + /** + * Override so we can block until failover has completd + * + * @param port + */ + @Override + public void failBroker(int port) + { + super.failBroker(port); + + try + { + if (!_failoverCompleted.await(DEFAULT_FAILOVER_TIME, TimeUnit.MILLISECONDS)) + { + // Use an exception so that we use our local fail() that notifies the main thread of failure + throw new Exception("Failover did not occur in specified time:" + DEFAULT_FAILOVER_TIME); + } + + } + catch (Exception e) + { + // Use an exception so that we use our local fail() that notifies the main thread of failure + fail(e); + } + } + +} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverTest.java new file mode 100644 index 0000000000..eb36522fac --- /dev/null +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverTest.java @@ -0,0 +1,306 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.test.unit.ack; + +import org.apache.qpid.client.AMQConnection; +import org.apache.qpid.client.AMQDestination; +import org.apache.qpid.client.AMQSession; +import org.apache.qpid.jms.ConnectionListener; + +import javax.jms.Connection; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.jms.TransactionRolledBackException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * + */ +public class AcknowledgeAfterFailoverTest extends AcknowledgeTest implements ConnectionListener +{ + + protected CountDownLatch _failoverCompleted = new CountDownLatch(1); + + @Override + public void setUp() throws Exception + { + super.setUp(); + // This must be even for the test to run correctly. + // Otherwise we will kill the standby broker + // not the one we are connected to. + // The test will still pass but it will not be exactly + // as described. + NUM_MESSAGES = 6; + } + + /** + * Override default init to add connectionListener so we can verify that + * failover took place + * + * @param transacted create a transacted session for this test + * @param mode if not transacted what ack mode to use for this test + * @throws Exception if a problem occured during test setup. + */ + @Override + protected void init(boolean transacted, int mode) throws Exception + { + super.init(transacted, mode); + ((AMQConnection) _connection).setConnectionListener(this); + } + + protected void prepBroker(int count) throws Exception + { + if (count % 2 == 1) + { + failBroker(getFailingPort()); + } + else + { + failBroker(getPort()); + } + + Connection connection = getConnection(); + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + // ensure destination is created. + session.createConsumer(_queue).close(); + + sendMessage(session, _queue, count, NUM_MESSAGES - count, 0); + + if (_consumerSession.getAcknowledgeMode() != AMQSession.NO_ACKNOWLEDGE) + { + assertEquals("Wrong number of messages on queue", count, + ((AMQSession) session).getQueueDepth((AMQDestination) _queue)); + } + + connection.close(); + + try + { + if (count % 2 == 1) + { + startBroker(getFailingPort()); + } + else + { + startBroker(getPort()); + } + } + catch (Exception e) + { + fail("Unable to start failover broker," + e.getMessage()); + } + } + + @Override + public void doAcknowlegement(Message msg) throws JMSException + { + //Acknowledge current message + super.doAcknowlegement(msg); + + try + { + prepBroker(NUM_MESSAGES - msg.getIntProperty(INDEX) - 1); + } + catch (Exception e) + { + fail("Unable to prep new broker," + e.getMessage()); + } + + } + + /** + * Test that Acking/Committing a message received before failover causes + * an exception at commit/ack time. + * + * Expected behaviour is that in: + * * tx mode commit() throws a transacted RolledBackException + * * client ack mode throws an IllegalStateException + * + * @param transacted is this session trasacted + * @param mode What ack mode should be used if not trasacted + * + * @throws Exception if something goes wrong. + */ + protected void testDirtyAcking(boolean transacted, int mode) throws Exception + { + NUM_MESSAGES = 2; + //Test Dirty Failover Fails + init(transacted, mode); + + _connection.start(); + + Message msg = _consumer.receive(1500); + + int count = 0; + assertNotNull("Message " + count + " not correctly received.", msg); + assertEquals("Incorrect message received", count, msg.getIntProperty(INDEX)); + + //Don't acknowledge just prep the next broker. Without changing count + // Prep the new broker to have all all the messages so we can validate + // that they can all be correctly received. + try + { + + //Stop the connection so we can validate the number of message count + // on the queue is correct after failover + _connection.stop(); + failBroker(getFailingPort()); + + //Get the connection to the first (main port) broker. + Connection connection = getConnection();//getConnectionFactory("connection1").getConnectionURL()); + // Use a transaction to send messages so we can be sure they arrive. + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + // ensure destination is created. + session.createConsumer(_queue).close(); + + sendMessage(session, _queue, NUM_MESSAGES); + + assertEquals("Wrong number of messages on queue", NUM_MESSAGES, + ((AMQSession) session).getQueueDepth((AMQDestination) _queue)); + + connection.close(); + + //restart connection + _connection.start(); + } + catch (Exception e) + { + fail("Unable to prep new broker," + e.getMessage()); + } + + // Consume the next message - don't check what it is as a normal would + // assume it is msg 1 but as we've fallen over it is msg 0 again. + msg = _consumer.receive(1500); + + if (_consumerSession.getTransacted()) + { + try + { + _consumerSession.commit(); + fail("Session is dirty we should get an TransactionRolledBackException"); + } + catch (TransactionRolledBackException trbe) + { + //expected path + } + } + else + { + try + { + msg.acknowledge(); + fail("Session is dirty we should get an IllegalStateException"); + } + catch (javax.jms.IllegalStateException ise) + { + assertEquals("Incorrect Exception thrown", "has failed over", ise.getMessage()); + // Recover the sesion and try again. + _consumerSession.recover(); + } + } + + msg = _consumer.receive(1500); + // Validate we now get the first message back + assertEquals(0, msg.getIntProperty(INDEX)); + + msg = _consumer.receive(1500); + // and the second message + assertEquals(1, msg.getIntProperty(INDEX)); + + // And now verify that we can now commit the clean session + if (_consumerSession.getTransacted()) + { + _consumerSession.commit(); + } + else + { + msg.acknowledge(); + } + + assertEquals("Wrong number of messages on queue", 0, + ((AMQSession) _consumerSession).getQueueDepth((AMQDestination) _queue)); + } + + public void testDirtyClientAck() throws Exception + { + testDirtyAcking(false, Session.CLIENT_ACKNOWLEDGE); + } + + public void testDirtyAckingTransacted() throws Exception + { + testDirtyAcking(true, Session.SESSION_TRANSACTED); + } + + // AMQConnectionListener Interface.. used so we can validate that we + // actually failed over. + + public void bytesSent(long count) + { + } + + public void bytesReceived(long count) + { + } + + public boolean preFailover(boolean redirect) + { + //Allow failover + return true; + } + + public boolean preResubscribe() + { + //Allow failover + return true; + } + + public void failoverComplete() + { + _failoverCompleted.countDown(); + } + + /** + * Override so we can block until failover has completd + * + * @param port + */ + @Override + public void failBroker(int port) + { + super.failBroker(port); + + try + { + if (!_failoverCompleted.await(DEFAULT_FAILOVER_TIME, TimeUnit.MILLISECONDS)) + { + fail("Failover did not occur in specified time:" + DEFAULT_FAILOVER_TIME); + } + } + catch (InterruptedException e) + { + fail("Failover was interuppted"); + } + } + +} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeOnMessageTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeOnMessageTest.java new file mode 100644 index 0000000000..4254727d36 --- /dev/null +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeOnMessageTest.java @@ -0,0 +1,170 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.test.unit.ack; + +import org.apache.qpid.client.AMQDestination; +import org.apache.qpid.client.AMQSession; +import org.apache.qpid.client.JMSAMQException; +import org.apache.qpid.client.failover.FailoverException; + +import javax.jms.Message; +import javax.jms.MessageListener; +import javax.jms.Session; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +public class AcknowledgeOnMessageTest extends AcknowledgeTest implements MessageListener +{ + protected CountDownLatch _receviedAll; + protected AtomicReference _causeOfFailure = new AtomicReference(null); + + @Override + public void setUp() throws Exception + { + super.setUp(); + } + + @Override + public void init(boolean transacted, int mode) throws Exception + { + _receviedAll = new CountDownLatch(NUM_MESSAGES); + + super.init(transacted, mode); + _consumer.setMessageListener(this); + } + + /** + * @param transacted + * @param mode + * + * @throws Exception + */ + protected void testAcking(boolean transacted, int mode) throws Exception + { + init(transacted, mode); + + _connection.start(); + + int lastCount = (int) _receviedAll.getCount(); + + boolean complete = _receviedAll.await(5000L, TimeUnit.MILLISECONDS); + + while (!complete) + { + int currentCount = (int) _receviedAll.getCount(); + + // make sure we have received a message in the last cycle. + if (lastCount == currentCount) + { + break; + } + // Remember the currentCount as the lastCount for the next cycle. + // so we can exit if things get locked up. + lastCount = currentCount; + + complete = _receviedAll.await(5000L, TimeUnit.MILLISECONDS); + } + + if (!complete) + { + // Check to see if we ended due to an exception in the onMessage handler + Exception cause = _causeOfFailure.get(); + if (cause != null) + { + cause.printStackTrace(); + fail(cause.getMessage()); + } + else + { + fail("All messages not received missing:" + _receviedAll.getCount() + "/" + NUM_MESSAGES); + } + } + + // Check to see if we ended due to an exception in the onMessage handler + Exception cause = _causeOfFailure.get(); + if (cause != null) + { + cause.printStackTrace(); + fail(cause.getMessage()); + } + + try + { + _consumer.close(); + } + catch (JMSAMQException amqe) + { + if (amqe.getLinkedException() instanceof FailoverException) + { + fail("QPID-143 : Auto Ack can acknowledge message from previous session after failver. If failover occurs between deliver and ack."); + } + // else Rethrow for TestCase to catch. + throw amqe; + } + + _consumerSession.close(); + + assertEquals("Wrong number of messages on queue", 0, + ((AMQSession) getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE)).getQueueDepth((AMQDestination) _queue)); + } + + public void onMessage(Message message) + { + try + { + int count = NUM_MESSAGES - (int) _receviedAll.getCount(); + + assertEquals("Incorrect message received", count, message.getIntProperty(INDEX)); + + count++; + if (count < NUM_MESSAGES) + { + //Send the next message + _producer.send(createNextMessage(_consumerSession, count)); + } + + doAcknowlegement(message); + + _receviedAll.countDown(); + } + catch (Exception e) + { + // This will end the test run by counting down _receviedAll + fail(e); + } + } + + /** + * Pass the given exception back to the waiting thread to fail the test run. + * + * @param e The exception that is causing the test to fail. + */ + protected void fail(Exception e) + { + _causeOfFailure.set(e); + // End the test. + while (_receviedAll.getCount() != 0) + { + _receviedAll.countDown(); + } + } +} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeTest.java index c367a0856c..7c9a77eb53 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeTest.java @@ -1,7 +1,5 @@ -package org.apache.qpid.test.unit.ack; - /* - * + * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information @@ -21,133 +19,138 @@ package org.apache.qpid.test.unit.ack; * */ +package org.apache.qpid.test.unit.ack; + +import org.apache.qpid.client.AMQDestination; +import org.apache.qpid.client.AMQSession; +import org.apache.qpid.test.utils.FailoverBaseCase; + 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 javax.jms.MessageProducer; -import org.apache.qpid.client.AMQDestination; -import org.apache.qpid.client.AMQSession; -import org.apache.qpid.client.AMQConnection; -import org.apache.qpid.client.message.AbstractJMSMessage; -import org.apache.qpid.test.utils.QpidTestCase; - -public class AcknowledgeTest extends QpidTestCase +public class AcknowledgeTest extends FailoverBaseCase { - protected static int NUM_MESSAGES = 100; - protected Connection _con; + protected int NUM_MESSAGES; + protected Connection _connection; protected Queue _queue; - private MessageProducer _producer; - private Session _producerSession; - private Session _consumerSession; - private MessageConsumer _consumerA; + protected Session _consumerSession; + protected MessageConsumer _consumer; + protected MessageProducer _producer; @Override protected void setUp() throws Exception { super.setUp(); - _queue = (Queue) getInitialContext().lookup("queue"); + NUM_MESSAGES = 5; + + _queue = getTestQueue(); //Create Producer put some messages on the queue - _con = getConnection(); - _con.start(); + _connection = getConnection(); } - private void init(boolean transacted, int mode) throws JMSException { - _producerSession = _con.createSession(true, Session.AUTO_ACKNOWLEDGE); - _consumerSession = _con.createSession(transacted, mode); - _producer = _producerSession.createProducer(_queue); - _consumerA = _consumerSession.createConsumer(_queue); - } + protected void init(boolean transacted, int mode) throws Exception + { + _consumerSession = _connection.createSession(transacted, mode); + _consumer = _consumerSession.createConsumer(_queue); + _producer = _consumerSession.createProducer(_queue); + + // These should all end up being prefetched by session + sendMessage(_consumerSession, _queue, 1); + + assertEquals("Wrong number of messages on queue", 1, + ((AMQSession) _consumerSession).getQueueDepth((AMQDestination) _queue)); + } /** - * Produces and consumes messages an either ack or commit the receipt of those messages - * * @param transacted * @param mode + * * @throws Exception */ - private void testMessageAck(boolean transacted, int mode) throws Exception + protected void testAcking(boolean transacted, int mode) throws Exception { - init(transacted, mode); - sendMessage(_producerSession, _queue, NUM_MESSAGES/2); - _producerSession.commit(); - MessageConsumer consumerB = _consumerSession.createConsumer(_queue); - sendMessage(_producerSession, _queue, NUM_MESSAGES/2); - _producerSession.commit(); + init(transacted, mode); + + _connection.start(); + + Message msg = _consumer.receive(1500); + int count = 0; - Message msg = consumerB.receive(1500); - while (msg != null) + while (count < NUM_MESSAGES) { - if (mode == Session.CLIENT_ACKNOWLEDGE) + assertNotNull("Message " + count + " not correctly received.", msg); + assertEquals("Incorrect message received", count, msg.getIntProperty(INDEX)); + count++; + + if (count < NUM_MESSAGES) { - msg.acknowledge(); + //Send the next message + _producer.send(createNextMessage(_consumerSession, count)); } - count++; - msg = consumerB.receive(1500); + + doAcknowlegement(msg); + + msg = _consumer.receive(1500); } - if (transacted) - { - _consumerSession.commit(); - } - _consumerA.close(); - consumerB.close(); - _consumerSession.close(); - assertEquals("Wrong number of messages on queue", NUM_MESSAGES - count, - ((AMQSession) _producerSession).getQueueDepth((AMQDestination) _queue)); - - // Clean up messages that may be left on the queue - _consumerSession = _con.createSession(transacted, mode); - _consumerA = _consumerSession.createConsumer(_queue); - msg = _consumerA.receive(1500); - while (msg != null) + + assertEquals("Wrong number of messages on queue", 0, + ((AMQSession) _consumerSession).getQueueDepth((AMQDestination) _queue)); + } + + /** + * Perform the acknowledgement of messages if additionally required. + * + * @param msg + * + * @throws JMSException + */ + protected void doAcknowlegement(Message msg) throws JMSException + { + if (_consumerSession.getTransacted()) { - if (mode == Session.CLIENT_ACKNOWLEDGE) - { - msg.acknowledge(); - } - msg = _consumerA.receive(1500); + _consumerSession.commit(); } - _consumerA.close(); - if (transacted) + + if (_consumerSession.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE) { - _consumerSession.commit(); + msg.acknowledge(); } - _consumerSession.close(); } - - public void test2ConsumersAutoAck() throws Exception + + public void testClientAck() throws Exception { - testMessageAck(false, Session.AUTO_ACKNOWLEDGE); + testAcking(false, Session.CLIENT_ACKNOWLEDGE); } - public void test2ConsumersClientAck() throws Exception + public void testAutoAck() throws Exception { - testMessageAck(true, Session.CLIENT_ACKNOWLEDGE); + testAcking(false, Session.AUTO_ACKNOWLEDGE); } - - public void test2ConsumersTx() throws Exception + + public void testTransacted() throws Exception { - testMessageAck(true, Session.AUTO_ACKNOWLEDGE); + testAcking(true, Session.SESSION_TRANSACTED); } - - public void testIndividualAck() throws Exception + + public void testDupsOk() throws Exception { - init(false, Session.CLIENT_ACKNOWLEDGE); - sendMessage(_producerSession, _queue, 3); - _producerSession.commit(); - Message msg = null; - for (int i = 0; i < 2; i++) - { - msg = _consumerA.receive(RECEIVE_TIMEOUT); - ((AbstractJMSMessage)msg).acknowledgeThis(); - } - msg = _consumerA.receive(RECEIVE_TIMEOUT); - msg.acknowledge(); - _con.close(); + testAcking(false, Session.DUPS_OK_ACKNOWLEDGE); } - + + public void testNoAck() throws Exception + { + testAcking(false, AMQSession.NO_ACKNOWLEDGE); + } + + public void testPreAck() throws Exception + { + testAcking(false, AMQSession.PRE_ACKNOWLEDGE); + } + } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/FailoverBeforeConsumingRecoverTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/FailoverBeforeConsumingRecoverTest.java new file mode 100644 index 0000000000..834b17430b --- /dev/null +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/FailoverBeforeConsumingRecoverTest.java @@ -0,0 +1,40 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.test.unit.ack; + +import org.apache.qpid.jms.Session; + +import javax.jms.Message; +import javax.jms.Queue; + +public class FailoverBeforeConsumingRecoverTest extends RecoverTest +{ + + @Override + protected void initTest() throws Exception + { + super.initTest(); + failBroker(getFailingPort()); + + Queue queue = _consumerSession.createQueue(getTestQueueName()); + sendMessage(_connection.createSession(false, Session.AUTO_ACKNOWLEDGE), queue, SENT_COUNT); + } +} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/QuickAcking.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/QuickAcking.java new file mode 100644 index 0000000000..6c4b7ba01b --- /dev/null +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/QuickAcking.java @@ -0,0 +1,148 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.test.unit.ack; + +import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch; +import org.apache.qpid.client.AMQConnection; +import org.apache.qpid.jms.ConnectionListener; +import org.apache.qpid.test.utils.QpidTestCase; + +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Queue; +import javax.jms.Session; + +/** + * This is a quick manual test to validate acking after failover with a + * transacted session. + * + * Start an external broker then run this test. Std Err will print. + * Sent Message: 1 + * Received Message: 1 + * + * You can then restart the external broker, which will cause failover, which + * will be complete when the following appears. + * + * Failover Complete + * + * A second message send/receive cycle is then done to validate that the + * connection/session are still working. + * + */ +public class QuickAcking extends QpidTestCase implements ConnectionListener +{ + protected AMQConnection _connection; + protected Queue _queue; + protected Session _session; + protected MessageConsumer _consumer; + private CountDownLatch _failedOver; + private static final String INDEX = "INDEX"; + private int _count = 0; + + public void setUp() + { + // Prevent broker startup. Broker must be run manually. + } + + public void test() throws Exception + { + _failedOver = new CountDownLatch(1); + + _connection = new AMQConnection("amqp://guest:guest@client/test?brokerlist='localhost?retries='20'&connectdelay='2000''"); + + _session = _connection.createSession(true, Session.SESSION_TRANSACTED); + _queue = _session.createQueue("QAtest"); + _consumer = _session.createConsumer(_queue); + _connection.setConnectionListener(this); + _connection.start(); + + sendAndReceive(); + + _failedOver.await(); + + sendAndReceive(); + + } + + private void sendAndReceive() + throws Exception + { + sendMessage(); + + Message message = _consumer.receive(); + + if (message.getIntProperty(INDEX) != _count) + { + throw new Exception("Incorrect message recieved:" + _count); + } + + if (_session.getTransacted()) + { + _session.commit(); + } + System.err.println("Recevied Message:" + _count); + } + + private void sendMessage() throws JMSException + { + MessageProducer producer = _session.createProducer(_queue); + Message message = _session.createMessage(); + _count++; + message.setIntProperty(INDEX, _count); + + producer.send(message); + if (_session.getTransacted()) + { + _session.commit(); + } + producer.close(); + + System.err.println("Sent Message:" + _count); + } + + public void bytesSent(long count) + { + //To change body of implemented methods use File | Settings | File Templates. + } + + public void bytesReceived(long count) + { + //To change body of implemented methods use File | Settings | File Templates. + } + + public boolean preFailover(boolean redirect) + { + return true; + } + + public boolean preResubscribe() + { + return true; + } + + public void failoverComplete() + { + System.err.println("Failover Complete"); + _failedOver.countDown(); + } +} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/RecoverTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/RecoverTest.java index 7434fcbb30..4a123cb1dc 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/RecoverTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/RecoverTest.java @@ -23,8 +23,7 @@ import org.apache.qpid.client.AMQConnection; import org.apache.qpid.client.AMQQueue; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.jms.Session; -import org.apache.qpid.test.utils.QpidTestCase; - +import org.apache.qpid.test.utils.FailoverBaseCase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,16 +34,21 @@ import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.TextMessage; - import java.util.concurrent.atomic.AtomicInteger; -public class RecoverTest extends QpidTestCase +public class RecoverTest extends FailoverBaseCase { - private static final Logger _logger = LoggerFactory.getLogger(RecoverTest.class); + static final Logger _logger = LoggerFactory.getLogger(RecoverTest.class); private Exception _error; private AtomicInteger count; + protected AMQConnection _connection; + protected Session _consumerSession; + protected MessageConsumer _consumer; + static final int SENT_COUNT = 4; + + @Override protected void setUp() throws Exception { super.setUp(); @@ -52,134 +56,110 @@ public class RecoverTest extends QpidTestCase count = new AtomicInteger(); } - protected void tearDown() throws Exception + protected void initTest() throws Exception { - super.tearDown(); - count = null; - } + _connection = (AMQConnection) getConnection("guest", "guest"); - public void testRecoverResendsMsgs() throws Exception - { - AMQConnection con = (AMQConnection) getConnection("guest", "guest"); - - Session consumerSession = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Queue queue = - new AMQQueue(consumerSession.getDefaultQueueExchangeName(), new AMQShortString("someQ"), - new AMQShortString("someQ"), false, true); - MessageConsumer consumer = consumerSession.createConsumer(queue); - // force synch to ensure the consumer has resulted in a bound queue - // ((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.DIRECT_EXCHANGE_NAME, ExchangeDefaults.DIRECT_EXCHANGE_CLASS); - // This is the default now + _consumerSession = _connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + Queue queue = _consumerSession.createQueue(getTestQueueName()); - AMQConnection con2 = (AMQConnection) getConnection("guest", "guest"); - Session producerSession = con2.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(queue); + _consumer = _consumerSession.createConsumer(queue); _logger.info("Sending four messages"); - producer.send(producerSession.createTextMessage("msg1")); - producer.send(producerSession.createTextMessage("msg2")); - producer.send(producerSession.createTextMessage("msg3")); - producer.send(producerSession.createTextMessage("msg4")); - - con2.close(); - + sendMessage(_connection.createSession(false, Session.AUTO_ACKNOWLEDGE), queue, SENT_COUNT); _logger.info("Starting connection"); - con.start(); - TextMessage tm = (TextMessage) consumer.receive(); - tm.acknowledge(); - _logger.info("Received and acknowledged first message"); - consumer.receive(); - consumer.receive(); - consumer.receive(); - _logger.info("Received all four messages. Calling recover with three outstanding messages"); - // no ack for last three messages so when I call recover I expect to get three messages back - consumerSession.recover(); - tm = (TextMessage) consumer.receive(3000); - assertEquals("msg2", tm.getText()); + _connection.start(); + } - tm = (TextMessage) consumer.receive(3000); - assertEquals("msg3", tm.getText()); + protected Message validateNextMessages(int nextCount, int startIndex) throws JMSException + { + Message message = null; + for (int index = 0; index < nextCount; index++) + { + message = _consumer.receive(3000); + assertEquals(startIndex + index, message.getIntProperty(INDEX)); + } + return message; + } - tm = (TextMessage) consumer.receive(3000); - assertEquals("msg4", tm.getText()); + protected void validateRemainingMessages(int remaining) throws JMSException + { + int index = SENT_COUNT - remaining; - _logger.info("Received redelivery of three messages. Acknowledging last message"); - tm.acknowledge(); + Message message = null; + while (index != SENT_COUNT) + { + message = _consumer.receive(3000); + assertEquals(index++, message.getIntProperty(INDEX)); + } + + if (message != null) + { + _logger.info("Received redelivery of three messages. Acknowledging last message"); + message.acknowledge(); + } _logger.info("Calling acknowledge with no outstanding messages"); // all acked so no messages to be delivered - consumerSession.recover(); + _consumerSession.recover(); - tm = (TextMessage) consumer.receiveNoWait(); - assertNull(tm); + message = _consumer.receiveNoWait(); + assertNull(message); _logger.info("No messages redelivered as is expected"); - - con.close(); } - public void testRecoverResendsMsgsAckOnEarlier() throws Exception + public void testRecoverResendsMsgs() throws Exception { - AMQConnection con = (AMQConnection) getConnection("guest", "guest"); + initTest(); - Session consumerSession = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Queue queue = - new AMQQueue(consumerSession.getDefaultQueueExchangeName(), new AMQShortString("someQ"), - new AMQShortString("someQ"), false, true); - MessageConsumer consumer = consumerSession.createConsumer(queue); - // force synch to ensure the consumer has resulted in a bound queue - // ((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.DIRECT_EXCHANGE_NAME, ExchangeDefaults.DIRECT_EXCHANGE_CLASS); - // This is the default now + Message message = validateNextMessages(1, 0); + message.acknowledge(); + _logger.info("Received and acknowledged first message"); - AMQConnection con2 = (AMQConnection) getConnection("guest", "guest"); - Session producerSession = con2.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(queue); + _consumer.receive(); + _consumer.receive(); + _consumer.receive(); + _logger.info("Received all four messages. Calling recover with three outstanding messages"); + // no ack for last three messages so when I call recover I expect to get three messages back - _logger.info("Sending four messages"); - producer.send(producerSession.createTextMessage("msg1")); - producer.send(producerSession.createTextMessage("msg2")); - producer.send(producerSession.createTextMessage("msg3")); - producer.send(producerSession.createTextMessage("msg4")); + _consumerSession.recover(); - con2.close(); + validateRemainingMessages(3); + } - _logger.info("Starting connection"); - con.start(); - TextMessage tm = (TextMessage) consumer.receive(); - consumer.receive(); - tm.acknowledge(); + public void testRecoverResendsMsgsAckOnEarlier() throws Exception + { + initTest(); + + Message message = validateNextMessages(2, 0); + message.acknowledge(); _logger.info("Received 2 messages, acknowledge() first message, should acknowledge both"); - consumer.receive(); - consumer.receive(); + _consumer.receive(); + _consumer.receive(); _logger.info("Received all four messages. Calling recover with two outstanding messages"); // no ack for last three messages so when I call recover I expect to get three messages back - consumerSession.recover(); - TextMessage tm3 = (TextMessage) consumer.receive(3000); - assertEquals("msg3", tm3.getText()); + _consumerSession.recover(); + + Message message2 = _consumer.receive(3000); + assertEquals(2, message2.getIntProperty(INDEX)); - TextMessage tm4 = (TextMessage) consumer.receive(3000); - assertEquals("msg4", tm4.getText()); + Message message3 = _consumer.receive(3000); + assertEquals(3, message3.getIntProperty(INDEX)); _logger.info("Received redelivery of two messages. calling acknolwedgeThis() first of those message"); - ((org.apache.qpid.jms.Message) tm3).acknowledgeThis(); + ((org.apache.qpid.jms.Message) message2).acknowledgeThis(); _logger.info("Calling recover"); // all acked so no messages to be delivered - consumerSession.recover(); + _consumerSession.recover(); - tm4 = (TextMessage) consumer.receive(3000); - assertEquals("msg4", tm4.getText()); - ((org.apache.qpid.jms.Message) tm4).acknowledgeThis(); + message3 = _consumer.receive(3000); + assertEquals(3, message3.getIntProperty(INDEX)); + ((org.apache.qpid.jms.Message) message3).acknowledgeThis(); - _logger.info("Calling recover"); // all acked so no messages to be delivered - consumerSession.recover(); - - tm = (TextMessage) consumer.receiveNoWait(); - assertNull(tm); - _logger.info("No messages redelivered as is expected"); - - con.close(); + validateRemainingMessages(0); } public void testAcknowledgePerConsumer() throws Exception @@ -188,11 +168,11 @@ public class RecoverTest extends QpidTestCase Session consumerSession = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); Queue queue = - new AMQQueue(consumerSession.getDefaultQueueExchangeName(), new AMQShortString("Q1"), new AMQShortString("Q1"), - false, true); + new AMQQueue(consumerSession.getDefaultQueueExchangeName(), new AMQShortString("Q1"), new AMQShortString("Q1"), + false, true); Queue queue2 = - new AMQQueue(consumerSession.getDefaultQueueExchangeName(), new AMQShortString("Q2"), new AMQShortString("Q2"), - false, true); + new AMQQueue(consumerSession.getDefaultQueueExchangeName(), new AMQShortString("Q2"), new AMQShortString("Q2"), + false, true); MessageConsumer consumer = consumerSession.createConsumer(queue); MessageConsumer consumer2 = consumerSession.createConsumer(queue2); @@ -231,8 +211,8 @@ public class RecoverTest extends QpidTestCase final Session consumerSession = con.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = - new AMQQueue(consumerSession.getDefaultQueueExchangeName(), new AMQShortString("Q3"), new AMQShortString("Q3"), - false, true); + new AMQQueue(consumerSession.getDefaultQueueExchangeName(), new AMQShortString("Q3"), new AMQShortString("Q3"), + false, true); MessageConsumer consumer = consumerSession.createConsumer(queue); MessageProducer producer = consumerSession.createProducer(queue); producer.send(consumerSession.createTextMessage("hello")); @@ -240,50 +220,50 @@ public class RecoverTest extends QpidTestCase final Object lock = new Object(); consumer.setMessageListener(new MessageListener() - { + { - public void onMessage(Message message) + public void onMessage(Message message) + { + try { - try + count.incrementAndGet(); + if (count.get() == 1) { - count.incrementAndGet(); - if (count.get() == 1) + if (message.getJMSRedelivered()) { - if (message.getJMSRedelivered()) - { - setError( + setError( new Exception("Message marked as redilvered on what should be first delivery attempt")); - } - - consumerSession.recover(); } - else if (count.get() == 2) + + consumerSession.recover(); + } + else if (count.get() == 2) + { + if (!message.getJMSRedelivered()) { - if (!message.getJMSRedelivered()) - { - setError( + setError( new Exception( - "Message not marked as redilvered on what should be second delivery attempt")); - } - } - else - { - System.err.println(message); - fail("Message delivered too many times!: " + count); + "Message not marked as redilvered on what should be second delivery attempt")); } } - catch (JMSException e) + else { - _logger.error("Error recovering session: " + e, e); - setError(e); + System.err.println(message); + fail("Message delivered too many times!: " + count); } + } + catch (JMSException e) + { + _logger.error("Error recovering session: " + e, e); + setError(e); + } - synchronized (lock) - { - lock.notify(); - } + synchronized (lock) + { + lock.notify(); } - }); + } + }); con.start(); @@ -323,9 +303,4 @@ public class RecoverTest extends QpidTestCase { _error = e; } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(RecoverTest.class); - } } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/basic/SelectorTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/basic/SelectorTest.java deleted file mode 100644 index c42e4c7582..0000000000 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/basic/SelectorTest.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.test.unit.basic; - -import org.apache.qpid.AMQException; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.client.AMQConnection; -import org.apache.qpid.client.AMQDestination; -import org.apache.qpid.client.AMQQueue; -import org.apache.qpid.client.AMQSession; -import org.apache.qpid.client.BasicMessageProducer; -import org.apache.qpid.client.state.StateWaiter; -import org.apache.qpid.url.URLSyntaxException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.InvalidSelectorException; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; -import java.util.concurrent.CountDownLatch; - -public class SelectorTest extends QpidTestCase implements MessageListener -{ - private static final Logger _logger = LoggerFactory.getLogger(SelectorTest.class); - - private AMQConnection _connection; - private AMQDestination _destination; - private AMQSession _session; - private int count; - public String _connectionString = "vm://:1"; - private static final String INVALID_SELECTOR = "Cost LIKE 5"; - CountDownLatch _responseLatch = new CountDownLatch(1); - - protected void setUp() throws Exception - { - super.setUp(); - init((AMQConnection) getConnection("guest", "guest")); - } - - protected void tearDown() throws Exception - { - super.tearDown(); - } - - private void init(AMQConnection connection) throws JMSException - { - init(connection, new AMQQueue(connection, randomize("SessionStartTest"), true)); - } - - private void init(AMQConnection connection, AMQDestination destination) throws JMSException - { - _connection = connection; - _destination = destination; - connection.start(); - - String selector = null; - selector = "Cost = 2 AND \"property-with-hyphen\" = 'wibble'"; - // selector = "JMSType = Special AND Cost = 2 AND AMQMessageID > 0 AND JMSDeliveryMode=" + DeliveryMode.NON_PERSISTENT; - - _session = (AMQSession) connection.createSession(false, AMQSession.NO_ACKNOWLEDGE); - // _session.createConsumer(destination).setMessageListener(this); - _session.createConsumer(destination, selector).setMessageListener(this); - } - - public void test() throws Exception - { - try - { - - init((AMQConnection) getConnection("guest", "guest", randomize("Client"))); - - Message msg = _session.createTextMessage("Message"); - msg.setJMSPriority(1); - msg.setIntProperty("Cost", 2); - msg.setStringProperty("property-with-hyphen", "wibble"); - msg.setJMSType("Special"); - - _logger.info("Sending Message:" + msg); - - ((BasicMessageProducer) _session.createProducer(_destination)).send(msg, DeliveryMode.NON_PERSISTENT); - _logger.info("Message sent, waiting for response..."); - - _responseLatch.await(); - - if (count > 0) - { - _logger.info("Got message"); - } - - if (count == 0) - { - fail("Did not get message!"); - // throw new RuntimeException("Did not get message!"); - } - } - catch (JMSException e) - { - _logger.debug("JMS:" + e.getClass().getSimpleName() + ":" + e.getMessage()); - if (!(e instanceof InvalidSelectorException)) - { - fail("Wrong exception:" + e.getMessage()); - } - else - { - System.out.println("SUCCESS!!"); - } - } - catch (InterruptedException e) - { - _logger.debug("IE :" + e.getClass().getSimpleName() + ":" + e.getMessage()); - } - catch (URLSyntaxException e) - { - _logger.debug("URL:" + e.getClass().getSimpleName() + ":" + e.getMessage()); - fail("Wrong exception"); - } - catch (AMQException e) - { - _logger.debug("AMQ:" + e.getClass().getSimpleName() + ":" + e.getMessage()); - fail("Wrong exception"); - } - - finally - { - if (_session != null) - { - _session.close(); - } - if (_connection != null) - { - _connection.close(); - } - } - } - - - public void testInvalidSelectors() throws Exception - { - Connection connection = null; - - try - { - connection = getConnection("guest", "guest", randomize("Client")); - _session = (AMQSession) connection.createSession(false, AMQSession.NO_ACKNOWLEDGE); - } - catch (JMSException e) - { - fail(e.getMessage()); - } - catch (AMQException e) - { - fail(e.getMessage()); - } - catch (URLSyntaxException e) - { - fail("Error:" + e.getMessage()); - } - - //Try Creating a Browser - try - { - _session.createBrowser(_session.createQueue("Ping"), INVALID_SELECTOR); - } - catch (JMSException e) - { - _logger.debug("JMS:" + e.getClass().getSimpleName() + ":" + e.getMessage()); - if (!(e instanceof InvalidSelectorException)) - { - fail("Wrong exception:" + e.getMessage()); - } - else - { - _logger.debug("SUCCESS!!"); - } - } - - //Try Creating a Consumer - try - { - _session.createConsumer(_session.createQueue("Ping"), INVALID_SELECTOR); - } - catch (JMSException e) - { - _logger.debug("JMS:" + e.getClass().getSimpleName() + ":" + e.getMessage()); - if (!(e instanceof InvalidSelectorException)) - { - fail("Wrong exception:" + e.getMessage()); - } - else - { - _logger.debug("SUCCESS!!"); - } - } - - //Try Creating a Receiever - try - { - _session.createReceiver(_session.createQueue("Ping"), INVALID_SELECTOR); - } - catch (JMSException e) - { - _logger.debug("JMS:" + e.getClass().getSimpleName() + ":" + e.getMessage()); - if (!(e instanceof InvalidSelectorException)) - { - fail("Wrong exception:" + e.getMessage()); - } - else - { - _logger.debug("SUCCESS!!"); - } - } - - finally - { - if (_session != null) - { - try - { - _session.close(); - } - catch (JMSException e) - { - fail("Error cleaning up:" + e.getMessage()); - } - } - if (_connection != null) - { - try - { - _connection.close(); - } - catch (JMSException e) - { - fail("Error cleaning up:" + e.getMessage()); - } - } - } - } - - public void onMessage(Message message) - { - count++; - _logger.info("Got Message:" + message); - _responseLatch.countDown(); - } - - private static String randomize(String in) - { - return in + System.currentTimeMillis(); - } - - public static void main(String[] argv) throws Exception - { - SelectorTest test = new SelectorTest(); - test._connectionString = (argv.length == 0) ? "localhost:3000" : argv[0]; - - try - { - while (true) - { - if (test._connectionString.contains("vm://:1")) - { - test.setUp(); - } - test.test(); - - if (test._connectionString.contains("vm://:1")) - { - test.tearDown(); - } - } - } - catch (Exception e) - { - System.err.println(e.getMessage()); - e.printStackTrace(); - } - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(SelectorTest.class); - } -} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/message/JMSPropertiesTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/message/JMSPropertiesTest.java index 1f90f1e29f..6b69ccab6c 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/message/JMSPropertiesTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/message/JMSPropertiesTest.java @@ -31,6 +31,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jms.Destination; +import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.ObjectMessage; @@ -105,7 +106,8 @@ public class JMSPropertiesTest extends QpidTestCase assertEquals("JMS Type mismatch", sentMsg.getJMSType(), rm.getJMSType()); assertEquals("JMS Reply To mismatch", sentMsg.getJMSReplyTo(), rm.getJMSReplyTo()); assertTrue("JMSMessageID Does not start ID:", rm.getJMSMessageID().startsWith("ID:")); - + assertEquals("JMS Default priority should be 4",Message.DEFAULT_PRIORITY,rm.getJMSPriority()); + //Validate that the JMSX values are correct assertEquals("JMSXGroupID is not as expected:", JMSXGroupID_VALUE, rm.getStringProperty("JMSXGroupID")); assertEquals("JMSXGroupSeq is not as expected:", JMSXGroupSeq_VALUE, rm.getIntProperty("JMSXGroupSeq")); diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/publish/DirtyTrasactedPubilshTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/publish/DirtyTrasactedPubilshTest.java new file mode 100644 index 0000000000..248042d2c4 --- /dev/null +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/publish/DirtyTrasactedPubilshTest.java @@ -0,0 +1,403 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.test.unit.publish; + +import org.apache.qpid.client.AMQConnection; +import org.apache.qpid.client.AMQDestination; +import org.apache.qpid.client.AMQSession; +import org.apache.qpid.jms.ConnectionListener; +import org.apache.qpid.test.utils.FailoverBaseCase; + +import javax.jms.Connection; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageListener; +import javax.jms.MessageProducer; +import javax.jms.Queue; +import javax.jms.Session; +import javax.jms.TransactionRolledBackException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +/** + * QPID-1816 : Whilst testing Acknoledgement after failover this completes testing + * of the client after failover. When we have a dirty session we should receive + * an error if we attempt to publish. This test ensures that both in the synchronous + * and asynchronous message delivery paths we receive the expected exceptions at + * the expected time. + */ +public class DirtyTrasactedPubilshTest extends FailoverBaseCase implements ConnectionListener +{ + protected CountDownLatch _failoverCompleted = new CountDownLatch(1); + + protected int NUM_MESSAGES; + protected Connection _connection; + protected Queue _queue; + protected Session _consumerSession; + protected MessageConsumer _consumer; + protected MessageProducer _producer; + + private static final String MSG = "MSG"; + private static final String SEND_FROM_ON_MESSAGE_TEXT = "sendFromOnMessage"; + protected CountDownLatch _receviedAll; + protected AtomicReference _causeOfFailure = new AtomicReference(null); + + @Override + protected void setUp() throws Exception + { + super.setUp(); + NUM_MESSAGES = 10; + + _queue = getTestQueue(); + + //Create Producer put some messages on the queue + _connection = getConnection(); + } + + /** + * Initialise the test variables + * @param transacted is this a transacted test + * @param mode if not trasacted then what ack mode to use + * @throws Exception if there is a setup issue. + */ + protected void init(boolean transacted, int mode) throws Exception + { + _consumerSession = _connection.createSession(transacted, mode); + _consumer = _consumerSession.createConsumer(_queue); + _producer = _consumerSession.createProducer(_queue); + + // These should all end up being prefetched by session + sendMessage(_consumerSession, _queue, 1); + + assertEquals("Wrong number of messages on queue", 1, + ((AMQSession) _consumerSession).getQueueDepth((AMQDestination) _queue)); + } + + /** + * If a transacted session has failed over whilst it has uncommitted sent + * data then we need to throw a TransactedRolledbackException on commit() + * + * The alternative would be to maintain a replay buffer so that the message + * could be resent. This is not currently implemented + * + * @throws Exception if something goes wrong. + */ + public void testDirtySendingSynchronousTransacted() throws Exception + { + Session producerSession = _connection.createSession(true, Session.SESSION_TRANSACTED); + + // Ensure we get failover notifications + ((AMQConnection) _connection).setConnectionListener(this); + + MessageProducer producer = producerSession.createProducer(_queue); + + // Create and send message 0 + Message msg = producerSession.createMessage(); + msg.setIntProperty(INDEX, 0); + producer.send(msg); + + // DON'T commit message .. fail connection + + failBroker(getFailingPort()); + + // Ensure destination exists for sending + producerSession.createConsumer(_queue).close(); + + // Send the next message + msg.setIntProperty(INDEX, 1); + try + { + producer.send(msg); + fail("Should fail with Qpid as we provide early warning of the dirty session via a JMSException."); + } + catch (JMSException jmse) + { + assertEquals("Early warning of dirty session not correct", + "Failover has occurred and session is dirty so unable to send.", jmse.getMessage()); + } + + // Ignore that the session is dirty and attempt to commit to validate the + // exception is thrown. AND that the above failure notification did NOT + // clean up the session. + + try + { + producerSession.commit(); + fail("Session is dirty we should get an TransactionRolledBackException"); + } + catch (TransactionRolledBackException trbe) + { + // Normal path. + } + + // Resending of messages should now work ok as the commit was forcilbly rolledback + msg.setIntProperty(INDEX, 0); + producer.send(msg); + msg.setIntProperty(INDEX, 1); + producer.send(msg); + + producerSession.commit(); + + assertEquals("Wrong number of messages on queue", 2, + ((AMQSession) producerSession).getQueueDepth((AMQDestination) _queue)); + } + + /** + * If a transacted session has failed over whilst it has uncommitted sent + * data then we need to throw a TransactedRolledbackException on commit() + * + * The alternative would be to maintain a replay buffer so that the message + * could be resent. This is not currently implemented + * + * @throws Exception if something goes wrong. + */ + public void testDirtySendingOnMessageTransacted() throws Exception + { + NUM_MESSAGES = 1; + _receviedAll = new CountDownLatch(NUM_MESSAGES); + ((AMQConnection) _connection).setConnectionListener(this); + + init(true, Session.SESSION_TRANSACTED); + + _consumer.setMessageListener(new MessageListener() + { + + public void onMessage(Message message) + { + try + { + // Create and send message 0 + Message msg = _consumerSession.createMessage(); + msg.setIntProperty(INDEX, 0); + _producer.send(msg); + + // DON'T commit message .. fail connection + + failBroker(getFailingPort()); + + // rep + repopulateBroker(); + + // Destination will exist as this failBroker will populate + // the queue with 1 message + + // Send the next message + msg.setIntProperty(INDEX, 1); + try + { + _producer.send(msg); + fail("Should fail with Qpid as we provide early warning of the dirty session via a JMSException."); + } + catch (JMSException jmse) + { + assertEquals("Early warning of dirty session not correct", + "Failover has occurred and session is dirty so unable to send.", jmse.getMessage()); + } + + // Ignore that the session is dirty and attempt to commit to validate the + // exception is thrown. AND that the above failure notification did NOT + // clean up the session. + + try + { + _consumerSession.commit(); + fail("Session is dirty we should get an TransactionRolledBackException"); + } + catch (TransactionRolledBackException trbe) + { + // Normal path. + } + + // Resend messages + msg.setIntProperty(INDEX, 0); + msg.setStringProperty(MSG, SEND_FROM_ON_MESSAGE_TEXT); + _producer.send(msg); + msg.setIntProperty(INDEX, 1); + msg.setStringProperty(MSG, SEND_FROM_ON_MESSAGE_TEXT); + _producer.send(msg); + + _consumerSession.commit(); + + // Stop this consumer .. can't do _consumer.stop == DEADLOCK + // this doesn't seem to stop dispatcher running + _connection.stop(); + + // Signal that the onMessage send part of test is complete + // main thread can validate that messages are correct + _receviedAll.countDown(); + + } + catch (Exception e) + { + fail(e); + } + + } + + }); + + _connection.start(); + + if (!_receviedAll.await(10000L, TimeUnit.MILLISECONDS)) + { + // Check to see if we ended due to an exception in the onMessage handler + Exception cause = _causeOfFailure.get(); + if (cause != null) + { + cause.printStackTrace(); + fail(cause.getMessage()); + } + else + { + fail("All messages not received:" + _receviedAll.getCount() + "/" + NUM_MESSAGES); + } + } + + // Check to see if we ended due to an exception in the onMessage handler + Exception cause = _causeOfFailure.get(); + if (cause != null) + { + cause.printStackTrace(); + fail(cause.getMessage()); + } + + _consumer.close(); + _consumerSession.close(); + + _consumerSession = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + _connection.start(); + + // Validate that we could send the messages as expected. + assertEquals("Wrong number of messages on queue", 3, + ((AMQSession) _consumerSession).getQueueDepth((AMQDestination) _queue)); + + MessageConsumer consumer = _consumerSession.createConsumer(_queue); + + //Validate the message sent to setup the failed over broker. + Message message = consumer.receive(1000); + assertNotNull("Message " + 0 + " not received.", message); + assertEquals("Incorrect message received", 0, message.getIntProperty(INDEX)); + + // Validate the two messages sent from within the onMessage + for (int index = 0; index <= 1; index++) + { + message = consumer.receive(1000); + assertNotNull("Message " + index + " not received.", message); + assertEquals("Incorrect message received", index, message.getIntProperty(INDEX)); + assertEquals("Incorrect message text for message:" + index, SEND_FROM_ON_MESSAGE_TEXT, message.getStringProperty(MSG)); + } + + assertNull("Extra message received.", consumer.receiveNoWait()); + + _consumerSession.close(); + + assertEquals("Wrong number of messages on queue", 0, + ((AMQSession) getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE)).getQueueDepth((AMQDestination) _queue)); + } + + private void repopulateBroker() throws Exception + { + // Repopulate this new broker so we can test what happends after failover + + //Get the connection to the first (main port) broker. + Connection connection = getConnection(); + // Use a transaction to send messages so we can be sure they arrive. + Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + // ensure destination is created. + session.createConsumer(_queue).close(); + + sendMessage(session, _queue, NUM_MESSAGES); + + assertEquals("Wrong number of messages on queue", NUM_MESSAGES, + ((AMQSession) session).getQueueDepth((AMQDestination) _queue)); + + connection.close(); + } + + // AMQConnectionListener Interface.. used so we can validate that we + // actually failed over. + + public void bytesSent(long count) + { + } + + public void bytesReceived(long count) + { + } + + public boolean preFailover(boolean redirect) + { + //Allow failover + return true; + } + + public boolean preResubscribe() + { + //Allow failover + return true; + } + + public void failoverComplete() + { + _failoverCompleted.countDown(); + } + + /** + * Override so we can block until failover has completd + * + * @param port int the port of the broker to fail. + */ + @Override + public void failBroker(int port) + { + super.failBroker(port); + + try + { + if (!_failoverCompleted.await(DEFAULT_FAILOVER_TIME, TimeUnit.MILLISECONDS)) + { + fail("Failover did not occur in specified time:" + DEFAULT_FAILOVER_TIME); + } + } + catch (InterruptedException e) + { + fail("Failover was interuppted"); + } + } + + /** + * Pass the given exception back to the waiting thread to fail the test run. + * + * @param e The exception that is causing the test to fail. + */ + protected void fail(Exception e) + { + _causeOfFailure.set(e); + // End the test. + while (_receviedAll.getCount() != 0) + { + _receviedAll.countDown(); + } + } +} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java index 64bd1503ba..0426c4f45f 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/FailoverBaseCase.java @@ -20,44 +20,43 @@ */ package org.apache.qpid.test.utils; -import javax.jms.Connection; -import javax.jms.JMSException; +import org.apache.qpid.util.FileUtils; + import javax.naming.NamingException; -import org.apache.qpid.util.FileUtils; +import org.apache.qpid.client.AMQConnectionFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class FailoverBaseCase extends QpidTestCase { + protected static final Logger _logger = LoggerFactory.getLogger(FailoverBaseCase.class); public static int FAILING_VM_PORT = 2; - public static int FAILING_PORT = DEFAULT_PORT + 100; + public static int FAILING_PORT = Integer.parseInt(System.getProperty("test.port.alt")); + public static final long DEFAULT_FAILOVER_TIME = 10000L; protected int failingPort; - - private boolean failedOver = false; - public FailoverBaseCase() + protected int getFailingPort() { if (_broker.equals(VM)) { - failingPort = FAILING_VM_PORT; + return FAILING_VM_PORT; } else { - failingPort = FAILING_PORT; + return FAILING_PORT; } } - - protected int getFailingPort() - { - return failingPort; - } protected void setUp() throws java.lang.Exception { super.setUp(); - setSystemProperty("QPID_WORK", System.getProperty("java.io.tmpdir")+"/"+getFailingPort()); - startBroker(failingPort); + // Set QPID_WORK to $QPID_WORK/ + // or /tmp/ if QPID_WORK not set. + setSystemProperty("QPID_WORK", System.getProperty("QPID_WORK") + "/" + getFailingPort()); + startBroker(getFailingPort()); } /** @@ -66,42 +65,52 @@ public class FailoverBaseCase extends QpidTestCase * @return a connection * @throws Exception */ - public Connection getConnection() throws JMSException, NamingException + @Override + public AMQConnectionFactory getConnectionFactory() throws NamingException { - Connection conn = - (Boolean.getBoolean("profile.use_ssl"))? - getConnectionFactory("failover.ssl").createConnection("guest", "guest"): - getConnectionFactory("failover").createConnection("guest", "guest"); - _connections.add(conn); - return conn; + _logger.info("get ConnectionFactory"); + if (_connectionFactory == null) + { + if (Boolean.getBoolean("profile.use_ssl")) + { + _connectionFactory = getConnectionFactory("failover.ssl"); + } + else + { + _connectionFactory = getConnectionFactory("failover"); + } + } + return _connectionFactory; } + public void tearDown() throws Exception { - stopBroker(_broker.equals(VM)?FAILING_PORT:FAILING_PORT); - super.tearDown(); - FileUtils.deleteDirectory(System.getProperty("java.io.tmpdir")+"/"+getFailingPort()); + try + { + super.tearDown(); + } + finally + { + // Ensure we shutdown any secondary brokers, even if we are unable + // to cleanly tearDown the QTC. + stopBroker(getFailingPort()); + FileUtils.deleteDirectory(System.getProperty("QPID_WORK") + "/" + getFailingPort()); + } } - /** - * Only used of VM borker. - */ - public void failBroker() + public void failBroker(int port) { - failedOver = true; try { - stopBroker(getFailingPort()); + stopBroker(port); } catch (Exception e) { throw new RuntimeException(e); } } - - protected void setFailingPort(int p) - { - failingPort = p; - } + + } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidTestCase.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidTestCase.java index 76e4118c96..6c1b1c7b8d 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidTestCase.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidTestCase.java @@ -22,8 +22,10 @@ import junit.framework.TestResult; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.apache.qpid.AMQException; +import org.apache.qpid.exchange.ExchangeDefaults; import org.apache.qpid.client.AMQConnection; import org.apache.qpid.client.AMQConnectionFactory; +import org.apache.qpid.client.AMQQueue; import org.apache.qpid.client.transport.TransportConnection; import org.apache.qpid.jms.BrokerDetails; import org.apache.qpid.jms.ConnectionURL; @@ -32,6 +34,7 @@ import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry; import org.apache.qpid.server.store.DerbyMessageStore; import org.apache.qpid.url.URLSyntaxException; +import org.apache.log4j.Level; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -70,13 +73,18 @@ public class QpidTestCase extends TestCase protected final String QpidHome = System.getProperty("QPID_HOME"); protected File _configFile = new File(System.getProperty("broker.config")); - private static final Logger _logger = LoggerFactory.getLogger(QpidTestCase.class); + protected static final Logger _logger = LoggerFactory.getLogger(QpidTestCase.class); protected long RECEIVE_TIMEOUT = 1000l; - private Map _setProperties = new HashMap(); + private Map _propertiesSetForTestOnly = new HashMap(); + private Map _propertiesSetForBroker = new HashMap(); + private Map _loggerLevelSetForTest = new HashMap(); + private XMLConfiguration _testConfiguration = new XMLConfiguration(); + protected static final String INDEX = "index"; + /** * Some tests are excluded when the property test.excludes is set to true. * An exclusion list is either a file (prop test.excludesfile) which contains one test name @@ -147,6 +155,7 @@ public class QpidTestCase extends TestCase private static final String BROKER_LANGUAGE = "broker.language"; private static final String BROKER = "broker"; private static final String BROKER_CLEAN = "broker.clean"; + private static final String BROKER_CLEAN_BETWEEN_TESTS = "broker.clean.between.tests"; private static final String BROKER_VERSION = "broker.version"; protected static final String BROKER_READY = "broker.ready"; private static final String BROKER_STOPPED = "broker.stopped"; @@ -169,6 +178,7 @@ public class QpidTestCase extends TestCase protected String _brokerLanguage = System.getProperty(BROKER_LANGUAGE, JAVA); protected String _broker = System.getProperty(BROKER, VM); private String _brokerClean = System.getProperty(BROKER_CLEAN, null); + private Boolean _brokerCleanBetweenTests = Boolean.getBoolean(BROKER_CLEAN_BETWEEN_TESTS); private String _brokerVersion = System.getProperty(BROKER_VERSION, VERSION_08); private String _output = System.getProperty(TEST_OUTPUT); @@ -177,7 +187,7 @@ public class QpidTestCase extends TestCase private Map _brokers = new HashMap(); private InitialContext _initialContext; - private AMQConnectionFactory _connectionFactory; + protected AMQConnectionFactory _connectionFactory; private String _testName; @@ -235,6 +245,19 @@ public class QpidTestCase extends TestCase { _logger.error("exception stopping broker", e); } + + if(_brokerCleanBetweenTests) + { + try + { + cleanBroker(); + } + catch (Exception e) + { + _logger.error("exception cleaning up broker", e); + } + } + _logger.info("========== stop " + _testName + " =========="); if (redirected) @@ -451,6 +474,15 @@ public class QpidTestCase extends TestCase env.put("QPID_PNAME", "-DPNAME=QPBRKR -DTNAME=\"" + _testName + "\""); env.put("QPID_WORK", System.getProperty("QPID_WORK")); + + // Use the environment variable to set amqj.logging.level for the broker + // The value used is a 'server' value in the test configuration to + // allow a differentiation between the client and broker logging levels. + if (System.getProperty("amqj.server.logging.level") != null) + { + setBrokerEnvironment("AMQJ_LOGGING_LEVEL", System.getProperty("amqj.server.logging.level")); + } + // Add all the environment settings the test requested if (!_env.isEmpty()) { @@ -460,13 +492,27 @@ public class QpidTestCase extends TestCase } } + + // Add default test logging levels that are used by the log4j-test + // Use the convenience methods to push the current logging setting + // in to the external broker's QPID_OPTS string. + if (System.getProperty("amqj.protocol.logging.level") != null) + { + setSystemProperty("amqj.protocol.logging.level"); + } + if (System.getProperty("root.logging.level") != null) + { + setSystemProperty("root.logging.level"); + } + + String QPID_OPTS = " "; // Add all the specified system properties to QPID_OPTS - if (!_setProperties.isEmpty()) + if (!_propertiesSetForBroker.isEmpty()) { - for (String key : _setProperties.keySet()) + for (String key : _propertiesSetForBroker.keySet()) { - QPID_OPTS += "-D" + key + "=" + System.getProperty(key) + " "; + QPID_OPTS += "-D" + key + "=" + _propertiesSetForBroker.get(key) + " "; } if (env.containsKey("QPID_OPTS")) @@ -489,7 +535,7 @@ public class QpidTestCase extends TestCase if (!p.await(30, TimeUnit.SECONDS)) { - _logger.info("broker failed to become ready:" + p.getStopLine()); + _logger.info("broker failed to become ready (" + p.ready + "):" + p.getStopLine()); //Ensure broker has stopped process.destroy(); cleanBroker(); @@ -666,29 +712,88 @@ public class QpidTestCase extends TestCase _testConfiguration.setProperty(property, value); } + /** + * Set a System property that is to be applied only to the external test + * broker. + * + * This is a convenience method to enable the setting of a -Dproperty=value + * entry in QPID_OPTS + * + * This is only useful for the External Java Broker tests. + * + * @param property the property name + * @param value the value to set the property to + */ + protected void setBrokerOnlySystemProperty(String property, String value) + { + if (!_propertiesSetForBroker.containsKey(property)) + { + _propertiesSetForBroker.put(property, value); + } + + } + + /** + * Set a System (-D) property for this test run. + * + * This convenience method copies the current VMs System Property + * for the external VM Broker. + * + * @param property the System property to set + */ + protected void setSystemProperty(String property) + { + setSystemProperty(property, System.getProperty(property)); + } + /** * Set a System property for the duration of this test. * * When the test run is complete the value will be reverted. * + * The values set using this method will also be propogated to the external + * Java Broker via a -D value defined in QPID_OPTS. + * + * If the value should not be set on the broker then use + * setTestClientSystemProperty(). + * * @param property the property to set * @param value the new value to use */ protected void setSystemProperty(String property, String value) { - if (!_setProperties.containsKey(property)) + // Record the value for the external broker + _propertiesSetForBroker.put(property, value); + + //Set the value for the test client vm aswell. + setTestClientSystemProperty(property, value); + } + + /** + * Set a System (-D) property for the external Broker of this test. + * + * @param property The property to set + * @param value the value to set it to. + */ + protected void setTestClientSystemProperty(String property, String value) + { + if (!_propertiesSetForTestOnly.containsKey(property)) { - _setProperties.put(property, System.getProperty(property)); - } + // Record the current value so we can revert it later. + _propertiesSetForTestOnly.put(property, System.getProperty(property)); + } System.setProperty(property, value); } + /** + * Restore the System property values that were set before this test run. + */ protected void revertSystemProperties() { - for (String key : _setProperties.keySet()) + for (String key : _propertiesSetForTestOnly.keySet()) { - String value = _setProperties.get(key); + String value = _propertiesSetForTestOnly.get(key); if (value != null) { System.setProperty(key, value); @@ -698,6 +803,12 @@ public class QpidTestCase extends TestCase System.clearProperty(key); } } + + _propertiesSetForTestOnly.clear(); + + // We don't change the current VMs settings for Broker only properties + // so we can just clear this map + _propertiesSetForBroker.clear(); } /** @@ -711,6 +822,40 @@ public class QpidTestCase extends TestCase _env.put(property, value); } + /** + * Adjust the VMs Log4j Settings just for this test run + * + * @param logger the logger to change + * @param level the level to set + */ + protected void setLoggerLevel(org.apache.log4j.Logger logger, Level level) + { + assertNotNull("Cannot set level of null logger", logger); + assertNotNull("Cannot set Logger("+logger.getName()+") to null level.",level); + + if (!_loggerLevelSetForTest.containsKey(logger)) + { + // Record the current value so we can revert it later. + _loggerLevelSetForTest.put(logger, logger.getLevel()); + } + + logger.setLevel(level); + } + + /** + * Restore the logging levels defined by this test. + */ + protected void revertLoggingLevels() + { + for (org.apache.log4j.Logger logger : _loggerLevelSetForTest.keySet()) + { + logger.setLevel(_loggerLevelSetForTest.get(logger)); + } + + _loggerLevelSetForTest.clear(); + + } + /** * Check whether the broker is an 0.8 * @@ -786,7 +931,7 @@ public class QpidTestCase extends TestCase { if (Boolean.getBoolean("profile.use_ssl")) { - _connectionFactory = getConnectionFactory("ssl"); + _connectionFactory = getConnectionFactory("default.ssl"); } else { @@ -876,15 +1021,32 @@ public class QpidTestCase extends TestCase return getClass().getSimpleName() + "-" + getName(); } + /** + * Return a Queue specific for this test. + * Uses getTestQueueName() as the name of the queue + * @return + */ + public Queue getTestQueue() + { + return new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME, getTestQueueName()); + } + + protected void tearDown() throws java.lang.Exception { - // close all the connections used by this test. - for (Connection c : _connections) + try { - c.close(); + // close all the connections used by this test. + for (Connection c : _connections) + { + c.close(); + } + } + finally{ + // Ensure any problems with close does not interfer with property resets + revertSystemProperties(); + revertLoggingLevels(); } - - revertSystemProperties(); } /** @@ -921,17 +1083,23 @@ public class QpidTestCase extends TestCase public List sendMessage(Session session, Destination destination, int count) throws Exception { - return sendMessage(session, destination, count, 0); + return sendMessage(session, destination, count, 0, 0); } public List sendMessage(Session session, Destination destination, int count, int batchSize) throws Exception + { + return sendMessage(session, destination, count, 0, batchSize); + } + + public List sendMessage(Session session, Destination destination, + int count, int offset, int batchSize) throws Exception { List messages = new ArrayList(count); MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < count; i++) + for (int i = offset; i < (count + offset); i++) { Message next = createNextMessage(session, i); @@ -950,8 +1118,11 @@ public class QpidTestCase extends TestCase } // Ensure we commit the last messages - if (session.getTransacted() && (batchSize > 0) && - (count / batchSize != 0)) + // Commit the session if we are transacted and + // we have no batchSize or + // our count is not divible by batchSize. + if (session.getTransacted() && + ( batchSize == 0 || count % batchSize != 0)) { session.commit(); } @@ -961,7 +1132,11 @@ public class QpidTestCase extends TestCase public Message createNextMessage(Session session, int msgCount) throws JMSException { - return session.createMessage(); + Message message = session.createMessage(); + message.setIntProperty(INDEX, msgCount); + + return message; + } public ConnectionURL getConnectionURL() throws NamingException -- cgit v1.2.1 From dffa942a2be4c0721e6ebce2c7a9203f4c83a41b Mon Sep 17 00:00:00 2001 From: Aidan Skinner Date: Wed, 14 Oct 2009 21:26:25 +0000 Subject: Merge from trunk git-svn-id: https://svn.apache.org/repos/asf/qpid/branches/java-network-refactor@825292 13f79535-47bb-0310-9956-ffa450edef68 --- .../MessageDisappearWithIOExceptionTest.java | 23 ++- .../qpid/server/security/acl/SimpleACLTest.java | 171 +++++++++++++++++++++ .../ack/AcknowledgeAfterFailoverOnMessageTest.java | 6 +- .../unit/ack/AcknowledgeAfterFailoverTest.java | 2 +- .../test/unit/ack/AcknowledgeOnMessageTest.java | 33 ++-- 5 files changed, 215 insertions(+), 20 deletions(-) (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/failover/MessageDisappearWithIOExceptionTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/failover/MessageDisappearWithIOExceptionTest.java index f1a1c1a9a8..e507ebc534 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/server/failover/MessageDisappearWithIOExceptionTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/failover/MessageDisappearWithIOExceptionTest.java @@ -179,9 +179,16 @@ public class MessageDisappearWithIOExceptionTest extends FailoverBaseCase implem messages.remove(0).getIntProperty("count"), received.getIntProperty("count")); - // Allow ack to be sent to broker, by performing a synchronous command - // along the session. -// _session.createConsumer(_session.createTemporaryQueue()).close(); + // When the Exception is received by the underlying IO layer it will + // initiate failover. The first step of which is to ensure that the + // existing conection is closed. So in this situation the connection + // will be flushed casuing the above ACK to be sent to the broker. + // + // That said: + // when the socket close is detected on the server it will rise up the + // Mina filter chain and interrupt processing. + // this has been raised as QPID-2138 + _session.createConsumer(_session.createTemporaryQueue()).close(); //Retain IO Layer AMQProtocolSession protocolSession = _connection.getProtocolHandler().getProtocolSession(); @@ -260,8 +267,14 @@ public class MessageDisappearWithIOExceptionTest extends FailoverBaseCase implem private void initialiseConnection() throws Exception { - //Create Connection - _connection = (AMQConnection) getConnection(); + //Create Connection using the default connection URL. i.e. not the Failover URL that would be used by default + _connection = (AMQConnection) getConnection(getConnectionFactory("default").getConnectionURL()); + // The default connection does not have any retries configured so + // Allow this connection to retry so that we can block on the failover. + // The alternative would be to use the getConnection() default. However, + // this would add additional complexity in the logging as a second + // broker is defined in that url. We do not need it for this test. + _connection.getFailoverPolicy().getCurrentMethod().setRetries(1); _connection.setConnectionListener(this); _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE); diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java index 3e5470d5cb..7a7d7f646e 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/server/security/acl/SimpleACLTest.java @@ -147,10 +147,23 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E setUpACLTest(); + //QPID-2081: use a latch to sync on exception causing connection close, to work + //around the connection close race during tearDown() causing sporadic failures + final CountDownLatch exceptionReceived = new CountDownLatch(1); + try { Connection conn = getConnection("guest", "guest"); + conn.setExceptionListener(new ExceptionListener() + { + public void onException(JMSException e) + { + exceptionReceived.countDown(); + } + }); + + Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); conn.start(); @@ -166,6 +179,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E assertNotNull("There was no liked exception", cause); assertEquals("Wrong linked exception type", AMQAuthenticationException.class, cause.getClass()); assertEquals("Incorrect error code received", 403, ((AMQAuthenticationException) cause).getErrorCode().getCode()); + + //use the latch to ensure the control thread waits long enough for the exception thread + //to have done enough to mark the connection closed before teardown commences + assertTrue("Timed out waiting for conneciton to report close", + exceptionReceived.await(2, TimeUnit.SECONDS)); } } @@ -195,6 +213,10 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E { setUpACLTest(); + //QPID-2081: use a latch to sync on exception causing connection close, to work + //around the connection close race during tearDown() causing sporadic failures + final CountDownLatch exceptionReceived = new CountDownLatch(1); + try { Connection conn = getConnection("client", "guest"); @@ -202,6 +224,14 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E //Prevent Failover ((AMQConnection) conn).setConnectionListener(this); + conn.setExceptionListener(new ExceptionListener() + { + public void onException(JMSException e) + { + exceptionReceived.countDown(); + } + }); + Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); conn.start(); @@ -217,6 +247,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E assertNotNull("There was no liked exception", cause); assertEquals("Wrong linked exception type", AMQAuthenticationException.class, cause.getClass()); assertEquals("Incorrect error code received", 403, ((AMQAuthenticationException) cause).getErrorCode().getCode()); + + //use the latch to ensure the control thread waits long enough for the exception thread + //to have done enough to mark the connection closed before teardown commences + assertTrue("Timed out waiting for conneciton to report close", + exceptionReceived.await(2, TimeUnit.SECONDS)); } } @@ -248,6 +283,10 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E { setUpACLTest(); + //QPID-2081: use a latch to sync on exception causing connection close, to work + //around the connection close race during tearDown() causing sporadic failures + final CountDownLatch exceptionReceived = new CountDownLatch(1); + try { Connection conn = getConnection("client", "guest"); @@ -256,6 +295,14 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E conn.start(); + conn.setExceptionListener(new ExceptionListener() + { + public void onException(JMSException e) + { + exceptionReceived.countDown(); + } + }); + //Create a Named Queue ((AMQSession) sesh).createQueue(new AMQShortString("IllegalQueue"), false, false, false); @@ -266,6 +313,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E { amqe.printStackTrace(); assertEquals("Incorrect error code thrown", 403, ((AMQAuthenticationException) amqe).getErrorCode().getCode()); + + //use the latch to ensure the control thread waits long enough for the exception thread + //to have done enough to mark the connection closed before teardown commences + assertTrue("Timed out waiting for conneciton to report close", + exceptionReceived.await(2, TimeUnit.SECONDS)); } } @@ -334,11 +386,23 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E { setUpACLTest(); + //QPID-2081: use a latch to sync on exception causing connection close, to work + //around the connection close race during tearDown() causing sporadic failures + final CountDownLatch exceptionReceived = new CountDownLatch(1); + try { Connection conn = getConnection("client", "guest"); ((AMQConnection) conn).setConnectionListener(this); + + conn.setExceptionListener(new ExceptionListener() + { + public void onException(JMSException e) + { + exceptionReceived.countDown(); + } + }); Session session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE); @@ -370,6 +434,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E foundCorrectException = true; } } + + //use the latch to ensure the control thread waits long enough for the exception thread + //to have done enough to mark the connection closed before teardown commences + assertTrue("Timed out waiting for conneciton to report close", + exceptionReceived.await(2, TimeUnit.SECONDS)); } assertTrue("Did not get AMQAuthenticationException thrown", foundCorrectException); } @@ -400,10 +469,22 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E { setUpACLTest(); + //QPID-2081: use a latch to sync on exception causing connection close, to work + //around the connection close race during tearDown() causing sporadic failures + final CountDownLatch exceptionReceived = new CountDownLatch(1); + try { Connection conn = getConnection("client", "guest"); + conn.setExceptionListener(new ExceptionListener() + { + public void onException(JMSException e) + { + exceptionReceived.countDown(); + } + }); + Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); conn.start(); @@ -420,6 +501,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E assertNotNull("There was no liked exception", cause); assertEquals("Wrong linked exception type", AMQAuthenticationException.class, cause.getClass()); assertEquals("Incorrect error code received", 403, ((AMQAuthenticationException) cause).getErrorCode().getCode()); + + //use the latch to ensure the control thread waits long enough for the exception thread + //to have done enough to mark the connection closed before teardown commences + assertTrue("Timed out waiting for conneciton to report close", + exceptionReceived.await(2, TimeUnit.SECONDS)); } } @@ -427,10 +513,22 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E { setUpACLTest(); + //QPID-2081: use a latch to sync on exception causing connection close, to work + //around the connection close race during tearDown() causing sporadic failures + final CountDownLatch exceptionReceived = new CountDownLatch(1); + try { Connection conn = getConnection("server", "guest"); + conn.setExceptionListener(new ExceptionListener() + { + public void onException(JMSException e) + { + exceptionReceived.countDown(); + } + }); + Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); conn.start(); @@ -446,6 +544,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E assertNotNull("There was no liked exception", cause); assertEquals("Wrong linked exception type", AMQAuthenticationException.class, cause.getClass()); assertEquals("Incorrect error code received", 403, ((AMQAuthenticationException) cause).getErrorCode().getCode()); + + //use the latch to ensure the control thread waits long enough for the exception thread + //to have done enough to mark the connection closed before teardown commences + assertTrue("Timed out waiting for conneciton to report close", + exceptionReceived.await(2, TimeUnit.SECONDS)); } } @@ -487,10 +590,22 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E { setUpACLTest(); + //QPID-2081: use a latch to sync on exception causing connection close, to work + //around the connection close race during tearDown() causing sporadic failures + final CountDownLatch exceptionReceived = new CountDownLatch(1); + try { Connection conn = getConnection("server", "guest"); + conn.setExceptionListener(new ExceptionListener() + { + public void onException(JMSException e) + { + exceptionReceived.countDown(); + } + }); + Session sesh = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); conn.start(); @@ -504,6 +619,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E catch (AMQAuthenticationException amqe) { assertEquals("Incorrect error code thrown", 403, amqe.getErrorCode().getCode()); + + //use the latch to ensure the control thread waits long enough for the exception thread + //to have done enough to mark the connection closed before teardown commences + assertTrue("Timed out waiting for conneciton to report close", + exceptionReceived.await(2, TimeUnit.SECONDS)); } } @@ -511,10 +631,22 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E { setUpACLTest(); + //QPID-2081: use a latch to sync on exception causing connection close, to work + //around the connection close race during tearDown() causing sporadic failures + final CountDownLatch exceptionReceived = new CountDownLatch(1); + try { Connection conn = getConnection("server", "guest"); + conn.setExceptionListener(new ExceptionListener() + { + public void onException(JMSException e) + { + exceptionReceived.countDown(); + } + }); + Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); conn.start(); @@ -531,6 +663,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E assertNotNull("There was no liked exception", cause); assertEquals("Wrong linked exception type", AMQAuthenticationException.class, cause.getClass()); assertEquals("Incorrect error code received", 403, ((AMQAuthenticationException) cause).getErrorCode().getCode()); + + //use the latch to ensure the control thread waits long enough for the exception thread + //to have done enough to mark the connection closed before teardown commences + assertTrue("Timed out waiting for conneciton to report close", + exceptionReceived.await(2, TimeUnit.SECONDS)); } } @@ -538,11 +675,23 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E { setUpACLTest(); + //QPID-2081: use a latch to sync on exception causing connection close, to work + //around the connection close race during tearDown() causing sporadic failures + final CountDownLatch exceptionReceived = new CountDownLatch(1); + Connection connection = null; try { connection = getConnection("server", "guest"); + connection.setExceptionListener(new ExceptionListener() + { + public void onException(JMSException e) + { + exceptionReceived.countDown(); + } + }); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); @@ -556,6 +705,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E catch (AMQAuthenticationException amqe) { assertEquals("Incorrect error code thrown", 403, amqe.getErrorCode().getCode()); + + //use the latch to ensure the control thread waits long enough for the exception thread + //to have done enough to mark the connection closed before teardown commences + assertTrue("Timed out waiting for conneciton to report close", + exceptionReceived.await(2, TimeUnit.SECONDS)); } } @@ -653,9 +807,21 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E { setUpACLTest(); + //QPID-2081: use a latch to sync on exception causing connection close, to work + //around the connection close race during tearDown() causing sporadic failures + final CountDownLatch exceptionReceived = new CountDownLatch(1); + try { Connection conn = getConnection("server", "guest"); + + conn.setExceptionListener(new ExceptionListener() + { + public void onException(JMSException e) + { + exceptionReceived.countDown(); + } + }); ((AMQConnection) conn).setConnectionListener(this); @@ -699,6 +865,11 @@ public class SimpleACLTest extends QpidTestCase implements ConnectionListener, E assertEquals("Incorrect exception", AMQAuthenticationException.class, cause.getClass()); assertEquals("Incorrect error code thrown", 403, ((AMQAuthenticationException) cause).getErrorCode().getCode()); } + + //use the latch to ensure the control thread waits long enough for the exception thread + //to have done enough to mark the connection closed before teardown commences + assertTrue("Timed out waiting for conneciton to report close", + exceptionReceived.await(2, TimeUnit.SECONDS)); } } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverOnMessageTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverOnMessageTest.java index f22a405fc3..7c5db290c4 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverOnMessageTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverOnMessageTest.java @@ -155,7 +155,7 @@ public class AcknowledgeAfterFailoverOnMessageTest extends AcknowledgeOnMessageT public void onMessage(Message message) { // Stop processing if we have an error and had to stop running. - if (_receviedAll.getCount() == 0) + if (_receivedAll.getCount() == 0) { _logger.debug("Dumping msgs due to error(" + _causeOfFailure.get().getMessage() + "):" + message); return; @@ -191,7 +191,7 @@ public class AcknowledgeAfterFailoverOnMessageTest extends AcknowledgeOnMessageT // Acknowledge the first message if we are now on the cleaned pass if (cleaned) { - _receviedAll.countDown(); + _receivedAll.countDown(); } return; @@ -234,7 +234,7 @@ public class AcknowledgeAfterFailoverOnMessageTest extends AcknowledgeOnMessageT // this will then trigger test teardown. if (cleaned) { - _receviedAll.countDown(); + _receivedAll.countDown(); } //Reset message count so we can try again. diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverTest.java index eb36522fac..ae7e30c231 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverTest.java @@ -299,7 +299,7 @@ public class AcknowledgeAfterFailoverTest extends AcknowledgeTest implements Con } catch (InterruptedException e) { - fail("Failover was interuppted"); + fail("Failover was interrupted"); } } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeOnMessageTest.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeOnMessageTest.java index 4254727d36..a2703be298 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeOnMessageTest.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeOnMessageTest.java @@ -34,7 +34,7 @@ import java.util.concurrent.atomic.AtomicReference; public class AcknowledgeOnMessageTest extends AcknowledgeTest implements MessageListener { - protected CountDownLatch _receviedAll; + protected CountDownLatch _receivedAll; protected AtomicReference _causeOfFailure = new AtomicReference(null); @Override @@ -46,7 +46,7 @@ public class AcknowledgeOnMessageTest extends AcknowledgeTest implements Message @Override public void init(boolean transacted, int mode) throws Exception { - _receviedAll = new CountDownLatch(NUM_MESSAGES); + _receivedAll = new CountDownLatch(NUM_MESSAGES); super.init(transacted, mode); _consumer.setMessageListener(this); @@ -64,26 +64,36 @@ public class AcknowledgeOnMessageTest extends AcknowledgeTest implements Message _connection.start(); - int lastCount = (int) _receviedAll.getCount(); + // Set the lastCount to NUM_MESSAGES, this ensures that the compare + // against the receviedAll count is accurate. + int lastCount = NUM_MESSAGES; - boolean complete = _receviedAll.await(5000L, TimeUnit.MILLISECONDS); + // Wait for messages to arrive + boolean complete = _receivedAll.await(5000L, TimeUnit.MILLISECONDS); + // If the messasges haven't arrived while (!complete) { - int currentCount = (int) _receviedAll.getCount(); + // Check how many we have received + int currentCount = (int) _receivedAll.getCount(); // make sure we have received a message in the last cycle. if (lastCount == currentCount) { + // If we didn't receive any messages then stop. + // Something must have gone wrong. + System.err.println("Giving up waiting as we didn't receive anything."); break; } // Remember the currentCount as the lastCount for the next cycle. // so we can exit if things get locked up. lastCount = currentCount; - complete = _receviedAll.await(5000L, TimeUnit.MILLISECONDS); + // Wait again for messages to arrive. + complete = _receivedAll.await(5000L, TimeUnit.MILLISECONDS); } + // If we failed to receive all the messages then fail the test. if (!complete) { // Check to see if we ended due to an exception in the onMessage handler @@ -95,10 +105,11 @@ public class AcknowledgeOnMessageTest extends AcknowledgeTest implements Message } else { - fail("All messages not received missing:" + _receviedAll.getCount() + "/" + NUM_MESSAGES); + fail("All messages not received missing:" + _receivedAll.getCount() + "/" + NUM_MESSAGES); } } + // Even if we received all the messages. // Check to see if we ended due to an exception in the onMessage handler Exception cause = _causeOfFailure.get(); if (cause != null) @@ -131,7 +142,7 @@ public class AcknowledgeOnMessageTest extends AcknowledgeTest implements Message { try { - int count = NUM_MESSAGES - (int) _receviedAll.getCount(); + int count = NUM_MESSAGES - (int) _receivedAll.getCount(); assertEquals("Incorrect message received", count, message.getIntProperty(INDEX)); @@ -144,7 +155,7 @@ public class AcknowledgeOnMessageTest extends AcknowledgeTest implements Message doAcknowlegement(message); - _receviedAll.countDown(); + _receivedAll.countDown(); } catch (Exception e) { @@ -162,9 +173,9 @@ public class AcknowledgeOnMessageTest extends AcknowledgeTest implements Message { _causeOfFailure.set(e); // End the test. - while (_receviedAll.getCount() != 0) + while (_receivedAll.getCount() != 0) { - _receviedAll.countDown(); + _receivedAll.countDown(); } } } -- cgit v1.2.1 From db07194fdec1c2c27d9de2fdc881e5d8e7b3ead9 Mon Sep 17 00:00:00 2001 From: Robert Godfrey Date: Sun, 7 Dec 2014 10:54:59 +0000 Subject: QPID-6263 : [Java Broker] Remove knowledge of BrokerOptions from SystemConfig and simply use attributes instead git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1643660 13f79535-47bb-0310-9956-ffa450edef68 --- .../main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java index fb254f59ae..3d0fb90036 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java @@ -108,7 +108,7 @@ public class TestBrokerConfiguration final AbstractSystemConfig parentObject = new JsonSystemConfigImpl(taskExecutor, mock(EventLogger.class), mock(LogRecorder.class), - brokerOptions, + brokerOptions.convertToSystemConfigAttributes(), mock(BrokerShutdownProvider.class)); ConfiguredObjectRecordConverter converter = new ConfiguredObjectRecordConverter(BrokerModel.getInstance()); @@ -219,7 +219,7 @@ public class TestBrokerConfiguration final SystemConfig parentObject = configFactory.newInstance(_taskExecutor, mock(EventLogger.class), mock(LogRecorder.class), - brokerOptions, + brokerOptions.convertToSystemConfigAttributes(), mock(BrokerShutdownProvider.class)); parentObject.open(); -- cgit v1.2.1 From b1e8d83ef545719e5a39d50726d977b5f747a245 Mon Sep 17 00:00:00 2001 From: Robert Godfrey Date: Sun, 7 Dec 2014 21:19:21 +0000 Subject: QPID-6263 : [Java Broker] Move startup/recovery logic from server.Broker to SystemConfig git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1643719 13f79535-47bb-0310-9956-ffa450edef68 --- .../qpid/test/utils/TestBrokerConfiguration.java | 22 ++++++---------------- 1 file changed, 6 insertions(+), 16 deletions(-) (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java index 3d0fb90036..549edcd650 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java @@ -44,21 +44,7 @@ import org.apache.qpid.server.BrokerOptions; import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.logging.EventLogger; import org.apache.qpid.server.logging.LogRecorder; -import org.apache.qpid.server.model.AbstractSystemConfig; -import org.apache.qpid.server.model.AccessControlProvider; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerModel; -import org.apache.qpid.server.model.BrokerShutdownProvider; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.GroupProvider; -import org.apache.qpid.server.model.JsonSystemConfigImpl; -import org.apache.qpid.server.model.Plugin; -import org.apache.qpid.server.model.PreferencesProvider; -import org.apache.qpid.server.model.SystemConfig; -import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.model.VirtualHostAlias; -import org.apache.qpid.server.model.VirtualHostNode; +import org.apache.qpid.server.model.*; import org.apache.qpid.server.model.adapter.FileBasedGroupProvider; import org.apache.qpid.server.model.adapter.FileBasedGroupProviderImpl; import org.apache.qpid.server.plugin.PluggableFactoryLoader; @@ -216,10 +202,13 @@ public class TestBrokerConfiguration SystemConfigFactory configFactory = (new PluggableFactoryLoader<>(SystemConfigFactory.class)).get(_storeType); + Map attributes = new HashMap<>(brokerOptions.convertToSystemConfigAttributes()); + attributes.put(SystemConfig.STARTUP_LOGGED_TO_SYSTEM_OUT, false); + attributes.put(ConfiguredObject.DESIRED_STATE, State.QUIESCED); final SystemConfig parentObject = configFactory.newInstance(_taskExecutor, mock(EventLogger.class), mock(LogRecorder.class), - brokerOptions.convertToSystemConfigAttributes(), + attributes, mock(BrokerShutdownProvider.class)); parentObject.open(); @@ -252,6 +241,7 @@ public class TestBrokerConfiguration configurationStore.openConfigurationStore(parentObject,true,initialRecords.toArray(new ConfiguredObjectRecord[initialRecords.size()])); configurationStore.closeConfigurationStore(); + parentObject.close(); return true; } -- cgit v1.2.1 From fd6bd8b5dee6807e7890f4eda578a73b4b1bb4dc Mon Sep 17 00:00:00 2001 From: Alex Rudyy Date: Wed, 10 Dec 2014 17:34:24 +0000 Subject: QPID-6265: Change system tests to have one log per file configured using Log4j, simplify QBTC git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1644492 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpid/test/utils/BrokerHolder.java | 11 +- .../qpid/test/utils/InternalBrokerHolder.java | 22 +- .../java/org/apache/qpid/test/utils/Piper.java | 20 +- .../apache/qpid/test/utils/QpidBrokerTestCase.java | 406 +++++++-------------- .../qpid/test/utils/SpawnedBrokerHolder.java | 207 ++++++++++- .../org/apache/qpid/server/BrokerStartupTest.java | 4 +- .../qpid/server/logging/BrokerLoggingTest.java | 119 +----- .../server/security/acl/AbstractACLTestCase.java | 2 +- .../management/jmx/LoggingManagementTest.java | 20 +- .../management/jmx/ManagementLoggingTest.java | 8 +- .../apache/qpid/systest/rest/KeyStoreRestTest.java | 4 +- .../apache/qpid/systest/rest/LogViewerTest.java | 49 ++- .../qpid/systest/rest/TrustStoreRestTest.java | 4 +- 13 files changed, 426 insertions(+), 450 deletions(-) (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/BrokerHolder.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/BrokerHolder.java index 3af57327d2..4537d1a678 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/BrokerHolder.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/BrokerHolder.java @@ -20,10 +20,19 @@ */ package org.apache.qpid.test.utils; +import org.apache.qpid.server.BrokerOptions; + public interface BrokerHolder { - String getWorkingDirectory(); + public void start(BrokerOptions options) throws Exception; void shutdown(); void kill(); String dumpThreads(); + + enum BrokerType + { + EXTERNAL /** Test case relies on a Broker started independently of the test-suite */, + INTERNAL /** Test case starts an embedded broker within this JVM */, + SPAWNED /** Test case spawns a new broker as a separate process */ + } } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/InternalBrokerHolder.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/InternalBrokerHolder.java index f980453d49..a76f79f8b0 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/InternalBrokerHolder.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/InternalBrokerHolder.java @@ -21,12 +21,13 @@ package org.apache.qpid.test.utils; import java.security.PrivilegedAction; +import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.apache.qpid.server.Broker; -import org.apache.qpid.server.security.auth.TaskPrincipal; +import org.apache.qpid.server.BrokerOptions; import org.apache.qpid.server.security.SecurityManager; import javax.security.auth.Subject; @@ -35,27 +36,22 @@ public class InternalBrokerHolder implements BrokerHolder { private static final Logger LOGGER = Logger.getLogger(InternalBrokerHolder.class); - private final Broker _broker; - private final String _workingDirectory; + private Broker _broker; private Set _portsUsedByBroker; - public InternalBrokerHolder(final Broker broker, String workingDirectory, Set portsUsedByBroker) + public InternalBrokerHolder(Set portsUsedByBroker) { - if(broker == null) - { - throw new IllegalArgumentException("Broker must not be null"); - } - - _broker = broker; - _workingDirectory = workingDirectory; _portsUsedByBroker = portsUsedByBroker; } @Override - public String getWorkingDirectory() + public void start(BrokerOptions options) throws Exception { - return _workingDirectory; + LOGGER.info("Starting internal broker (same JVM)"); + + _broker = new Broker(); + _broker.startup(options); } public void shutdown() diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/Piper.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/Piper.java index 9413e38606..12be233c35 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/Piper.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/Piper.java @@ -35,27 +35,21 @@ public final class Piper extends Thread private static final Logger LOGGER = Logger.getLogger(Piper.class); private final BufferedReader _in; - private final PrintStream _out; + private final Logger _out; private final String _ready; private final CountDownLatch _latch; private final String _stopped; - private final String _prefix; private volatile boolean _seenReady; private volatile String _stopLine; - public Piper(InputStream in, PrintStream out, String ready, String stopped) - { - this(in, out, ready, stopped, null); - } - - public Piper(InputStream in, PrintStream out, String ready, String stopped, String prefix) + public Piper(InputStream in, String ready, String stopped, String threadName, String loggerName) { + super(threadName); _in = new BufferedReader(new InputStreamReader(in)); - _out = out; + _out = Logger.getLogger(loggerName); _ready = ready; _stopped = stopped; _seenReady = false; - _prefix = prefix; if (this._ready != null && !this._ready.equals("")) { @@ -87,11 +81,7 @@ public final class Piper extends Thread String line; while ((line = _in.readLine()) != null) { - if (_prefix != null) - { - line = _prefix + line; - } - _out.println(line); + _out.info(line); if (_latch != null && line.contains(_ready)) { diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java index 369a76a6c6..9a3308603b 100755 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java @@ -18,9 +18,7 @@ package org.apache.qpid.test.utils; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -28,7 +26,6 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.concurrent.TimeUnit; import javax.jms.BytesMessage; import javax.jms.Connection; @@ -48,8 +45,10 @@ import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; -import org.apache.commons.lang.StringUtils; +import org.apache.log4j.FileAppender; +import org.apache.log4j.LogManager; import org.apache.log4j.Logger; +import org.apache.log4j.xml.DOMConfigurator; import org.apache.qpid.AMQException; import org.apache.qpid.client.AMQConnectionFactory; @@ -60,7 +59,6 @@ import org.apache.qpid.exchange.ExchangeDefaults; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.jms.BrokerDetails; import org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.server.Broker; import org.apache.qpid.server.BrokerOptions; import org.apache.qpid.server.configuration.BrokerProperties; import org.apache.qpid.server.configuration.updater.TaskExecutor; @@ -83,19 +81,11 @@ public class QpidBrokerTestCase extends QpidTestCase { private TaskExecutor _taskExecutor; - public enum BrokerType - { - EXTERNAL /** Test case relies on a Broker started independently of the test-suite */, - INTERNAL /** Test case starts an embedded broker within this JVM */, - SPAWNED /** Test case spawns a new broker as a separate process */ - } - public static final String GUEST_USERNAME = "guest"; public static final String GUEST_PASSWORD = "guest"; - protected final static String QpidHome = System.getProperty("QPID_HOME"); private final File _configFile = new File(System.getProperty("broker.config")); - private File _logConfigFile; + private File _spawnedBrokerLogConfigFile; protected final String _brokerStoreType = System.getProperty("broker.config-store-type", "JSON"); protected static final Logger _logger = Logger.getLogger(QpidBrokerTestCase.class); protected static final int LOGMONITOR_TIMEOUT = 5000; @@ -128,11 +118,7 @@ public class QpidBrokerTestCase extends QpidTestCase private static final String BROKER_COMMAND_PLATFORM = "broker.command." + SystemUtils.getOSConfigSuffix(); private static final String BROKER_CLEAN_BETWEEN_TESTS = "broker.clean.between.tests"; private static final String BROKER_VERSION = "broker.version"; - protected static final String BROKER_READY = "broker.ready"; - private static final String BROKER_STOPPED = "broker.stopped"; private static final String TEST_OUTPUT = "test.output"; - private static final String BROKER_LOG_INTERLEAVE = "broker.log.interleave"; - private static final String BROKER_LOG_PREFIX = "broker.log.prefix"; private static final String BROKER_PERSITENT = "broker.persistent"; public static final String PROFILE_USE_SSL = "profile.use_ssl"; @@ -141,41 +127,30 @@ public class QpidBrokerTestCase extends QpidTestCase public static final int DEFAULT_JMXPORT_REGISTRYSERVER = 8999; public static final int JMXPORT_CONNECTORSERVER_OFFSET = 100; public static final int DEFAULT_HTTP_MANAGEMENT_PORT_VALUE = 8080; - public static final int DEFAULT_HTTPS_MANAGEMENT_PORT_VALUE = 8443; public static final String TEST_AMQP_PORT_PROTOCOLS_PROPERTY="test.amqp_port_protocols"; // values protected static final String JAVA = "java"; - protected static final String CPP = "cpp"; - - protected static final String QPID_HOME = "QPID_HOME"; public static final int DEFAULT_PORT = Integer.getInteger("test.port", DEFAULT_PORT_VALUE); public static final int FAILING_PORT = Integer.parseInt(System.getProperty("test.port.alt")); public static final int DEFAULT_MANAGEMENT_PORT = Integer.getInteger("test.mport", DEFAULT_JMXPORT_REGISTRYSERVER); public static final int DEFAULT_HTTP_MANAGEMENT_PORT = Integer.getInteger("test.hport", DEFAULT_HTTP_MANAGEMENT_PORT_VALUE); - public static final int DEFAULT_HTTPS_MANAGEMENT_PORT = Integer.getInteger("test.hsport", DEFAULT_HTTPS_MANAGEMENT_PORT_VALUE); public static final int DEFAULT_SSL_PORT = Integer.getInteger("test.port.ssl", DEFAULT_SSL_PORT_VALUE); protected String _brokerLanguage = System.getProperty(BROKER_LANGUAGE, JAVA); - protected BrokerType _brokerType = BrokerType.valueOf(System.getProperty(BROKER_TYPE, "").toUpperCase()); + protected BrokerHolder.BrokerType _brokerType = BrokerHolder.BrokerType.valueOf(System.getProperty(BROKER_TYPE, "").toUpperCase()); private static final String BROKER_COMMAND_TEMPLATE = System.getProperty(BROKER_COMMAND_PLATFORM, System.getProperty(BROKER_COMMAND)); - protected BrokerCommandHelper _brokerCommandHelper = new BrokerCommandHelper(BROKER_COMMAND_TEMPLATE); private Boolean _brokerCleanBetweenTests = Boolean.getBoolean(BROKER_CLEAN_BETWEEN_TESTS); private final Protocol _brokerProtocol = Protocol.valueOf("AMQP_" + System.getProperty(BROKER_VERSION, " ").substring(1)); protected String _output = System.getProperty(TEST_OUTPUT, System.getProperty("java.io.tmpdir")); protected Boolean _brokerPersistent = Boolean.getBoolean(BROKER_PERSITENT); - protected static String _brokerLogPrefix = System.getProperty(BROKER_LOG_PREFIX,"BROKER: "); - protected static boolean _interleaveBrokerLog = Boolean.valueOf(System.getProperty(BROKER_LOG_INTERLEAVE,"true")); - protected File _outputFile; - protected PrintStream _testcaseOutputStream; - protected Map _brokers = new HashMap(); protected InitialContext _initialContext; @@ -195,6 +170,8 @@ public class QpidBrokerTestCase extends QpidTestCase /** Size to create our message*/ private int _messageSize = DEFAULT_MESSAGE_SIZE; + private String _brokerCommandTemplate; + /** Type of message*/ protected enum MessageType { @@ -210,7 +187,8 @@ public class QpidBrokerTestCase extends QpidTestCase { super(); _brokerConfigurations = new HashMap(); - initialiseLogConfigFile(); + initialiseSpawnedBrokerLogConfigFile(); + _brokerCommandTemplate = BROKER_COMMAND_TEMPLATE; } public TestBrokerConfiguration getBrokerConfiguration(int port) @@ -259,12 +237,12 @@ public class QpidBrokerTestCase extends QpidTestCase return configuration; } - private void initialiseLogConfigFile() + private void initialiseSpawnedBrokerLogConfigFile() { - _logConfigFile = new File(LOG4J_CONFIG_FILE_PATH); - if(!_logConfigFile.exists()) + _spawnedBrokerLogConfigFile = new File(SPAWNED_BROKER_LOG4J_CONFIG_FILE_PATH); + if(!_spawnedBrokerLogConfigFile.exists()) { - throw new RuntimeException("Log config file " + _logConfigFile.getAbsolutePath() + " does not exist"); + throw new RuntimeException("Log config file " + _spawnedBrokerLogConfigFile.getAbsolutePath() + " does not exist"); } } @@ -276,36 +254,18 @@ public class QpidBrokerTestCase extends QpidTestCase @Override public void runBare() throws Throwable { - String qname = getClass().getName() + "." + getName(); - // Initialize this for each test run _env = new HashMap(); - PrintStream oldOut = System.out; - PrintStream oldErr = System.err; - PrintStream out = null; - PrintStream err = null; + // Log4j properties expects this to be set + System.setProperty("qpid.testMethod", "-" + getName()); + System.setProperty("qpid.testClass", getClass().getName()); - boolean redirected = _output != null && _output.length() > 0; - if (redirected) - { - _outputFile = new File(String.format("%s/TEST-%s.out", _output, qname)); - out = new PrintStream(new FileOutputStream(_outputFile), true); - err = new PrintStream(String.format("%s/TEST-%s.err", _output, qname)); + String log4jConfigFile = System.getProperty("log4j.configuration.file"); + DOMConfigurator.configure(log4jConfigFile); - System.setOut(out); - System.setErr(err); - - if (_interleaveBrokerLog) - { - _testcaseOutputStream = out; - } - else - { - _testcaseOutputStream = new PrintStream(new FileOutputStream(String - .format("%s/TEST-%s.broker.out", _output, qname)), true); - } - } + // get log file from file appender + _outputFile = new File(((FileAppender)LogManager.getRootLogger().getAllAppenders().nextElement()).getFile()); try { @@ -324,7 +284,7 @@ public class QpidBrokerTestCase extends QpidTestCase revertSystemProperties(); revertLoggingLevels(); - if(_brokerCleanBetweenTests) + if (_brokerCleanBetweenTests) { final String qpidWork = System.getProperty("QPID_WORK"); cleanBrokerWork(qpidWork); @@ -333,17 +293,7 @@ public class QpidBrokerTestCase extends QpidTestCase _logger.info("========== stop " + getTestName() + " =========="); - if (redirected) - { - System.setErr(oldErr); - System.setOut(oldOut); - err.close(); - out.close(); - if (!_interleaveBrokerLog) - { - _testcaseOutputStream.close(); - } - } + LogManager.resetConfiguration(); } } @@ -403,7 +353,7 @@ public class QpidBrokerTestCase extends QpidTestCase protected int getPort(int port) { - if (!_brokerType.equals(BrokerType.EXTERNAL)) + if (!_brokerType.equals(BrokerHolder.BrokerType.EXTERNAL)) { return port == 0 ? DEFAULT_PORT : port; } @@ -424,29 +374,34 @@ public class QpidBrokerTestCase extends QpidTestCase } public void startBroker(int port, boolean managementMode) throws Exception + { + startBroker(port, managementMode, null); + } + + public void startBroker(int port, boolean managementMode, String log4jFile) throws Exception { int actualPort = getPort(port); TestBrokerConfiguration configuration = getBrokerConfiguration(actualPort); - startBroker(actualPort, configuration, managementMode); + startBroker(actualPort, configuration, managementMode, log4jFile); } protected File getBrokerCommandLog4JFile() { - return _logConfigFile; + return _spawnedBrokerLogConfigFile; } protected void setBrokerCommandLog4JFile(File file) { - _logConfigFile = file; + _spawnedBrokerLogConfigFile = file; _logger.info("Modified log config file to: " + file); } - public void startBroker(int port, TestBrokerConfiguration testConfiguration) throws Exception + public void startBroker(int port, TestBrokerConfiguration testConfiguration, String log4jFile) throws Exception { - startBroker(port, testConfiguration, false); + startBroker(port, testConfiguration, false, log4jFile); } - public void startBroker(int port, TestBrokerConfiguration testConfiguration, boolean managementMode) throws Exception + protected void startBroker(int port, TestBrokerConfiguration testConfiguration, boolean managementMode, String log4jFile) throws Exception { port = getPort(port); @@ -455,181 +410,12 @@ public class QpidBrokerTestCase extends QpidTestCase throw new IllegalStateException("There is already an existing broker running on port " + port); } - Set portsUsedByBroker = guessAllPortsUsedByBroker(port); String testConfig = saveTestConfiguration(port, testConfiguration); - - if (_brokerType.equals(BrokerType.INTERNAL) && !existingInternalBroker()) - { - setSystemProperty(BrokerProperties.PROPERTY_USE_CUSTOM_RMI_SOCKET_FACTORY, "false"); - BrokerOptions options = new BrokerOptions(); - - options.setConfigurationStoreType(_brokerStoreType); - options.setConfigurationStoreLocation(testConfig); - options.setManagementMode(managementMode); - if (managementMode) - { - options.setManagementModePassword(MANAGEMENT_MODE_PASSWORD); - } - - //Set the log config file, relying on the log4j.configuration system property - //set on the JVM by the JUnit runner task in module.xml. - options.setLogConfigFileLocation(_logConfigFile.getAbsolutePath()); - - Broker broker = new Broker(); - _logger.info("Starting internal broker (same JVM)"); - broker.startup(options); - - _brokers.put(port, new InternalBrokerHolder(broker, System.getProperty("QPID_WORK"), portsUsedByBroker)); - } - else if (!_brokerType.equals(BrokerType.EXTERNAL)) - { - // Add the port to QPID_WORK to ensure unique working dirs for multi broker tests - final String qpidWork = getQpidWork(_brokerType, port); - - String[] cmd = _brokerCommandHelper.getBrokerCommand(port, testConfig, _brokerStoreType, _logConfigFile); - if (managementMode) - { - String[] newCmd = new String[cmd.length + 3]; - System.arraycopy(cmd, 0, newCmd, 0, cmd.length); - newCmd[cmd.length] = "-mm"; - newCmd[cmd.length + 1] = "-mmpass"; - newCmd[cmd.length + 2] = MANAGEMENT_MODE_PASSWORD; - cmd = newCmd; - } - _logger.info("Starting spawn broker using command: " + StringUtils.join(cmd, ' ')); - ProcessBuilder pb = new ProcessBuilder(cmd); - pb.redirectErrorStream(true); - Map processEnv = pb.environment(); - String qpidHome = System.getProperty(QPID_HOME); - processEnv.put(QPID_HOME, qpidHome); - //Augment Path with bin directory in QPID_HOME. - boolean foundPath = false; - final String pathEntry = qpidHome + File.separator + "bin"; - for(Map.Entry entry : processEnv.entrySet()) - { - if(entry.getKey().equalsIgnoreCase("path")) - { - entry.setValue(entry.getValue().concat(File.pathSeparator + pathEntry)); - foundPath = true; - } - } - if(!foundPath) - { - processEnv.put("PATH", pathEntry); - - } - //Add the test name to the broker run. - // DON'T change PNAME, qpid.stop needs this value. - processEnv.put("QPID_PNAME", "-DPNAME=QPBRKR -DTNAME=\"" + getTestName() + "\""); - processEnv.put("QPID_WORK", qpidWork); - - // Use the environment variable to set amqj.logging.level for the broker - // The value used is a 'server' value in the test configuration to - // allow a differentiation between the client and broker logging levels. - if (System.getProperty("amqj.server.logging.level") != null) - { - setBrokerEnvironment("AMQJ_LOGGING_LEVEL", System.getProperty("amqj.server.logging.level")); - } - - // Add all the environment settings the test requested - if (!_env.isEmpty()) - { - for (Map.Entry entry : _env.entrySet()) - { - processEnv.put(entry.getKey(), entry.getValue()); - } - } - - String qpidOpts = ""; - - // a synchronized hack to avoid adding into QPID_OPTS the values - // of JVM properties "test.virtualhosts" and "test.config" set by a concurrent startup process - synchronized (_propertiesSetForBroker) - { - // Add default test logging levels that are used by the log4j-test - // Use the convenience methods to push the current logging setting - // in to the external broker's QPID_OPTS string. - setSystemProperty("amqj.protocol.logging.level"); - setSystemProperty("root.logging.level"); - - setSystemProperty("test.port"); - setSystemProperty("test.mport"); - setSystemProperty("test.cport"); - setSystemProperty("test.hport"); - setSystemProperty("test.hsport"); - setSystemProperty("test.port.ssl"); - setSystemProperty("test.port.alt"); - setSystemProperty("test.port.alt.ssl"); - setSystemProperty("test.amqp_port_protocols"); - - setSystemProperty("virtualhostnode.type"); - setSystemProperty("virtualhostnode.context.blueprint"); - - // Add all the specified system properties to QPID_OPTS - if (!_propertiesSetForBroker.isEmpty()) - { - for (String key : _propertiesSetForBroker.keySet()) - { - qpidOpts += " -D" + key + "=" + _propertiesSetForBroker.get(key); - } - } - } - if (processEnv.containsKey("QPID_OPTS")) - { - qpidOpts = processEnv.get("QPID_OPTS") + qpidOpts; - } - processEnv.put("QPID_OPTS", qpidOpts); - - // cpp broker requires that the work directory is created - createBrokerWork(qpidWork); - - Process process = pb.start(); - - Piper p = new Piper(process.getInputStream(), - _testcaseOutputStream, - System.getProperty(BROKER_READY), - System.getProperty(BROKER_STOPPED), - _interleaveBrokerLog ? _brokerLogPrefix : null); - - p.start(); - StringBuilder cmdLine = new StringBuilder(cmd[0]); - for(int i = 1; i< cmd.length; i++) - { - cmdLine.append(' '); - cmdLine.append(cmd[i]); - } - - SpawnedBrokerHolder holder = new SpawnedBrokerHolder(process, qpidWork, portsUsedByBroker, cmdLine.toString()); - if (!p.await(30, TimeUnit.SECONDS)) - { - _logger.info("broker failed to become ready (" + p.getReady() + "):" + p.getStopLine()); - String threadDump = holder.dumpThreads(); - if (!threadDump.isEmpty()) - { - _logger.info("the result of a try to capture thread dump:" + threadDump); - } - //Ensure broker has stopped - process.destroy(); - cleanBrokerWork(qpidWork); - throw new RuntimeException("broker failed to become ready:" - + p.getStopLine()); - } - - try - { - //test that the broker is still running and hasn't exited unexpectedly - int exit = process.exitValue(); - _logger.info("broker aborted: " + exit); - cleanBrokerWork(qpidWork); - throw new RuntimeException("broker aborted: " + exit); - } - catch (IllegalThreadStateException e) - { - // this is expect if the broker started successfully - } - - _brokers.put(port, holder); - } + String log4jConfig = log4jFile == null ? getBrokerCommandLog4JFile().getAbsolutePath() : log4jFile; + BrokerOptions options = getBrokerOptions(managementMode, testConfig, log4jConfig, log4jFile == null); + BrokerHolder holder = new BrokerHolderFactory().create(_brokerType, port, this); + _brokers.put(port, holder); + holder.start(options); } private boolean existingInternalBroker() @@ -645,21 +431,6 @@ public class QpidBrokerTestCase extends QpidTestCase return false; } - private String getQpidWork(BrokerType broker, int port) - { - if (!broker.equals(BrokerType.EXTERNAL)) - { - return System.getProperty("QPID_WORK")+ "/" + port; - } - - return System.getProperty("QPID_WORK"); - } - - public String getTestConfigFile() - { - return getTestConfigFile(getPort()); - } - public String getTestConfigFile(int port) { return _output + File.separator + getTestQueueName() + "-" + port + "-config"; @@ -1035,7 +806,7 @@ public class QpidBrokerTestCase extends QpidTestCase protected boolean isInternalBroker() { - return _brokerType.equals(BrokerType.INTERNAL); + return _brokerType.equals(BrokerHolder.BrokerType.INTERNAL); } protected boolean isBrokerStorePersistent() @@ -1397,16 +1168,6 @@ public class QpidBrokerTestCase extends QpidTestCase return message; } - protected int getMessageSize() - { - return _messageSize; - } - - protected void setMessageSize(int byteSize) - { - _messageSize = byteSize; - } - public BrokerDetails getBroker() { try @@ -1453,4 +1214,91 @@ public class QpidBrokerTestCase extends QpidTestCase session.commit(); session.close(); } + + protected BrokerOptions getBrokerOptions( boolean managementMode, String testConfig, String log4jConfig, boolean skipLoggingConfiguration) + { + BrokerOptions options = new BrokerOptions(); + + options.setConfigurationStoreType(_brokerStoreType); + options.setConfigurationStoreLocation(testConfig); + options.setManagementMode(managementMode); + if (managementMode) + { + options.setManagementModePassword(MANAGEMENT_MODE_PASSWORD); + } + options.setSkipLoggingConfiguration(skipLoggingConfiguration); + options.setLogConfigFileLocation(log4jConfig); + options.setStartupLoggedToSystemOut(false); + return options; + } + + private Map getJvmProperties() + { + Map jvmOptions = new HashMap(); + synchronized (_propertiesSetForBroker) + { + jvmOptions.putAll(_propertiesSetForBroker); + + copySystemProperty("amqj.protocol.logging.level", jvmOptions); + copySystemProperty("root.logging.level", jvmOptions); + + copySystemProperty("test.port", jvmOptions); + copySystemProperty("test.mport", jvmOptions); + copySystemProperty("test.cport", jvmOptions); + copySystemProperty("test.hport", jvmOptions); + copySystemProperty("test.hsport", jvmOptions); + copySystemProperty("test.port.ssl", jvmOptions); + copySystemProperty("test.port.alt", jvmOptions); + copySystemProperty("test.port.alt.ssl", jvmOptions); + copySystemProperty("test.amqp_port_protocols", jvmOptions); + + copySystemProperty("virtualhostnode.type", jvmOptions); + copySystemProperty("virtualhostnode.context.blueprint", jvmOptions); + } + return jvmOptions; + } + + private void copySystemProperty(String name, Map jvmOptions) + { + String value = System.getProperty(name); + if (value != null) + { + jvmOptions.put(name, value); + } + } + + private Map getEnvironmentProperties() + { + return new HashMap<>(_env); + } + + private String getBrokerCommandTemplate() + { + return _brokerCommandTemplate; + } + + public static class BrokerHolderFactory + { + + public BrokerHolder create(BrokerHolder.BrokerType brokerType, int port, QpidBrokerTestCase testCase) + { + Set portsUsedByBroker = testCase.guessAllPortsUsedByBroker(port); + BrokerHolder holder = null; + if (brokerType.equals(BrokerHolder.BrokerType.INTERNAL) && !testCase.existingInternalBroker()) + { + testCase.setSystemProperty(BrokerProperties.PROPERTY_USE_CUSTOM_RMI_SOCKET_FACTORY, "false"); + holder = new InternalBrokerHolder(portsUsedByBroker); + } + else if (!brokerType.equals(BrokerHolder.BrokerType.EXTERNAL)) + { + + Map jvmOptions = testCase.getJvmProperties(); + Map environmentProperties = testCase.getEnvironmentProperties(); + + holder = new SpawnedBrokerHolder(testCase.getBrokerCommandTemplate(), port, testCase.getTestName(), jvmOptions, environmentProperties, brokerType, portsUsedByBroker); + } + return holder; + } + } + } diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/SpawnedBrokerHolder.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/SpawnedBrokerHolder.java index 4b747e869c..2581093f97 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/SpawnedBrokerHolder.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/SpawnedBrokerHolder.java @@ -22,6 +22,7 @@ package org.apache.qpid.test.utils; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; +import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -30,39 +31,215 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; +import org.apache.qpid.server.BrokerOptions; +import org.apache.qpid.server.configuration.BrokerProperties; +import org.apache.qpid.server.logging.messages.BrokerMessages; +import org.apache.qpid.util.FileUtils; import org.apache.qpid.util.SystemUtils; public class SpawnedBrokerHolder implements BrokerHolder { private static final Logger LOGGER = Logger.getLogger(SpawnedBrokerHolder.class); + protected static final String BROKER_READY = System.getProperty("broker.ready", BrokerMessages.READY().toString()); + private static final String BROKER_STOPPED = System.getProperty("broker.stopped", BrokerMessages.STOPPED().toString()); - private final Process _process; - private final Integer _pid; - private final String _workingDirectory; + private final BrokerType _type; + private final int _port; + private final String _name; + private final Map _jvmOptions; + private final Map _environmentSettings; + protected BrokerCommandHelper _brokerCommandHelper; + + private Process _process; + private Integer _pid; private Set _portsUsedByBroker; - private final String _brokerCommand; + private String _brokerCommand; + + public SpawnedBrokerHolder(String brokerCommandTemplate, int port, String name, Map jvmOptions, Map environmentSettings, BrokerType type, Set portsUsedByBroker) + { + _type = type; + _portsUsedByBroker = portsUsedByBroker; + _port = port; + _name = name; + _jvmOptions = jvmOptions; + _environmentSettings = environmentSettings; + _brokerCommandHelper = new BrokerCommandHelper(brokerCommandTemplate); + } - public SpawnedBrokerHolder(final Process process, final String workingDirectory, Set portsUsedByBroker, - String brokerCmd) + + @Override + public void start(BrokerOptions brokerOptions) throws Exception { - if(process == null) + // Add the port to QPID_WORK to ensure unique working dirs for multi broker tests + final String qpidWork = getQpidWork(_type, _port); + + String[] cmd = _brokerCommandHelper.getBrokerCommand(_port, brokerOptions.getConfigurationStoreLocation(), brokerOptions.getConfigurationStoreType(), + new File(brokerOptions.getLogConfigFileLocation())); + if (brokerOptions.isManagementMode()) + { + String[] newCmd = new String[cmd.length + 3]; + System.arraycopy(cmd, 0, newCmd, 0, cmd.length); + newCmd[cmd.length] = "-mm"; + newCmd[cmd.length + 1] = "-mmpass"; + newCmd[cmd.length + 2] = brokerOptions.getManagementModePassword(); + cmd = newCmd; + } + ProcessBuilder pb = new ProcessBuilder(cmd); + pb.redirectErrorStream(true); + Map processEnv = pb.environment(); + String qpidHome = System.getProperty(BrokerProperties.PROPERTY_QPID_HOME); + processEnv.put(BrokerProperties.PROPERTY_QPID_HOME, qpidHome); + + //Augment Path with bin directory in QPID_HOME. + boolean foundPath = false; + final String pathEntry = qpidHome + File.separator + "bin"; + for(Map.Entry entry : processEnv.entrySet()) + { + if(entry.getKey().equalsIgnoreCase("path")) + { + entry.setValue(entry.getValue().concat(File.pathSeparator + pathEntry)); + foundPath = true; + } + } + if(!foundPath) + { + processEnv.put("PATH", pathEntry); + } + //Add the test name to the broker run. + // DON'T change PNAME, qpid.stop needs this value. + processEnv.put("QPID_PNAME", "-DPNAME=QPBRKR -DTNAME=\"" + _name + "\""); + processEnv.put("QPID_WORK", qpidWork); + + // Use the environment variable to set amqj.logging.level for the broker + // The value used is a 'server' value in the test configuration to + // allow a differentiation between the client and broker logging levels. + if (System.getProperty("amqj.server.logging.level") != null) + { + processEnv.put("AMQJ_LOGGING_LEVEL", System.getProperty("amqj.server.logging.level")); + } + + // Add all the environment settings the test requested + if (!_environmentSettings.isEmpty()) + { + for (Map.Entry entry : _environmentSettings.entrySet()) + { + processEnv.put(entry.getKey(), entry.getValue()); + } + } + + String qpidOpts = ""; + + // Add all the specified system properties to QPID_OPTS + if (!_jvmOptions.isEmpty()) { - throw new IllegalArgumentException("Process must not be null"); + for (String key : _jvmOptions.keySet()) + { + qpidOpts += " -D" + key + "=" + _jvmOptions.get(key); + } } - _process = process; + if (processEnv.containsKey("QPID_OPTS")) + { + qpidOpts = processEnv.get("QPID_OPTS") + qpidOpts; + } + processEnv.put("QPID_OPTS", qpidOpts); + + // cpp broker requires that the work directory is created + createBrokerWork(qpidWork); + + _process = pb.start(); + + Piper standardOutputPiper = new Piper(_process.getInputStream(), + BROKER_READY, + BROKER_STOPPED, + "STD", "BROKER-" + _port); + + standardOutputPiper.start(); + + new Piper(_process.getErrorStream(), null, null, "ERROR", "BROKER-" + _port).start(); + + StringBuilder cmdLine = new StringBuilder(cmd[0]); + for(int i = 1; i< cmd.length; i++) + { + cmdLine.append(' '); + cmdLine.append(cmd[i]); + } + + _brokerCommand = cmdLine.toString(); _pid = retrieveUnixPidIfPossible(); - _workingDirectory = workingDirectory; - _portsUsedByBroker = portsUsedByBroker; - _brokerCommand = brokerCmd; + + if (!standardOutputPiper.await(30, TimeUnit.SECONDS)) + { + LOGGER.info("broker failed to become ready (" + standardOutputPiper.getReady() + "):" + standardOutputPiper.getStopLine()); + String threadDump = dumpThreads(); + if (!threadDump.isEmpty()) + { + LOGGER.info("the result of a try to capture thread dump:" + threadDump); + } + //Ensure broker has stopped + _process.destroy(); + cleanBrokerWork(qpidWork); + throw new RuntimeException("broker failed to become ready:" + + standardOutputPiper.getStopLine()); + } + + try + { + //test that the broker is still running and hasn't exited unexpectedly + int exit = _process.exitValue(); + LOGGER.info("broker aborted: " + exit); + cleanBrokerWork(qpidWork); + throw new RuntimeException("broker aborted: " + exit); + } + catch (IllegalThreadStateException e) + { + // this is expect if the broker started successfully + } + } - @Override - public String getWorkingDirectory() + protected void createBrokerWork(final String qpidWork) { - return _workingDirectory; + if (qpidWork != null) + { + final File dir = new File(qpidWork); + dir.mkdirs(); + if (!dir.isDirectory()) + { + throw new RuntimeException("Failed to created Qpid work directory : " + qpidWork); + } + } + } + + private String getQpidWork(BrokerType broker, int port) + { + if (!broker.equals(BrokerType.EXTERNAL)) + { + return System.getProperty(BrokerProperties.PROPERTY_QPID_WORK) + File.separator + port; + } + + return System.getProperty(BrokerProperties.PROPERTY_QPID_WORK); + } + + private void cleanBrokerWork(final String qpidWork) + { + if (qpidWork != null) + { + LOGGER.info("Cleaning broker work dir: " + qpidWork); + + File file = new File(qpidWork); + if (file.exists()) + { + final boolean success = FileUtils.delete(file, true); + if(!success) + { + throw new RuntimeException("Failed to recursively delete beneath : " + file); + } + } + } } public void shutdown() diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/server/BrokerStartupTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/server/BrokerStartupTest.java index e267bf439b..c475432113 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/server/BrokerStartupTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/server/BrokerStartupTest.java @@ -77,7 +77,7 @@ public class BrokerStartupTest extends AbstractTestLogging brokerConfigFile.delete(); } - startBroker(port, null); + startBroker(port, null, null); AMQConnectionURL url = new AMQConnectionURL(String.format("amqp://" + GUEST_USERNAME @@ -209,7 +209,7 @@ public class BrokerStartupTest extends AbstractTestLogging brokerConfigFile.delete(); } - startBroker(port, null); + startBroker(port, null, null); AMQConnectionURL url = new AMQConnectionURL(String.format("amqp://" + GUEST_USERNAME diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/server/logging/BrokerLoggingTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/server/logging/BrokerLoggingTest.java index 4952c4e10e..f7953e56d1 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/server/logging/BrokerLoggingTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/server/logging/BrokerLoggingTest.java @@ -22,13 +22,15 @@ package org.apache.qpid.server.logging; import junit.framework.AssertionFailedError; -import org.apache.qpid.server.BrokerOptions; +import org.apache.log4j.FileAppender; +import org.apache.log4j.LogManager; import org.apache.qpid.server.model.Port; import org.apache.qpid.server.model.Transport; import org.apache.qpid.test.utils.TestBrokerConfiguration; import org.apache.qpid.transport.ConnectionException; import org.apache.qpid.util.LogMonitor; +import java.io.File; import java.io.IOException; import java.net.Socket; import java.util.Collections; @@ -59,6 +61,7 @@ public class BrokerLoggingTest extends AbstractTestLogging private static final Pattern BROKER_MESSAGE_LOG_PATTERN = Pattern.compile(BROKER_MESSAGE_LOG_REG_EXP); private static final String BRK_LOG_PREFIX = "BRK-"; + @Override public void setUp() throws Exception { setLogMessagePrefix(); @@ -144,94 +147,6 @@ public class BrokerLoggingTest extends AbstractTestLogging return getPathRelativeToWorkingDirectory(getTestConfigFile(DEFAULT_PORT)); } - /** - * Description: - * On startup the broker must report correctly report the log4j file in use. This is important as it can help diagnose why logging messages are not being reported. - * Input: - * No custom -l value should be provided on the command line so that the default value is correctly reported. - * Output: - * - * MESSAGE BRK-1007 : Using logging configuration : <$QPID_HOME>/etc/log4j.xml - * - * Validation Steps: - * - * 1. The BRK ID is correct - * 2. This occurs before the BRK-1001 startup message. - * 3. The log4j file is the full path to the file specified on the commandline. - * - * @throws Exception caused by broker startup - */ - public void testBrokerStartupDefaultLog4j() throws Exception - { - if (isJavaBroker() && isExternalBroker() && !isInternalBroker()) - { - String TESTID = "BRK-1007"; - - _brokerCommandHelper.removeBrokerCommandLog4JFile(); - - startBroker(); - - // Now we can create the monitor as _outputFile will now be defined - _monitor = new LogMonitor(_outputFile); - - // Ensure broker has fully started up. - getConnection(); - - // Ensure we wait for TESTID to be logged - waitAndFindMatches(TESTID); - - List results = waitAndFindMatches(BRK_LOG_PREFIX); - try - { - // Validation - - assertTrue("BRKer message not logged", results.size() > 0); - - boolean validation = false; - for (String rawLog : results) - { - // We don't care about messages after we have our log config - if (validation) - { - break; - } - - String log = getLog(rawLog); - - // Ensure we do not have a BRK-1001 message before - if (!getMessageID(log).equals(TESTID)) - { - assertFalse(getMessageID(log).equals("BRK-1001")); - continue; - } - - //1 - validateMessageID(TESTID, log); - - //2 - //There will be 1 copy of this startup message (via SystemOut) - assertEquals("Unexpected log4j configuration message count.", - 1, findMatches(TESTID).size()); - - //3 - String defaultLog4j = System.getProperty(QPID_HOME) + "/" + BrokerOptions.DEFAULT_LOG_CONFIG_FILE; - assertTrue("Log4j file(" + defaultLog4j + ") details not correctly logged:" + getMessageString(log), - getMessageString(log).endsWith(defaultLog4j)); - - validation = true; - } - - assertTrue("Validation not performed: " + TESTID + " not logged", validation); - } - catch (AssertionFailedError afe) - { - dumpLogs(results, _monitor); - - throw afe; - } - } - } - /** * Description: * On startup the broker must report correctly report the log4j file in use. This is important as it can help diagnose why logging messages are not being reported. The broker must also be capable of correctly recognising the command line property to specify the custom logging configuration. @@ -254,11 +169,17 @@ public class BrokerLoggingTest extends AbstractTestLogging // This logging startup code only occurs when you run a Java broker if (isJavaBroker()) { - String customLog4j = getBrokerCommandLog4JFile().getAbsolutePath(); + // Log4j properties expects this to be set + System.setProperty("qpid.testMethod", "-" + getName() + ".customLog4j"); + System.setProperty("qpid.testClass", getClass().getName() ); + + String customLog4j = System.getProperty("log4j.configuration.file"); String TESTID = "BRK-1007"; - startBroker(); + startBroker(0, false, customLog4j); + _outputFile = new File(((FileAppender) LogManager.getRootLogger().getAllAppenders().nextElement()).getFile()); + // Now we can create the monitor as _outputFile will now be defined _monitor = new LogMonitor(_outputFile); @@ -385,7 +306,7 @@ public class BrokerLoggingTest extends AbstractTestLogging //2 //There will be 2 copies of the startup message (one via SystemOut, and one via Log4J) assertEquals("Unexpected startup message count", - 2, findMatches(TESTID).size()); + 1, findMatches(TESTID).size()); validation = true; } @@ -471,9 +392,8 @@ public class BrokerLoggingTest extends AbstractTestLogging assertEquals("Incorrect message", TESTID, id); //2 - //There will be 2 copies of the startup message (one via SystemOut, and one via Log4J) assertEquals("Unexpected listen message count", - 2, findMatches(TESTID).size()); + 1, findMatches(TESTID).size()); //3 String message = getMessageString(log); @@ -587,7 +507,7 @@ public class BrokerLoggingTest extends AbstractTestLogging //There will be 4 copies of the startup message (two via SystemOut, and two via Log4J) List listenMessages = findMatches(TESTID); assertEquals("Four listen messages should be found.", - 4, listenMessages .size()); + 2, listenMessages .size()); int tcpStarted = 0; int sslStarted = 0; @@ -604,8 +524,8 @@ public class BrokerLoggingTest extends AbstractTestLogging } } - assertEquals("Unexpected number of logs 'Listening on TCP port'", 2, tcpStarted); - assertEquals("Unexpected number of logs 'Listening on SSL port'", 2, sslStarted); + assertEquals("Unexpected number of logs 'Listening on TCP port'", 1, tcpStarted); + assertEquals("Unexpected number of logs 'Listening on SSL port'", 1, sslStarted); //4 Test ports open testSocketOpen(getPort()); @@ -690,10 +610,9 @@ public class BrokerLoggingTest extends AbstractTestLogging //2 assertEquals("Ready message not present", "Qpid Broker Ready", getMessageString(log)); - //There will be 2 copies of the startup message (one via SystemOut, and one via Log4J) assertEquals("Unexpected ready message count", - 2, findMatches(TESTID).size()); - assertEquals("The ready messages should have been the last 2 messages", results.size() - 2, i); + 1, findMatches(TESTID).size()); + assertEquals("The ready messages should have been the last 2 messages", results.size() - 1, i); validationComplete = true; break; diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/server/security/acl/AbstractACLTestCase.java b/qpid/java/systests/src/test/java/org/apache/qpid/server/security/acl/AbstractACLTestCase.java index 789ad420d8..f7722a8384 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/server/security/acl/AbstractACLTestCase.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/server/security/acl/AbstractACLTestCase.java @@ -59,7 +59,7 @@ public abstract class AbstractACLTestCase extends QpidBrokerTestCase implements @Override public void setUp() throws Exception { - getBrokerConfiguration().addGroupFileConfiguration(System.getProperty(QPID_HOME) + "/etc/groups-systests"); + getBrokerConfiguration().addGroupFileConfiguration(QPID_HOME + "/etc/groups-systests"); // run test specific setup String testSetup = StringUtils.replace(getName(), "test", "setUp"); diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/systest/management/jmx/LoggingManagementTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/systest/management/jmx/LoggingManagementTest.java index 3717c1594d..a06ed7be52 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/systest/management/jmx/LoggingManagementTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/systest/management/jmx/LoggingManagementTest.java @@ -25,6 +25,7 @@ import javax.management.openmbean.CompositeData; import javax.management.openmbean.TabularData; import org.apache.qpid.management.common.mbeans.LoggingManagement; +import org.apache.qpid.server.configuration.BrokerProperties; import org.apache.qpid.server.logging.log4j.LoggingManagementFacadeTest; import org.apache.qpid.test.utils.JMXTestUtils; import org.apache.qpid.test.utils.QpidBrokerTestCase; @@ -35,7 +36,6 @@ import org.apache.qpid.util.LogMonitor; * System test for Logging Management. These tests rely on value set within * test-profiles/log4j-test.xml. * - * @see LoggingManagementMBeanTest * @see LoggingManagementFacadeTest * */ @@ -44,7 +44,9 @@ public class LoggingManagementTest extends QpidBrokerTestCase private JMXTestUtils _jmxUtils; private LoggingManagement _loggingManagement; private LogMonitor _monitor; + private File _logConfig; + @Override public void setUp() throws Exception { getBrokerConfiguration().addJmxManagementConfiguration(); @@ -56,8 +58,9 @@ public class LoggingManagementTest extends QpidBrokerTestCase File tmpLogFile = File.createTempFile("log4j" + "." + getName(), ".xml"); tmpLogFile.deleteOnExit(); - FileUtils.copy(getBrokerCommandLog4JFile(), tmpLogFile); + FileUtils.copy(new File(System.getProperty("log4j.configuration.file")), tmpLogFile); setBrokerCommandLog4JFile(tmpLogFile); + _logConfig = tmpLogFile; super.setUp(); _jmxUtils.open(); @@ -66,6 +69,12 @@ public class LoggingManagementTest extends QpidBrokerTestCase _monitor = new LogMonitor(_outputFile); } + public void startBroker() throws Exception + { + super.startBroker(0, false, _logConfig.getAbsolutePath()); + } + + @Override public void tearDown() throws Exception { try @@ -74,6 +83,11 @@ public class LoggingManagementTest extends QpidBrokerTestCase { _jmxUtils.close(); } + + if (_logConfig != null) + { + _logConfig.delete(); + } } finally { @@ -122,7 +136,7 @@ public class LoggingManagementTest extends QpidBrokerTestCase _loggingManagement.setConfigFileLoggerLevel(operationalLoggingLogger, "OFF"); List matches = _monitor.waitAndFindMatches("Setting level to OFF for logger 'qpid.message'", 5000); - assertEquals(1, matches.size()); + assertTrue(matches.size()>=1); assertEffectiveLoggingLevel(operationalLoggingLogger, "INFO"); diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/systest/management/jmx/ManagementLoggingTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/systest/management/jmx/ManagementLoggingTest.java index cb6eae013e..4df81845d8 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/systest/management/jmx/ManagementLoggingTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/systest/management/jmx/ManagementLoggingTest.java @@ -104,7 +104,7 @@ public class ManagementLoggingTest extends AbstractTestLogging //There will be 2 copies of the startup message (one via SystemOut, and one via Log4J) results = findMatches("MNG-1001"); assertEquals("Unexpected startup message count.", - 2, results.size()); + 1, results.size()); //3 assertEquals("Startup log message is not 'Startup'.", "JMX Management Startup", @@ -185,7 +185,7 @@ public class ManagementLoggingTest extends AbstractTestLogging // Validation //There will be 4 startup messages (two via SystemOut, and two via Log4J) - assertEquals("Unexpected MNG-1002 message count", 4, results.size()); + assertEquals("Unexpected MNG-1002 message count", 2, results.size()); String log = getLogMessage(results, 0); @@ -197,7 +197,7 @@ public class ManagementLoggingTest extends AbstractTestLogging assertTrue("RMI Registry port not as expected(" + mPort + ").:" + getMessageString(log), getMessageString(log).endsWith(String.valueOf(mPort))); - log = getLogMessage(results, 2); + log = getLogMessage(results, 1); //1 validateMessageID("MNG-1002", log); @@ -243,7 +243,7 @@ public class ManagementLoggingTest extends AbstractTestLogging // Validate we only have two MNG-1002 (one via stdout, one via log4j) results = findMatches("MNG-1006"); assertEquals("Upexpected SSL Keystore message count", - 2, results.size()); + 1, results.size()); // Validate the keystore path is as expected assertTrue("SSL Keystore entry expected.:" + getMessageString(log), diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/KeyStoreRestTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/KeyStoreRestTest.java index 4b881d1e9f..169ece986e 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/KeyStoreRestTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/KeyStoreRestTest.java @@ -56,7 +56,7 @@ public class KeyStoreRestTest extends QpidRestTestCase Map keystore = keyStores.get(0); assertKeyStoreAttributes(keystore, TestBrokerConfiguration.ENTRY_NAME_SSL_KEYSTORE, - System.getProperty(QPID_HOME) + "/../" + TestSSLConstants.BROKER_KEYSTORE, null); + QPID_HOME + "/../" + TestSSLConstants.BROKER_KEYSTORE, null); } public void testCreate() throws Exception @@ -98,7 +98,7 @@ public class KeyStoreRestTest extends QpidRestTestCase List> keyStores = assertNumberOfKeyStores(1); Map keystore = keyStores.get(0); assertKeyStoreAttributes(keystore, TestBrokerConfiguration.ENTRY_NAME_SSL_KEYSTORE, - System.getProperty(QPID_HOME) + "/../" + TestSSLConstants.BROKER_KEYSTORE, null); + QPID_HOME + "/../" + TestSSLConstants.BROKER_KEYSTORE, null); } public void testDeleteFailsWhenKeyStoreInUse() throws Exception diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/LogViewerTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/LogViewerTest.java index f2fb2581f7..a7bf743e72 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/LogViewerTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/LogViewerTest.java @@ -28,25 +28,40 @@ import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; -import org.apache.qpid.server.BrokerOptions; +import org.apache.log4j.FileAppender; +import org.apache.log4j.Logger; +import org.apache.log4j.SimpleLayout; +import org.apache.qpid.server.configuration.BrokerProperties; public class LogViewerTest extends QpidRestTestCase { - public static final String DEFAULT_FILE_APPENDER_NAME = "FileAppender"; private String _expectedLogFileName; + private FileAppender _fileAppender; + private String _appenderName; + @Override public void setUp() throws Exception { - setSystemProperty("logsuffix", "-" + getTestQueueName()); - _expectedLogFileName = System.getProperty("logprefix", "") + "qpid" + System.getProperty("logsuffix", "") + ".log"; - - // use real broker log file - File brokerLogFile = new File(System.getProperty(QPID_HOME), BrokerOptions.DEFAULT_LOG_CONFIG_FILE); - setBrokerCommandLog4JFile(brokerLogFile); + _appenderName = getTestQueueName(); + _expectedLogFileName = "qpid-" + _appenderName + ".log"; + _fileAppender = new FileAppender(new SimpleLayout(), + System.getProperty(BrokerProperties.PROPERTY_QPID_WORK) + File.separator + _expectedLogFileName, false); + _fileAppender.setName(_appenderName); + Logger.getRootLogger().addAppender(_fileAppender); super.setUp(); } + @Override + public void tearDown() throws Exception + { + if (_fileAppender != null) + { + Logger.getRootLogger().removeAppender(_fileAppender); + } + super.tearDown(); + } + public void testGetLogFiles() throws Exception { List> logFiles = getRestTestHelper().getJsonAsList("/service/logfilenames"); @@ -54,24 +69,32 @@ public class LogViewerTest extends QpidRestTestCase // 1 file appender is configured in QPID default log4j xml: assertTrue("Unexpected number of log files", logFiles.size() > 0); + Map logFileDetails = null; + for (Map appenderDetails: logFiles) + { + if (_appenderName.equals(appenderDetails.get("appenderName"))) + { + logFileDetails = appenderDetails; + break; + } + } - Map logFileDetails = logFiles.get(0); assertEquals("Unexpected log file name", _expectedLogFileName, logFileDetails.get("name")); assertEquals("Unexpected log file mime type", "text/plain", logFileDetails.get("mimeType")); - assertEquals("Unexpected log file appender",DEFAULT_FILE_APPENDER_NAME, logFileDetails.get("appenderName")); + assertEquals("Unexpected log file appender",_appenderName, logFileDetails.get("appenderName")); assertTrue("Unexpected log file size", ((Number)logFileDetails.get("size")).longValue()>0); assertTrue("Unexpected log file modification time", ((Number)logFileDetails.get("lastModified")).longValue()>0); } public void testDownloadExistingLogFiles() throws Exception { - byte[] bytes = getRestTestHelper().getBytes("/service/logfile?l=" + DEFAULT_FILE_APPENDER_NAME + "%2F" + _expectedLogFileName); + byte[] bytes = getRestTestHelper().getBytes("/service/logfile?l=" + _appenderName + "%2F" + _expectedLogFileName); ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bytes)); try { ZipEntry entry = zis.getNextEntry(); - assertEquals("Unexpected broker log file name", DEFAULT_FILE_APPENDER_NAME + "/" + _expectedLogFileName, entry.getName()); + assertEquals("Unexpected broker log file name", _appenderName + "/" + _expectedLogFileName, entry.getName()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; @@ -91,7 +114,7 @@ public class LogViewerTest extends QpidRestTestCase public void testDownloadNonExistingLogFiles() throws Exception { - int responseCode = getRestTestHelper().submitRequest("/service/logfile?l=" + DEFAULT_FILE_APPENDER_NAME + "%2F" + int responseCode = getRestTestHelper().submitRequest("/service/logfile?l=" + _appenderName + "%2F" + _expectedLogFileName + "_" + System.currentTimeMillis(), "GET"); assertEquals("Unexpected response code", 404, responseCode); diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/TrustStoreRestTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/TrustStoreRestTest.java index 5d2e9de3fa..1aac22d0aa 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/TrustStoreRestTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/TrustStoreRestTest.java @@ -56,7 +56,7 @@ public class TrustStoreRestTest extends QpidRestTestCase Map truststore = trustStores.get(0); assertTrustStoreAttributes(truststore, TestBrokerConfiguration.ENTRY_NAME_SSL_TRUSTSTORE, - System.getProperty(QPID_HOME) + "/../" + TestSSLConstants.BROKER_TRUSTSTORE, false); + QPID_HOME + "/../" + TestSSLConstants.BROKER_TRUSTSTORE, false); } public void testCreate() throws Exception @@ -96,7 +96,7 @@ public class TrustStoreRestTest extends QpidRestTestCase List> trustStores = assertNumberOfTrustStores(1); Map truststore = trustStores.get(0); assertTrustStoreAttributes(truststore, TestBrokerConfiguration.ENTRY_NAME_SSL_TRUSTSTORE, - System.getProperty(QPID_HOME) + "/../" + TestSSLConstants.BROKER_TRUSTSTORE, false); + QPID_HOME + "/../" + TestSSLConstants.BROKER_TRUSTSTORE, false); } public void testDeleteFailsWhenTrustStoreInUse() throws Exception -- cgit v1.2.1 From 96f9c3e225682940e18bd5fa6a9a270a80de034c Mon Sep 17 00:00:00 2001 From: Keith Wall Date: Mon, 15 Dec 2014 14:28:17 +0000 Subject: QPID-6125: [Java Broker] Fix test broken by my previous commit git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1645667 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/qpid/test/unit/close/JavaServerCloseRaceConditionTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/test/unit/close/JavaServerCloseRaceConditionTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/test/unit/close/JavaServerCloseRaceConditionTest.java index 3fe45143d5..dfec1a8517 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/test/unit/close/JavaServerCloseRaceConditionTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/test/unit/close/JavaServerCloseRaceConditionTest.java @@ -106,7 +106,7 @@ public class JavaServerCloseRaceConditionTest extends QpidBrokerTestCase } catch (Exception e) { - assertTrue("Exception should say the exchange is not known.", e.getMessage().contains("Unknown exchange: " + EXCHANGE_NAME)); + assertTrue("Exception should say the exchange is not known.", e.getMessage().contains("Unknown exchange: '" + EXCHANGE_NAME + "'")); } try @@ -119,7 +119,7 @@ public class JavaServerCloseRaceConditionTest extends QpidBrokerTestCase } catch (Exception e) { - assertTrue("Exception should say the exchange is not known.", e.getMessage().contains("Unknown exchange: " + EXCHANGE_NAME)); + assertTrue("Exception should say the exchange is not known.", e.getMessage().contains("Unknown exchange: '" + EXCHANGE_NAME + "'")); } } -- cgit v1.2.1 From 5e0175cee706d931b12968004e61e5ed0aac071a Mon Sep 17 00:00:00 2001 From: Keith Wall Date: Mon, 22 Dec 2014 14:21:22 +0000 Subject: QPID-5099: Add system test to ensure that client does indeed release the messages on consumer close git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1647319 13f79535-47bb-0310-9956-ffa450edef68 --- .../test/unit/close/MessageConsumerCloseTest.java | 38 ++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/test/unit/close/MessageConsumerCloseTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/test/unit/close/MessageConsumerCloseTest.java index df32bd7858..de30a98a7d 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/test/unit/close/MessageConsumerCloseTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/test/unit/close/MessageConsumerCloseTest.java @@ -35,7 +35,7 @@ import org.apache.qpid.test.utils.QpidBrokerTestCase; public class MessageConsumerCloseTest extends QpidBrokerTestCase { - Exception _exception; + private volatile Exception _exception; public void testConsumerCloseAndSessionRollback() throws Exception { @@ -65,7 +65,7 @@ public class MessageConsumerCloseTest extends QpidBrokerTestCase boolean messageReceived = receiveLatch.await(1l, TimeUnit.SECONDS); consumer.close(); - assertNull("Exception occured on rollback:" + _exception, _exception); + assertNull("Exception occurred on rollback:" + _exception, _exception); assertTrue("Message is not received", messageReceived); consumer = session.createConsumer(destination); @@ -74,4 +74,38 @@ public class MessageConsumerCloseTest extends QpidBrokerTestCase Message message2 = consumer.receive(1000l); assertNotNull("message2 is not received", message2); } + + public void testPrefetchedMessagesReleasedOnConsumerClose() throws Exception + { + Connection connection = getConnection(); + final Session session = connection.createSession(true, Session.SESSION_TRANSACTED); + + Destination destination = getTestQueue(); + MessageConsumer consumer = session.createConsumer(destination); + + sendMessage(session, destination, 3); + + connection.start(); + + Message msg1 = consumer.receive(1000); + assertNotNull("Message one was null", msg1); + assertEquals("Message one has unexpected content", 0, msg1.getIntProperty(INDEX)); + session.commit(); + + // Messages two and three will have been prefetched by the consumer. + // Closing the consumer must make the available for delivery elsewhere + + consumer.close(); + + MessageConsumer consumer2 = session.createConsumer(destination); + + Message msg2 = consumer2.receive(1000); + Message msg3 = consumer2.receive(1000); + assertNotNull("Message two was null", msg2); + assertEquals("Message two has unexpected content", 1, msg2.getIntProperty(INDEX)); + + assertNotNull("Message three was null", msg3); + assertEquals("Message three has unexpected content", 2, msg3.getIntProperty(INDEX)); + session.commit(); + } } -- cgit v1.2.1 From b0175c7154a5025c0e98c7fff7d3a59f5fb4a405 Mon Sep 17 00:00:00 2001 From: Keith Wall Date: Sun, 28 Dec 2014 19:26:55 +0000 Subject: QPID-6290: [Java Broker] Management UI - refactor add VHN/VH to remove type based conditional logic * Also removed now defunct Broker attributes #supportedVirtualHostNodeTypes and #supportedVirtualHostTypes git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1648245 13f79535-47bb-0310-9956-ffa450edef68 --- .../src/test/java/org/apache/qpid/systest/rest/BrokerRestTest.java | 3 --- 1 file changed, 3 deletions(-) (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/BrokerRestTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/BrokerRestTest.java index ba95eecc6d..4023830a8d 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/BrokerRestTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/BrokerRestTest.java @@ -235,9 +235,6 @@ public class BrokerRestTest extends QpidRestTestCase assertNotNull("Unexpected value of attribute ports", brokerDetails.get(BROKER_PORTS_ATTRIBUTE)); assertNotNull("Unexpected value of attribute authenticationproviders", brokerDetails.get(BROKER_AUTHENTICATIONPROVIDERS_ATTRIBUTE)); - assertNotNull("Unexpected value of attribute supportedVirtualHostTypes", brokerDetails.get(Broker.SUPPORTED_VIRTUALHOST_TYPES)); - assertNotNull("Unexpected value of attribute supportedVirtualHostNodeTypes", brokerDetails.get(Broker.SUPPORTED_VIRTUALHOSTNODE_TYPES)); - } } -- cgit v1.2.1 From 1c420bf20a6902efb0256c881c8b777ccd211b4a Mon Sep 17 00:00:00 2001 From: Keith Wall Date: Mon, 29 Dec 2014 17:06:39 +0000 Subject: QPID-6291: [Java Broker] Remove the now defunct supported attributes: VH#supportedExchangeTypes, VH#supportedQueueTypes, Broker#supportedAuthenticationProviders, Broker#supportedPreferencesProviderTypes Clients now can discover the supported attributes in a generic fashion via the metadata service. git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1648392 13f79535-47bb-0310-9956-ffa450edef68 --- .../src/main/java/org/apache/qpid/systest/rest/Asserts.java | 7 ------- 1 file changed, 7 deletions(-) (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.java b/qpid/java/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.java index 2c3ad1f8e5..e609d73268 100644 --- a/qpid/java/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.java +++ b/qpid/java/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.java @@ -76,7 +76,6 @@ public class Asserts ConfiguredObject.DESCRIPTION, ConfiguredObject.CONTEXT, ConfiguredObject.DESIRED_STATE, - VirtualHost.SUPPORTED_QUEUE_TYPES, VirtualHost.TYPE); assertEquals("Unexpected value of attribute " + VirtualHost.NAME, @@ -92,12 +91,6 @@ public class Asserts assertEquals("Unexpected value of attribute " + VirtualHost.QUEUE_DEAD_LETTER_QUEUE_ENABLED, Boolean.FALSE, virtualHost.get(VirtualHost.QUEUE_DEAD_LETTER_QUEUE_ENABLED)); - @SuppressWarnings("unchecked") - Collection exchangeTypes = (Collection) virtualHost.get(VirtualHost.SUPPORTED_EXCHANGE_TYPES); - assertEquals("Unexpected value of attribute " + VirtualHost.SUPPORTED_EXCHANGE_TYPES, - new HashSet(Arrays.asList("headers", "topic", "direct", "fanout")), - new HashSet(exchangeTypes)); - @SuppressWarnings("unchecked") Map statistics = (Map) virtualHost.get(STATISTICS_ATTRIBUTE); Asserts.assertAttributesPresent(statistics, -- cgit v1.2.1 From fcaa5ff88e5ad15469c54e29d8f0d87821ccf8e1 Mon Sep 17 00:00:00 2001 From: Keith Wall Date: Tue, 30 Dec 2014 07:48:12 +0000 Subject: NO-JIRA: [Java Tests] Prevent sporadic spurious failure of testUnidirectionalHeartbeating git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1648488 13f79535-47bb-0310-9956-ffa450edef68 --- .../systests/src/test/java/org/apache/qpid/client/HeartbeatTest.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/client/HeartbeatTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/client/HeartbeatTest.java index 881a37a970..6612fedd35 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/client/HeartbeatTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/client/HeartbeatTest.java @@ -120,12 +120,15 @@ public class HeartbeatTest extends QpidBrokerTestCase sendConn.setHeartbeatListener(sendListener); receiveConn.start(); + // Start the flow of messages to the consumer + consumer.receiveNoWait(); + for(int i = 0; i < 5; i++) { producer.send(senderSession.createTextMessage("Msg " + i)); Thread.sleep(500); assertNotNull("Expected to received message", consumer.receive(500)); - // Consumer does not ack the message in order to generate no bytes from consumer back to Broker + // Consumer does not ack the message in order that no bytes flow from consumer connection back to Broker } assertTrue("Too few heartbeats sent "+ receiveListener.getHeartbeatsSent() +" (expected at least 2)", receiveListener.getHeartbeatsSent()>=2); -- cgit v1.2.1 From 6631e8e980107ad609105d4ef1bb2ee5c4275e8b Mon Sep 17 00:00:00 2001 From: Robert Godfrey Date: Fri, 2 Jan 2015 09:47:21 +0000 Subject: QPID-6294 : [Java Client] Allow use of 0 prefetch in AMQP 0-8/9/9-1 git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1648987 13f79535-47bb-0310-9956-ffa450edef68 --- .../qpid/systest/prefetch/ZeroPrefetchTest.java | 83 ++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 qpid/java/systests/src/test/java/org/apache/qpid/systest/prefetch/ZeroPrefetchTest.java (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/systest/prefetch/ZeroPrefetchTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/systest/prefetch/ZeroPrefetchTest.java new file mode 100644 index 0000000000..6a9fa0175a --- /dev/null +++ b/qpid/java/systests/src/test/java/org/apache/qpid/systest/prefetch/ZeroPrefetchTest.java @@ -0,0 +1,83 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.systest.prefetch; + +import java.util.UUID; + +import javax.jms.Connection; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Queue; +import javax.jms.Session; + +import org.apache.qpid.configuration.ClientProperties; +import org.apache.qpid.test.utils.QpidBrokerTestCase; + +public class ZeroPrefetchTest extends QpidBrokerTestCase +{ + + private static final String TEST_PROPERTY_NAME = "testProp"; + + // send two messages to the queue, consume and acknowledge one message on connection 1 + // create a second connection and attempt to consume the second message - this will only be possible + // if the first connection has no prefetch + public void testZeroPrefetch() throws Exception + { + setTestClientSystemProperty(ClientProperties.MAX_PREFETCH_PROP_NAME, "0"); + Connection prefetch1Connection = getConnection(); + + prefetch1Connection.start(); + + final Session prefetch1session = prefetch1Connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = prefetch1session.createQueue(getTestQueueName()); + MessageConsumer prefetch1consumer = prefetch1session.createConsumer(queue); + + + Session producerSession = prefetch1Connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = producerSession.createProducer(queue); + Message firstMessage = producerSession.createMessage(); + String firstPropertyValue = UUID.randomUUID().toString(); + firstMessage.setStringProperty(TEST_PROPERTY_NAME, firstPropertyValue); + producer.send(firstMessage); + + Message secondMessage = producerSession.createMessage(); + String secondPropertyValue = UUID.randomUUID().toString(); + secondMessage.setStringProperty(TEST_PROPERTY_NAME, secondPropertyValue); + producer.send(secondMessage); + + + Message receivedMessage = prefetch1consumer.receive(2000l); + assertNotNull("First message was not received", receivedMessage); + assertEquals("Message property was not as expected", firstPropertyValue, receivedMessage.getStringProperty(TEST_PROPERTY_NAME)); + + Connection prefetch2Connection = getConnection(); + + prefetch2Connection.start(); + final Session prefetch2session = prefetch2Connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageConsumer prefetch2consumer = prefetch2session.createConsumer(queue); + + receivedMessage = prefetch2consumer.receive(2000l); + assertNotNull("Second message was not received", receivedMessage); + assertEquals("Message property was not as expected", secondPropertyValue, receivedMessage.getStringProperty(TEST_PROPERTY_NAME)); + + } +} -- cgit v1.2.1 From 87d3ca113acad85afe0143069484f0640427928a Mon Sep 17 00:00:00 2001 From: Robert Godfrey Date: Mon, 5 Jan 2015 16:45:58 +0000 Subject: QPID-6295 : [Java Broker] reload ACL config when the file value is changed git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1649587 13f79535-47bb-0310-9956-ffa450edef68 --- .../test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java index 8c4effd685..e40add449e 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java @@ -795,10 +795,11 @@ public class BrokerACLTest extends QpidRestTestCase assertAccessControlProviderExistence(accessControlProviderName, true); + File aclFile = TestFileUtils.createTempFile(this, ".acl", "ACL ALLOW all all"); + Map attributes = new HashMap(); - attributes.put(GroupProvider.NAME, accessControlProviderName); - attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); - attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); + attributes.put(AccessControlProvider.NAME, accessControlProviderName); + attributes.put(FileBasedGroupProvider.PATH, aclFile.getAbsolutePath()); responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); assertEquals("Setting of access control provider attributes should be allowed", 200, responseCode); } -- cgit v1.2.1 From a1b5b082b083bc574866bb53712a68269fc793e0 Mon Sep 17 00:00:00 2001 From: Robert Godfrey Date: Sat, 10 Jan 2015 01:20:02 +0000 Subject: QPID-6306 : [Java Broker] Restrict broker to single ACL Provider at any given time git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1650708 13f79535-47bb-0310-9956-ffa450edef68 --- .../rest/AccessControlProviderRestTest.java | 78 ++-------------------- .../qpid/systest/rest/acl/BrokerACLTest.java | 48 +++---------- 2 files changed, 14 insertions(+), 112 deletions(-) (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/AccessControlProviderRestTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/AccessControlProviderRestTest.java index 4140c9c12c..0dda8e077b 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/AccessControlProviderRestTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/AccessControlProviderRestTest.java @@ -125,34 +125,28 @@ public class AccessControlProviderRestTest extends QpidRestTestCase public void testReplaceAccessControlProvider() throws Exception { - String accessControlProviderName1 = getTestName() + "1"; - //verify that the access control provider doesn't exist, and - //in doing so implicitly verify that the 'denied' user can - //actually currently connect because no ACL is in effect yet - getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); - assertAccessControlProviderExistence(accessControlProviderName1, false); //create the access control provider using the 'allowed' user getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); - int responseCode = createAccessControlProvider(accessControlProviderName1, _aclFileContent1); + int responseCode = createAccessControlProvider(getTestName(), _aclFileContent1); assertEquals("Access control provider creation should be allowed", 201, responseCode); //verify it exists with the 'allowed' user - assertAccessControlProviderExistence(accessControlProviderName1, true); + assertAccessControlProviderExistence(getTestName(), true); //verify the 'denied' and 'other' user can no longer access the management //interface due to the just-created ACL file now preventing them getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); - assertCanAccessManagementInterface(accessControlProviderName1, false); + assertCanAccessManagementInterface(getTestName(), false); getRestTestHelper().setUsernameAndPassword(OTHER_USER, OTHER_USER); - assertCanAccessManagementInterface(accessControlProviderName1, false); + assertCanAccessManagementInterface(getTestName(), false); //create the replacement access control provider using the 'allowed' user. String accessControlProviderName2 = getTestName() + "2"; getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); - responseCode = createAccessControlProvider(accessControlProviderName2, _aclFileContent2); - assertEquals("Access control provider creation should be allowed", 201, responseCode); + responseCode = createAccessControlProvider(getTestName(), _aclFileContent2); + assertEquals("Access control provider creation should be allowed", 200, responseCode); //Verify that it took effect immediately, replacing the first access control provider @@ -162,11 +156,6 @@ public class AccessControlProviderRestTest extends QpidRestTestCase getRestTestHelper().setUsernameAndPassword(OTHER_USER, OTHER_USER); assertCanAccessManagementInterface(accessControlProviderName2, true); - //remove the original access control provider using the 'allowed' user - getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); - responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName1, "DELETE"); - assertEquals("Access control provider deletion should be allowed", 200, responseCode); - assertAccessControlProviderExistence(accessControlProviderName1, false); //verify the 'denied' user still can't access the management interface, the 'other' user still can, thus //confirming that the second access control provider is still in effect @@ -177,61 +166,6 @@ public class AccessControlProviderRestTest extends QpidRestTestCase } - public void testAddAndRemoveSecondAccessControlProviderReinstatesOriginal() throws Exception - { - String accessControlProviderName1 = getTestName() + "1"; - - //verify that the access control provider doesn't exist, and - //in doing so implicitly verify that the 'denied' user can - //actually currently connect because no ACL is in effect yet - getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); - assertAccessControlProviderExistence(accessControlProviderName1, false); - - //create the access control provider using the 'allowed' user - getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); - int responseCode = createAccessControlProvider(accessControlProviderName1, _aclFileContent1); - assertEquals("Access control provider creation should be allowed", 201, responseCode); - - //verify it exists with the 'allowed' user - assertAccessControlProviderExistence(accessControlProviderName1, true); - - //verify the 'denied' and 'other' user can no longer access the management - //interface due to the just-created ACL file now preventing them - getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); - assertCanAccessManagementInterface(accessControlProviderName1, false); - getRestTestHelper().setUsernameAndPassword(OTHER_USER, OTHER_USER); - assertCanAccessManagementInterface(accessControlProviderName1, false); - - //create the replacement access control provider using the 'allowed' user. - String accessControlProviderName2 = getTestName() + "2"; - getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); - responseCode = createAccessControlProvider(accessControlProviderName2, _aclFileContent2); - assertEquals("Access control provider creation should be allowed", 201, responseCode); - - //Verify that it took effect immediately, replacing the first access control provider - - //verify the 'denied' user still can't access the management interface, but the 'other' user now CAN. - getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); - assertCanAccessManagementInterface(accessControlProviderName2, false); - getRestTestHelper().setUsernameAndPassword(OTHER_USER, OTHER_USER); - assertCanAccessManagementInterface(accessControlProviderName2, true); - - //remove the second access control provider using the 'allowed' user - getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); - responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName2, "DELETE"); - assertEquals("Access control provider deletion should be allowed", 200, responseCode); - assertAccessControlProviderExistence(accessControlProviderName2, false); - - //verify the 'denied' user still can't access the management interface, the - //'other' now CANT again, the 'allowed' still can, thus confirming that the - //first access control provider is now in effect once again - getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); - assertCanAccessManagementInterface(accessControlProviderName2, false); - getRestTestHelper().setUsernameAndPassword(OTHER_USER, OTHER_USER); - assertCanAccessManagementInterface(accessControlProviderName2, false); - getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); - assertCanAccessManagementInterface(accessControlProviderName2, true); - } public void testRemovalOfAccessControlProviderInErrorStateUsingManagementMode() throws Exception { diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java index e40add449e..86ebf11575 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java @@ -714,19 +714,6 @@ public class BrokerACLTest extends QpidRestTestCase /* === AccessControlProvider === */ - public void testCreateAccessControlProviderAllowed() throws Exception - { - getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); - - String accessControlProviderName = getTestName(); - - assertAccessControlProviderExistence(accessControlProviderName, false); - - int responseCode = createAccessControlProvider(accessControlProviderName); - assertEquals("Access control provider creation should be allowed", 201, responseCode); - - assertAccessControlProviderExistence(accessControlProviderName, true); - } public void testCreateAccessControlProviderDenied() throws Exception { @@ -746,18 +733,13 @@ public class BrokerACLTest extends QpidRestTestCase { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); - String accessControlProviderName = getTestName(); - - assertAccessControlProviderExistence(accessControlProviderName, false); - - int responseCode = createAccessControlProvider(accessControlProviderName); - assertEquals("Access control provider creation should be allowed", 201, responseCode); + String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER); - responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE"); + int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE"); assertEquals("Access control provider deletion should be denied", 403, responseCode); assertAccessControlProviderExistence(accessControlProviderName, true); @@ -767,16 +749,12 @@ public class BrokerACLTest extends QpidRestTestCase { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); - String accessControlProviderName = getTestName(); - - assertAccessControlProviderExistence(accessControlProviderName, false); + String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; - int responseCode = createAccessControlProvider(accessControlProviderName); - assertEquals("Access control provider creation should be allowed", 201, responseCode); assertAccessControlProviderExistence(accessControlProviderName, true); - responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE"); + int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE"); assertEquals("Access control provider deletion should be allowed", 200, responseCode); assertAccessControlProviderExistence(accessControlProviderName, false); @@ -786,12 +764,7 @@ public class BrokerACLTest extends QpidRestTestCase { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); - String accessControlProviderName = getTestName(); - - assertAccessControlProviderExistence(accessControlProviderName, false); - - int responseCode = createAccessControlProvider(accessControlProviderName); - assertEquals("Access control provider creation should be allowed", 201, responseCode); + String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); @@ -800,7 +773,7 @@ public class BrokerACLTest extends QpidRestTestCase Map attributes = new HashMap(); attributes.put(AccessControlProvider.NAME, accessControlProviderName); attributes.put(FileBasedGroupProvider.PATH, aclFile.getAbsolutePath()); - responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); + int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); assertEquals("Setting of access control provider attributes should be allowed", 200, responseCode); } @@ -808,12 +781,7 @@ public class BrokerACLTest extends QpidRestTestCase { getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER); - String accessControlProviderName = getTestName(); - - assertAccessControlProviderExistence(accessControlProviderName, false); - - int responseCode = createAccessControlProvider(accessControlProviderName); - assertEquals("Access control provider creation should be allowed", 201, responseCode); + String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE; assertAccessControlProviderExistence(accessControlProviderName, true); @@ -823,7 +791,7 @@ public class BrokerACLTest extends QpidRestTestCase attributes.put(GroupProvider.NAME, accessControlProviderName); attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); attributes.put(FileBasedGroupProvider.PATH, "/path/to/file"); - responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); + int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes); assertEquals("Setting of access control provider attributes should be denied", 403, responseCode); } -- cgit v1.2.1 From 9b1d37a0cbef71478b58c6acee4f72a2474a9f7d Mon Sep 17 00:00:00 2001 From: Andrew MacBean Date: Wed, 14 Jan 2015 10:38:04 +0000 Subject: QPID-6304: [Java Broker] Allow truststore and keystore (JKS) files to be stored as a data:// URL inside the config * Added truststore/keystore unit tests too to cover both new and (most of) the existing functionality, retiring the equivilent slower REST system tests. * Added single REST test exercising the creation of a keystore/teststore from data:// URL. git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1651615 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/qpid/systest/rest/KeyStoreRestTest.java | 172 ++++++--------------- .../qpid/systest/rest/TrustStoreRestTest.java | 147 ++++-------------- 2 files changed, 72 insertions(+), 247 deletions(-) (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/KeyStoreRestTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/KeyStoreRestTest.java index 169ece986e..03b0a7a304 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/KeyStoreRestTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/KeyStoreRestTest.java @@ -20,23 +20,20 @@ */ package org.apache.qpid.systest.rest; -import java.io.IOException; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.JsonParseException; -import org.codehaus.jackson.map.JsonMappingException; +import javax.servlet.http.HttpServletResponse; + import org.apache.qpid.server.model.AbstractConfiguredObject; import org.apache.qpid.server.model.KeyStore; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.Transport; import org.apache.qpid.server.security.FileKeyStore; import org.apache.qpid.test.utils.TestBrokerConfiguration; import org.apache.qpid.test.utils.TestSSLConstants; +import org.apache.qpid.util.DataUrlUtils; +import org.apache.qpid.util.FileUtils; public class KeyStoreRestTest extends QpidRestTestCase { @@ -67,7 +64,7 @@ public class KeyStoreRestTest extends QpidRestTestCase String certAlias = "app2"; assertNumberOfKeyStores(1); - createKeyStore(name, certAlias); + createKeyStore(name, certAlias, TestSSLConstants.KEYSTORE, TestSSLConstants.KEYSTORE_PASSWORD); assertNumberOfKeyStores(2); List> keyStores = getRestTestHelper().getJsonAsList("keystore/" + name); @@ -76,161 +73,72 @@ public class KeyStoreRestTest extends QpidRestTestCase assertKeyStoreAttributes(keyStores.get(0), name, TestSSLConstants.KEYSTORE, certAlias); } - public void testDelete() throws Exception + public void testCreateWithDataUrl() throws Exception { super.setUp(); String name = getTestName(); - String certAlias = "app2"; + byte[] keystoreAsBytes = FileUtils.readFileAsBytes(TestSSLConstants.KEYSTORE); + String dataUrlForKeyStore = DataUrlUtils.getDataUrlForBytes(keystoreAsBytes); assertNumberOfKeyStores(1); - createKeyStore(name, certAlias); - assertNumberOfKeyStores(2); - - int responseCode = getRestTestHelper().submitRequest("keystore/" + name , "DELETE"); - assertEquals("Unexpected response code for provider deletion", 200, responseCode); - - List> keyStore = getRestTestHelper().getJsonAsList("keystore/" + name); - assertNotNull("details should not be null", keyStore); - assertTrue("details should be empty as the keystore no longer exists", keyStore.isEmpty()); - - //check only the default systests key store remains - List> keyStores = assertNumberOfKeyStores(1); - Map keystore = keyStores.get(0); - assertKeyStoreAttributes(keystore, TestBrokerConfiguration.ENTRY_NAME_SSL_KEYSTORE, - QPID_HOME + "/../" + TestSSLConstants.BROKER_KEYSTORE, null); - } - - public void testDeleteFailsWhenKeyStoreInUse() throws Exception - { - String name = "testDeleteFailsWhenKeyStoreInUse"; - - //add a new key store config to use - Map sslKeyStoreAttributes = new HashMap(); - sslKeyStoreAttributes.put(KeyStore.NAME, name); - sslKeyStoreAttributes.put(FileKeyStore.PATH, TestSSLConstants.BROKER_KEYSTORE); - sslKeyStoreAttributes.put(FileKeyStore.PASSWORD, TestSSLConstants.BROKER_KEYSTORE_PASSWORD); - getBrokerConfiguration().addObjectConfiguration(KeyStore.class,sslKeyStoreAttributes); - - //add the SSL port using it - Map sslPortAttributes = new HashMap(); - sslPortAttributes.put(Port.TRANSPORTS, Collections.singleton(Transport.SSL)); - sslPortAttributes.put(Port.PORT, DEFAULT_SSL_PORT); - sslPortAttributes.put(Port.NAME, TestBrokerConfiguration.ENTRY_NAME_SSL_PORT); - sslPortAttributes.put(Port.AUTHENTICATION_PROVIDER, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER); - sslPortAttributes.put(Port.KEY_STORE, name); - getBrokerConfiguration().addObjectConfiguration(Port.class,sslPortAttributes); - - super.setUp(); - - //verify the keystore is there + createKeyStore(name, null, dataUrlForKeyStore, TestSSLConstants.KEYSTORE_PASSWORD); assertNumberOfKeyStores(2); - List> keyStore = getRestTestHelper().getJsonAsList("keystore/" + name); - assertNotNull("details should not be null", keyStore); - assertKeyStoreAttributes(keyStore.get(0), name, TestSSLConstants.BROKER_KEYSTORE, null); - - //try to delete it, which should fail as it is in use - int responseCode = getRestTestHelper().submitRequest("keystore/" + name , "DELETE"); - assertEquals("Unexpected response code for provider deletion", 409, responseCode); + List> keyStores = getRestTestHelper().getJsonAsList("keystore/" + name); + assertNotNull("details cannot be null", keyStores); - //check its still there - assertNumberOfKeyStores(2); - keyStore = getRestTestHelper().getJsonAsList("keystore/" + name); - assertNotNull("details should not be null", keyStore); - assertKeyStoreAttributes(keyStore.get(0), name, TestSSLConstants.BROKER_KEYSTORE, null); + assertKeyStoreAttributes(keyStores.get(0), name, dataUrlForKeyStore, null); } - public void testUpdateWithGoodPathSucceeds() throws Exception + public void testDelete() throws Exception { super.setUp(); String name = getTestName(); + String certAlias = "app2"; assertNumberOfKeyStores(1); - createKeyStore(name, null); + createKeyStore(name, certAlias, TestSSLConstants.KEYSTORE, TestSSLConstants.KEYSTORE_PASSWORD); assertNumberOfKeyStores(2); - Map attributes = new HashMap(); - attributes.put(KeyStore.NAME, name); - attributes.put(FileKeyStore.PATH, TestSSLConstants.UNTRUSTED_KEYSTORE); - - int responseCode = getRestTestHelper().submitRequest("keystore/" + name , "PUT", attributes); - assertEquals("Unexpected response code for keystore update", 200, responseCode); + getRestTestHelper().submitRequest("keystore/" + name, "DELETE", HttpServletResponse.SC_OK); List> keyStore = getRestTestHelper().getJsonAsList("keystore/" + name); assertNotNull("details should not be null", keyStore); + assertTrue("details should be empty as the keystore no longer exists", keyStore.isEmpty()); - assertKeyStoreAttributes(keyStore.get(0), name, TestSSLConstants.UNTRUSTED_KEYSTORE, null); + //check only the default systests key store remains + List> keyStores = assertNumberOfKeyStores(1); + Map keystore = keyStores.get(0); + assertKeyStoreAttributes(keystore, TestBrokerConfiguration.ENTRY_NAME_SSL_KEYSTORE, + QPID_HOME + "/../" + TestSSLConstants.BROKER_KEYSTORE, null); } - public void testUpdateWithNonExistentPathFails() throws Exception + public void testUpdate() throws Exception { super.setUp(); String name = getTestName(); assertNumberOfKeyStores(1); - createKeyStore(name, null); + createKeyStore(name, null, TestSSLConstants.KEYSTORE, TestSSLConstants.KEYSTORE_PASSWORD); assertNumberOfKeyStores(2); Map attributes = new HashMap(); attributes.put(KeyStore.NAME, name); - attributes.put(FileKeyStore.PATH, "does.not.exist"); + attributes.put(FileKeyStore.PATH, TestSSLConstants.UNTRUSTED_KEYSTORE); - int responseCode = getRestTestHelper().submitRequest("keystore/" + name , "PUT", attributes); - assertEquals("Unexpected response code for keystore update", 409, responseCode); + getRestTestHelper().submitRequest("keystore/" + name, "PUT", attributes, HttpServletResponse.SC_OK); List> keyStore = getRestTestHelper().getJsonAsList("keystore/" + name); assertNotNull("details should not be null", keyStore); - //verify the details remain unchanged - assertKeyStoreAttributes(keyStore.get(0), name, TestSSLConstants.KEYSTORE, null); + assertKeyStoreAttributes(keyStore.get(0), name, TestSSLConstants.UNTRUSTED_KEYSTORE, null); } - public void testUpdateCertificateAlias() throws Exception - { - super.setUp(); - - String name = getTestName(); - - assertNumberOfKeyStores(1); - createKeyStore(name, "app1"); - assertNumberOfKeyStores(2); - - List> keyStore = getRestTestHelper().getJsonAsList("keystore/" + name); - assertNotNull("details should not be null", keyStore); - assertKeyStoreAttributes(keyStore.get(0), name, TestSSLConstants.KEYSTORE, "app1"); - - //Update the certAlias from app1 to app2 - Map attributes = new HashMap(); - attributes.put(KeyStore.NAME, name); - attributes.put(FileKeyStore.CERTIFICATE_ALIAS, "app2"); - - int responseCode = getRestTestHelper().submitRequest("keystore/" + name , "PUT", attributes); - assertEquals("Unexpected response code for keystore update", 200, responseCode); - - keyStore = getRestTestHelper().getJsonAsList("keystore/" + name); - assertNotNull("details should not be null", keyStore); - - assertKeyStoreAttributes(keyStore.get(0), name, TestSSLConstants.KEYSTORE, "app2"); - - //Update the certAlias to clear it (i.e go from from app1 to null) - attributes = new HashMap(); - attributes.put(KeyStore.NAME, name); - attributes.put(FileKeyStore.CERTIFICATE_ALIAS, null); - - responseCode = getRestTestHelper().submitRequest("keystore/" + name , "PUT", attributes); - assertEquals("Unexpected response code for keystore update", 200, responseCode); - keyStore = getRestTestHelper().getJsonAsList("keystore/" + name); - assertNotNull("details should not be null", keyStore); - - assertKeyStoreAttributes(keyStore.get(0), name, TestSSLConstants.KEYSTORE, null); - } - - private List> assertNumberOfKeyStores(int numberOfKeystores) throws IOException, - JsonParseException, JsonMappingException + private List> assertNumberOfKeyStores(int numberOfKeystores) throws Exception { List> keyStores = getRestTestHelper().getJsonAsList("keystore"); assertNotNull("keystores should not be null", keyStores); @@ -239,16 +147,18 @@ public class KeyStoreRestTest extends QpidRestTestCase return keyStores; } - private void createKeyStore(String name, String certAlias) throws IOException, JsonGenerationException, JsonMappingException + private void createKeyStore(String name, String certAlias, final String keyStorePath, final String keystorePassword) throws Exception { - Map keyStoreAttributes = new HashMap(); + Map keyStoreAttributes = new HashMap<>(); keyStoreAttributes.put(KeyStore.NAME, name); - keyStoreAttributes.put(FileKeyStore.PATH, TestSSLConstants.KEYSTORE); - keyStoreAttributes.put(FileKeyStore.PASSWORD, TestSSLConstants.KEYSTORE_PASSWORD); - keyStoreAttributes.put(FileKeyStore.CERTIFICATE_ALIAS, certAlias); + keyStoreAttributes.put(FileKeyStore.PATH, keyStorePath); + keyStoreAttributes.put(FileKeyStore.PASSWORD, keystorePassword); + if (certAlias != null) + { + keyStoreAttributes.put(FileKeyStore.CERTIFICATE_ALIAS, certAlias); + } - int responseCode = getRestTestHelper().submitRequest("keystore/" + name, "PUT", keyStoreAttributes); - assertEquals("Unexpected response code", 201, responseCode); + getRestTestHelper().submitRequest("keystore/" + name, "PUT", keyStoreAttributes, HttpServletResponse.SC_CREATED); } private void assertKeyStoreAttributes(Map keystore, String name, String path, String certAlias) @@ -261,12 +171,16 @@ public class KeyStoreRestTest extends QpidRestTestCase AbstractConfiguredObject.SECURED_STRING_VALUE, keystore.get(FileKeyStore.PASSWORD)); assertEquals("unexpected type of default systests key store", java.security.KeyStore.getDefaultType(), keystore.get(FileKeyStore.KEY_STORE_TYPE)); - assertEquals("unexpected certificateAlias value", - certAlias, keystore.get(FileKeyStore.CERTIFICATE_ALIAS)); if(certAlias == null) { assertFalse("should not be a certificateAlias attribute", keystore.containsKey(FileKeyStore.CERTIFICATE_ALIAS)); } + else + { + assertEquals("unexpected certificateAlias value", + certAlias, keystore.get(FileKeyStore.CERTIFICATE_ALIAS)); + + } } } diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/TrustStoreRestTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/TrustStoreRestTest.java index 1aac22d0aa..6cca3fc12c 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/TrustStoreRestTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/systest/rest/TrustStoreRestTest.java @@ -20,23 +20,19 @@ */ package org.apache.qpid.systest.rest; -import java.io.IOException; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.JsonParseException; -import org.codehaus.jackson.map.JsonMappingException; +import javax.servlet.http.HttpServletResponse; import org.apache.qpid.server.model.AbstractConfiguredObject; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.Transport; import org.apache.qpid.server.model.TrustStore; import org.apache.qpid.server.security.FileTrustStore; import org.apache.qpid.test.utils.TestBrokerConfiguration; import org.apache.qpid.test.utils.TestSSLConstants; +import org.apache.qpid.util.DataUrlUtils; +import org.apache.qpid.util.FileUtils; public class TrustStoreRestTest extends QpidRestTestCase { @@ -66,7 +62,7 @@ public class TrustStoreRestTest extends QpidRestTestCase String name = getTestName(); assertNumberOfTrustStores(1); - createTrustStore(name, true); + createTrustStore(name, true, TestSSLConstants.TRUSTSTORE, TestSSLConstants.TRUSTSTORE_PASSWORD); assertNumberOfTrustStores(2); List> trustStores = getRestTestHelper().getJsonAsList("truststore/" + name); @@ -75,157 +71,73 @@ public class TrustStoreRestTest extends QpidRestTestCase assertTrustStoreAttributes(trustStores.get(0), name, TestSSLConstants.TRUSTSTORE, true); } - public void testDelete() throws Exception + public void testCreateUsingDataUrl() throws Exception { super.setUp(); String name = getTestName(); + byte[] trustStoreAsBytes = FileUtils.readFileAsBytes(TestSSLConstants.TRUSTSTORE); + String dataUrlForTruststore = DataUrlUtils.getDataUrlForBytes(trustStoreAsBytes); assertNumberOfTrustStores(1); - createTrustStore(name, false); - assertNumberOfTrustStores(2); - - int responseCode = getRestTestHelper().submitRequest("truststore/" + name , "DELETE"); - assertEquals("Unexpected response code for provider deletion", 200, responseCode); - - List> trustStore = getRestTestHelper().getJsonAsList("truststore/" + name); - assertNotNull("details should not be null", trustStore); - assertTrue("details should be empty as the truststore no longer exists", trustStore.isEmpty()); - - //check only the default systests trust store remains - List> trustStores = assertNumberOfTrustStores(1); - Map truststore = trustStores.get(0); - assertTrustStoreAttributes(truststore, TestBrokerConfiguration.ENTRY_NAME_SSL_TRUSTSTORE, - QPID_HOME + "/../" + TestSSLConstants.BROKER_TRUSTSTORE, false); - } - public void testDeleteFailsWhenTrustStoreInUse() throws Exception - { - String name = "testDeleteFailsWhenTrustStoreInUse"; - - //add a new trust store config to use - Map sslTrustStoreAttributes = new HashMap(); - sslTrustStoreAttributes.put(TrustStore.NAME, name); - sslTrustStoreAttributes.put(FileTrustStore.PATH, TestSSLConstants.TRUSTSTORE); - sslTrustStoreAttributes.put(FileTrustStore.PASSWORD, TestSSLConstants.TRUSTSTORE_PASSWORD); - getBrokerConfiguration().addObjectConfiguration(TrustStore.class,sslTrustStoreAttributes); - - //add the SSL port using it - Map sslPortAttributes = new HashMap(); - sslPortAttributes.put(Port.TRANSPORTS, Collections.singleton(Transport.SSL)); - sslPortAttributes.put(Port.PORT, DEFAULT_SSL_PORT); - sslPortAttributes.put(Port.NAME, TestBrokerConfiguration.ENTRY_NAME_SSL_PORT); - sslPortAttributes.put(Port.AUTHENTICATION_PROVIDER, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER); - sslPortAttributes.put(Port.KEY_STORE, TestBrokerConfiguration.ENTRY_NAME_SSL_KEYSTORE); - sslPortAttributes.put(Port.TRUST_STORES, Collections.singleton(name)); - getBrokerConfiguration().addObjectConfiguration(Port.class, sslPortAttributes); + createTrustStore(name, false, dataUrlForTruststore, TestSSLConstants.TRUSTSTORE_PASSWORD); - super.setUp(); - - //verify the truststore is there assertNumberOfTrustStores(2); - List> trustStore = getRestTestHelper().getJsonAsList("truststore/" + name); - assertNotNull("details should not be null", trustStore); - assertTrustStoreAttributes(trustStore.get(0), name, TestSSLConstants.TRUSTSTORE, false); - - //try to delete it, which should fail as it is in use - int responseCode = getRestTestHelper().submitRequest("truststore/" + name , "DELETE"); - assertEquals("Unexpected response code for provider deletion", 409, responseCode); + List> trustStores = getRestTestHelper().getJsonAsList("truststore/" + name); + assertNotNull("details cannot be null", trustStores); - //check its still there - assertNumberOfTrustStores(2); - trustStore = getRestTestHelper().getJsonAsList("truststore/" + name); - assertNotNull("details should not be null", trustStore); - assertTrustStoreAttributes(trustStore.get(0), name, TestSSLConstants.TRUSTSTORE, false); + assertTrustStoreAttributes(trustStores.get(0), name, dataUrlForTruststore, false); } - public void testUpdateWithGoodPathSucceeds() throws Exception + public void testDelete() throws Exception { super.setUp(); String name = getTestName(); assertNumberOfTrustStores(1); - createTrustStore(name, false); + createTrustStore(name, false, TestSSLConstants.TRUSTSTORE, TestSSLConstants.TRUSTSTORE_PASSWORD); assertNumberOfTrustStores(2); - Map attributes = new HashMap(); - attributes.put(TrustStore.NAME, name); - attributes.put(FileTrustStore.PATH, TestSSLConstants.TRUSTSTORE); - - int responseCode = getRestTestHelper().submitRequest("truststore/" + name , "PUT", attributes); - assertEquals("Unexpected response code for truststore update", 200, responseCode); + getRestTestHelper().submitRequest("truststore/" + name , "DELETE", HttpServletResponse.SC_OK); List> trustStore = getRestTestHelper().getJsonAsList("truststore/" + name); assertNotNull("details should not be null", trustStore); + assertTrue("details should be empty as the truststore no longer exists", trustStore.isEmpty()); - assertTrustStoreAttributes(trustStore.get(0), name, TestSSLConstants.TRUSTSTORE, false); + //check only the default systests trust store remains + List> trustStores = assertNumberOfTrustStores(1); + Map truststore = trustStores.get(0); + assertTrustStoreAttributes(truststore, TestBrokerConfiguration.ENTRY_NAME_SSL_TRUSTSTORE, + QPID_HOME + "/../" + TestSSLConstants.BROKER_TRUSTSTORE, false); } - public void testUpdateWithNonExistentPathFails() throws Exception - { - super.setUp(); - - String name = getTestName(); - - assertNumberOfTrustStores(1); - createTrustStore(name, false); - assertNumberOfTrustStores(2); - Map attributes = new HashMap(); - attributes.put(TrustStore.NAME, name); - attributes.put(FileTrustStore.PATH, "does.not.exist"); - - int responseCode = getRestTestHelper().submitRequest("truststore/" + name , "PUT", attributes); - assertEquals("Unexpected response code for trust store update", 409, responseCode); - - List> trustStore = getRestTestHelper().getJsonAsList("truststore/" + name); - assertNotNull("details should not be null", trustStore); - - //verify the details remain unchanged - assertTrustStoreAttributes(trustStore.get(0), name, TestSSLConstants.TRUSTSTORE, false); - } - - public void testUpdatePeersOnly() throws Exception + public void testUpdate() throws Exception { super.setUp(); String name = getTestName(); assertNumberOfTrustStores(1); - createTrustStore(name, false); + createTrustStore(name, false, TestSSLConstants.TRUSTSTORE, TestSSLConstants.TRUSTSTORE_PASSWORD); assertNumberOfTrustStores(2); - //update the peersOnly attribute from false to true Map attributes = new HashMap(); attributes.put(TrustStore.NAME, name); - attributes.put(FileTrustStore.PEERS_ONLY, true); + attributes.put(FileTrustStore.PATH, TestSSLConstants.TRUSTSTORE); - int responseCode = getRestTestHelper().submitRequest("truststore/" + name , "PUT", attributes); - assertEquals("Unexpected response code for trust store update", 200, responseCode); + getRestTestHelper().submitRequest("truststore/" + name , "PUT", attributes, HttpServletResponse.SC_OK); List> trustStore = getRestTestHelper().getJsonAsList("truststore/" + name); assertNotNull("details should not be null", trustStore); - assertTrustStoreAttributes(trustStore.get(0), name, TestSSLConstants.TRUSTSTORE, true); - - //Update peersOnly to clear it (i.e go from from true to null, which will default to false) - attributes = new HashMap(); - attributes.put(TrustStore.NAME, name); - attributes.put(FileTrustStore.PEERS_ONLY, null); - - responseCode = getRestTestHelper().submitRequest("truststore/" + name , "PUT", attributes); - assertEquals("Unexpected response code for trust store update", 200, responseCode); - - trustStore = getRestTestHelper().getJsonAsList("truststore/" + name); - assertNotNull("details should not be null", trustStore); - assertTrustStoreAttributes(trustStore.get(0), name, TestSSLConstants.TRUSTSTORE, false); } - private List> assertNumberOfTrustStores(int numberOfTrustStores) throws IOException, - JsonParseException, JsonMappingException + private List> assertNumberOfTrustStores(int numberOfTrustStores) throws Exception { List> trustStores = getRestTestHelper().getJsonAsList("truststore"); assertNotNull("trust stores should not be null", trustStores); @@ -234,17 +146,16 @@ public class TrustStoreRestTest extends QpidRestTestCase return trustStores; } - private void createTrustStore(String name, boolean peersOnly) throws IOException, JsonGenerationException, JsonMappingException + private void createTrustStore(String name, boolean peersOnly, final String truststorePath, final String truststorePassword) throws Exception { Map trustStoreAttributes = new HashMap(); trustStoreAttributes.put(TrustStore.NAME, name); //deliberately using the client trust store to differentiate from the one we are already for broker - trustStoreAttributes.put(FileTrustStore.PATH, TestSSLConstants.TRUSTSTORE); - trustStoreAttributes.put(FileTrustStore.PASSWORD, TestSSLConstants.TRUSTSTORE_PASSWORD); + trustStoreAttributes.put(FileTrustStore.PATH, truststorePath); + trustStoreAttributes.put(FileTrustStore.PASSWORD, truststorePassword); trustStoreAttributes.put(FileTrustStore.PEERS_ONLY, peersOnly); - int responseCode = getRestTestHelper().submitRequest("truststore/" + name, "PUT", trustStoreAttributes); - assertEquals("Unexpected response code", 201, responseCode); + getRestTestHelper().submitRequest("truststore/" + name, "PUT", trustStoreAttributes, HttpServletResponse.SC_CREATED); } private void assertTrustStoreAttributes(Map truststore, String name, String path, boolean peersOnly) -- cgit v1.2.1 From d6ad905aa5da8b0c4be507c87cdae735d778154f Mon Sep 17 00:00:00 2001 From: Keith Wall Date: Tue, 27 Jan 2015 13:27:05 +0000 Subject: QPID-6336: [Java Broker] Change 0-8..0-91 path to await the receiver being closed before continuing with the next connection attempt Based on work by Oleksandr Rudyy git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1655034 13f79535-47bb-0310-9956-ffa450edef68 --- .../failover/MultipleBrokersFailoverTest.java | 28 ++++++++-------------- .../java/org/apache/qpid/client/ssl/SSLTest.java | 24 +++++++++++++++++++ .../unit/client/connection/ConnectionTest.java | 1 - 3 files changed, 34 insertions(+), 19 deletions(-) (limited to 'qpid/java/systests/src') diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/client/failover/MultipleBrokersFailoverTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/client/failover/MultipleBrokersFailoverTest.java index 15ec0f9a4d..c59b0ecf34 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/client/failover/MultipleBrokersFailoverTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/client/failover/MultipleBrokersFailoverTest.java @@ -38,7 +38,6 @@ import org.apache.qpid.client.AMQConnection; import org.apache.qpid.client.AMQConnectionURL; import org.apache.qpid.jms.ConnectionListener; import org.apache.qpid.test.utils.QpidBrokerTestCase; -import org.apache.qpid.test.utils.TestUtils; import org.apache.qpid.util.FileUtils; public class MultipleBrokersFailoverTest extends QpidBrokerTestCase implements ConnectionListener @@ -48,9 +47,10 @@ public class MultipleBrokersFailoverTest extends QpidBrokerTestCase implements C private static final String FAILOVER_VIRTUAL_HOST = "failover"; private static final String NON_FAILOVER_VIRTUAL_HOST = "nonfailover"; private static final String BROKER_PORTION_FORMAT = "tcp://localhost:%d?connectdelay='%d',retries='%d'"; - private static final int FAILOVER_RETRIES = 1; - private static final int FAILOVER_CONNECTDELAY = 1000; - private static final int FAILOVER_FACTOR = 4; + private static final int FAILOVER_RETRIES = 0; + private static final int FAILOVER_CONNECTDELAY = 0; + private static final int FAILOVER_AWAIT_TIME = 10000; + private int[] _brokerPorts; private AMQConnectionURL _connectionURL; @@ -169,7 +169,7 @@ public class MultipleBrokersFailoverTest extends QpidBrokerTestCase implements C killBroker(_brokerPorts[1]); - awaitForFailoverCompletion(FAILOVER_CONNECTDELAY * _brokerPorts.length * FAILOVER_FACTOR); + awaitForFailoverCompletion(FAILOVER_AWAIT_TIME); assertEquals("Failover is not started as expected", 0, _failoverStarted.getCount()); assertSendReceive(2); @@ -185,7 +185,7 @@ public class MultipleBrokersFailoverTest extends QpidBrokerTestCase implements C stopBroker(_brokerPorts[1]); - awaitForFailoverCompletion(FAILOVER_CONNECTDELAY * _brokerPorts.length * FAILOVER_FACTOR); + awaitForFailoverCompletion(FAILOVER_AWAIT_TIME); assertEquals("Failover is not started as expected", 0, _failoverStarted.getCount()); assertSendReceive(1); @@ -214,20 +214,12 @@ public class MultipleBrokersFailoverTest extends QpidBrokerTestCase implements C } } - private void awaitForFailoverCompletion(long delay) + private void awaitForFailoverCompletion(long delay) throws Exception { _logger.info("Awaiting Failover completion.."); - try - { - if (!_failoverComplete.await(delay, TimeUnit.MILLISECONDS)) - { - _logger.warn("Test thread stack:\n\n" + TestUtils.dumpThreads()); - fail("Failover did not complete"); - } - } - catch (InterruptedException e) + if (!_failoverComplete.await(delay, TimeUnit.MILLISECONDS)) { - fail("Test was interrupted:" + e.getMessage()); + fail("Failover did not complete within " + delay + "ms."); } } @@ -239,7 +231,7 @@ public class MultipleBrokersFailoverTest extends QpidBrokerTestCase implements C receivedMessage instanceof TextMessage); } - private void init(int acknowledgeMode, boolean startConnection) throws JMSException + private void init(int acknowledgeMode, boolean startConnection) throws Exception { boolean isTransacted = acknowledgeMode == Session.SESSION_TRANSACTED ? true : false; diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/client/ssl/SSLTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/client/ssl/SSLTest.java index 1dba5ced9d..7c82ea8e55 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/client/ssl/SSLTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/client/ssl/SSLTest.java @@ -94,6 +94,29 @@ public class SSLTest extends QpidBrokerTestCase } } + public void testSSLConnectionToPlainPortRejected() throws Exception + { + if (shouldPerformTest()) + { + super.setUp(); + + String url = "amqp://guest:guest@test/?brokerlist='tcp://localhost:%s" + + "?ssl='true''"; + + url = String.format(url,QpidBrokerTestCase.DEFAULT_PORT); + + try + { + getConnection(new AMQConnectionURL(url)); + fail("Exception not thrown"); + } + catch (JMSException e) + { + assertTrue("Unexpected exception message", e.getMessage().contains("Unrecognized SSL message, plaintext connection?")); + } + } + } + public void testHostVerificationIsOnByDefault() throws Exception { if (shouldPerformTest()) @@ -116,6 +139,7 @@ public class SSLTest extends QpidBrokerTestCase try { getConnection(new AMQConnectionURL(url)); + fail("Exception not thrown"); } catch(JMSException e) { diff --git a/qpid/java/systests/src/test/java/org/apache/qpid/test/unit/client/connection/ConnectionTest.java b/qpid/java/systests/src/test/java/org/apache/qpid/test/unit/client/connection/ConnectionTest.java index ed03e83292..191f9d72cf 100644 --- a/qpid/java/systests/src/test/java/org/apache/qpid/test/unit/client/connection/ConnectionTest.java +++ b/qpid/java/systests/src/test/java/org/apache/qpid/test/unit/client/connection/ConnectionTest.java @@ -81,7 +81,6 @@ public class ConnectionTest extends QpidBrokerTestCase + "&temporaryQueueExchange='tmp.direct'" + "&temporaryTopicExchange='tmp.topic'"); - System.err.println(url.toString()); conn = new AMQConnection(url); -- cgit v1.2.1