You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@qpid.apache.org by kw...@apache.org on 2018/03/12 16:44:09 UTC
[1/8] qpid-broker-j git commit: NO-JIRA: [Broker-J] [System Tests]
Remove logging tests
Repository: qpid-broker-j
Updated Branches:
refs/heads/master 7ce54800d -> cec889db6
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/systests/src/test/java/org/apache/qpid/server/logging/ConsumerLoggingTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/server/logging/ConsumerLoggingTest.java b/systests/src/test/java/org/apache/qpid/server/logging/ConsumerLoggingTest.java
deleted file mode 100644
index ca7eca6..0000000
--- a/systests/src/test/java/org/apache/qpid/server/logging/ConsumerLoggingTest.java
+++ /dev/null
@@ -1,352 +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.server.logging;
-
-import java.io.IOException;
-import java.util.List;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.Topic;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.qpid.server.model.Consumer;
-
-/**
- * Subscription
- *
- * The Subscription test suite validates that the follow log messages as specified in the Functional Specification.
- *
- * This suite of tests validate that the Subscription messages occur correctly and according to the following format:
- *
- * SUB-1001 : Create : [Durable] [Arguments : <key=value>]
- * SUB-1002 : Close
- * SUB-1003 : State : <state>
- */
-public class ConsumerLoggingTest extends AbstractTestLogging
-{
- private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerLoggingTest.class);
-
- static final String SUB_PREFIX = "SUB-";
-
- private Connection _connection;
- private Session _session;
- private Queue _queue;
- private Topic _topic;
-
- @Override
- public void setUp() throws Exception
- {
- setSystemProperty(Consumer.SUSPEND_NOTIFICATION_PERIOD, "100");
- super.setUp();
-
- _connection = getConnection();
-
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- final String queueName = getTestQueueName() + "Queue";
- final String topicName = getTestQueueName() + "Topic";
- _queue = createTestQueue(_session, queueName);
- _topic = createTopic(_connection, topicName);
-
- //Remove broker startup logging messages
- _monitor.markDiscardPoint();
- }
-
- /**
- * Description:
- * When a Subscription is created it will be logged. This test validates that Subscribing to a transient queue is correctly logged.
- * Input:
- *
- * 1. Running Broker
- * 2. Create a new Subscription to a transient queue/topic.
- * Output: 6
- *
- * <date> SUB-1001 : Create
- *
- * Validation Steps:
- * 3. The SUB ID is correct
- *
- * @throws java.io.IOException - if there is a problem getting the matches
- * @throws javax.jms.JMSException - if there is a problem creating the consumer
- */
- public void testSubscriptionCreate() throws JMSException, IOException
- {
- _session.createConsumer(_queue);
-
- //Validate
-
- //Ensure that we wait for the SUB log message
- waitAndFindMatches("SUB-1001");
-
- List<String> results = findMatches(SUB_PREFIX);
-
- assertEquals("Result set larger than expected.", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- validateMessageID("SUB-1001", log);
-
- assertEquals("Log Message not as expected", "Create", getMessageString(fromMessage(log)));
- }
-
- /**
- * Description:
- * The creation of a Durable Subscription, such as a JMS DurableTopicSubscriber will result in an extra Durable tag being included in the Create log message
- * Input:
- *
- * 1. Running Broker
- * 2. Creation of a JMS DurableTopicSubiber
- * Output:
- *
- * <date> SUB-1001 : Create : Durable
- *
- * Validation Steps:
- * 3. The SUB ID is correct
- * 4. The Durable tag is present in the message
- * NOTE: A Subscription is not Durable, the queue it consumes from is.
- *
- * @throws java.io.IOException - if there is a problem getting the matches
- * @throws javax.jms.JMSException - if there is a problem creating the consumer
- */
- public void testSubscriptionCreateDurable() throws JMSException, IOException
- {
- _session.createDurableSubscriber(_topic, getName());
-
- //Validate
- //Ensure that we wait for the SUB log message
- waitAndFindMatches("SUB-1001");
-
- List<String> results = findMatches(SUB_PREFIX);
-
- assertEquals("Result set not as expected.", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- validateMessageID("SUB-1001", log);
-
- String message = getMessageString(fromMessage(log));
- assertTrue("Durable not on log message:" + message, message.contains("Durable"));
- }
-
- /**
- * Description:
- * The creation of a Subscriber with a JMS Selector will result in the Argument field being populated. These argument key/value pairs are then shown in the log message.
- * Input:
- *
- * 1. Running Broker
- * 2. Subscriber created with a JMS Selector.
- * Output:
- *
- * <date> SUB-1001 : Create : Arguments : <key=value>
- *
- * Validation Steps:
- * 3. The SUB ID is correct
- * 4. Argument tag is present in the message
- *
- * @throws java.io.IOException - if there is a problem getting the matches
- * @throws javax.jms.JMSException - if there is a problem creating the consumer
- */
- public void testSubscriptionCreateWithArguments() throws JMSException, IOException
- {
- final String SELECTOR = "Selector='True'";
- _session.createConsumer(_queue, SELECTOR);
-
- //Validate
-
- //Ensure that we wait for the SUB log message
- waitAndFindMatches("SUB-1001");
-
- List<String> results = findMatches(SUB_PREFIX);
-
- assertEquals("Result set larger than expected.", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- validateMessageID("SUB-1001", log);
-
- String message = getMessageString(fromMessage(log));
- assertTrue("Selector not on log message:" + message, message.contains(SELECTOR));
- }
-
- /**
- * Description:
- * The final combination of SUB-1001 Create messages involves the creation of a Durable Subscription that also contains a set of Arguments, such as those provided via a JMS Selector.
- * Input:
- *
- * 1. Running Broker
- * 2. Java Client creates a Durable Subscription with Selector
- * Output:
- *
- * <date> SUB-1001 : Create : Durable Arguments : <key=value>
- *
- * Validation Steps:
- * 3. The SUB ID is correct
- * 4. The tag Durable is present in the message
- * 5. The Arguments are present in the message
- *
- * @throws java.io.IOException - if there is a problem getting the matches
- * @throws javax.jms.JMSException - if there is a problem creating the consumer
- */
- public void testSubscriptionCreateDurableWithArguments() throws JMSException, IOException
- {
- final String SELECTOR = "Selector='True'";
- _session.createDurableSubscriber(_topic, getName(), SELECTOR, false);
-
- //Validate
-
- //Ensure that we wait for the SUB log message
- waitAndFindMatches("SUB-1001");
-
- List<String> results = findMatches(SUB_PREFIX);
-
- assertEquals("Result set larger than expected.", 1, results.size());
-
- String log = getLogMessage(results, 0);
-
- validateMessageID("SUB-1001", log);
-
- String message = getMessageString(fromMessage(log));
- assertTrue("Durable not on log message:" + message, message.contains("Durable"));
- assertTrue("Selector not on log message:" + message, message.contains(SELECTOR));
- }
-
- /**
- * Description:
- * When a Subscription is closed it will log this so that it can be correlated with the Create.
- * Input:
- *
- * 1. Running Broker
- * 2. Client with a subscription.
- * 3. The subscription is then closed.
- * Output:
- *
- * <date> SUB-1002 : Close
- *
- * Validation Steps:
- * 1. The SUB ID is correct
- * 2. There must be a SUB-1001 Create message preceding this message
- * 3. This must be the last message from the given Subscription
- *
- * @throws java.io.IOException - if there is a problem getting the matches
- * @throws javax.jms.JMSException - if there is a problem creating the consumer
- */
- public void testSubscriptionClose() throws JMSException, IOException
- {
- _session.createConsumer(_queue).close();
-
- //Validate
- //Ensure that we wait for the SUB log message
- waitAndFindMatches("SUB-1002");
-
- List<String> results = findMatches(SUB_PREFIX);
-
- //3
- assertEquals("Result set larger than expected.", 2, results.size());
-
- // 2
- String log = getLogMessage(results, 0);
- validateMessageID("SUB-1001", log);
- // 1
- log = getLogMessage(results, 1);
- validateMessageID("SUB-1002", log);
-
- String message = getMessageString(fromMessage(log));
- assertEquals("Log message is not close", "Close", message);
-
- }
-
- /**
- * Description:
- * When a Subscription fills its prefetch it will become suspended. This
- * will be logged as a SUB-1003 message.
- * Input:
- *
- * 1. Running broker
- * 2. Message Producer to put more data on the queue than the client's prefetch
- * 3. Client that ensures that its prefetch becomes full
- * Output:
- *
- * <date> SUB-1003 : State : <state>
- *
- * Validation Steps:
- * 1. The SUB ID is correct
- * 2. The state is correct
- *
- * @throws java.io.IOException - if there is a problem getting the matches
- * @throws javax.jms.JMSException - if there is a problem creating the consumer
- */
- public void testSubscriptionSuspend() throws Exception, IOException
- {
- //Close session with large prefetch
- _connection.close();
- int PREFETCH = 15;
- _connection = getConnectionWithPrefetch(PREFETCH);
- _session = _connection.createSession(true, Session.SESSION_TRANSACTED);
-
-
- 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
- // 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();
-
- Thread.sleep(2500l);
-
- LOGGER.debug("Looking for SUB-1003s");
- List<String> results = waitAndFindMatches("SUB-1003");
-
- assertTrue("Expected at least two suspension messages, but got " + results.size(), results.size() >= 2);
-
- // consume all messages to hopefully resume the consumer
- Message msg;
- for (int i = 0; i < SEND_COUNT; ++i)
- {
- msg = consumer.receive(1000);
- assertNotNull("Message not retrieved", msg);
- }
- _session.commit();
-
- int count = waitAndFindMatches("SUB-1003").size();
- Thread.sleep(2000l);
- assertEquals("More suspension messages were received unexpectedly", count, waitAndFindMatches("SUB-1003").size());
-
- _connection.close();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/systests/src/test/java/org/apache/qpid/server/logging/DurableQueueLoggingTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/server/logging/DurableQueueLoggingTest.java b/systests/src/test/java/org/apache/qpid/server/logging/DurableQueueLoggingTest.java
deleted file mode 100644
index aaad678..0000000
--- a/systests/src/test/java/org/apache/qpid/server/logging/DurableQueueLoggingTest.java
+++ /dev/null
@@ -1,312 +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.server.logging;
-
-import org.apache.qpid.QpidException;
-import org.apache.qpid.client.AMQSession;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.naming.NamingException;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * The Queue test suite validates that the follow log messages as specified in
- * the Functional Specification.
- *
- * This suite of tests validate that the Queue messages occur correctly and
- * according to the following format:
- *
- * QUE-1001 : Create : [AutoDelete] [Durable|Transient] [Priority:<levels>] [Owner:<name>]
- */
-public class DurableQueueLoggingTest extends AbstractTestLogging
-{
- protected String DURABLE = "Durable";
- protected String TRANSIENT = "Transient";
- protected boolean _durable;
-
- protected Connection _connection;
- protected Session _session;
- private static final String QUEUE_PREFIX = "QUE-";
- private static int PRIORITIES = 6;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- //Ensure we only have logs from our test
- _monitor.markDiscardPoint();
-
- _connection = getConnection();
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- _durable = true;
- }
-
- /**
- * Description:
- * When a simple transient queue is created then a QUE-1001 create message
- * is expected to be logged.
- * Input:
- * 1. Running broker
- * 2. Persistent Queue is created from a client
- * Output:
- *
- * <date> QUE-1001 : Create : Owner: '<name>' Durable
- *
- * Validation Steps:
- * 3. The QUE ID is correct
- * 4. The Durable tag is present in the message
- * 5. The Owner is as expected
- *
- * @throws javax.jms.JMSException
- * @throws javax.naming.NamingException
- * @throws java.io.IOException
- */
- public void testQueueCreateDurableExclusive() throws NamingException, JMSException, IOException
- {
- String queueName= getTestQueueName();
- // To force a queue Creation Event we need to create a consumer.
- Queue queue = (Queue) _session.createQueue("direct://amq.direct/" + queueName + "/" + queueName + "?durable='" + _durable + "'&exclusive='true'");
-
- _session.createConsumer(queue);
-
- List<String> results = waitForMesssage();
-
- String clientID = _connection.getClientID();
- assertNotNull("clientID should not be null", clientID);
-
- // in 0-8/9/9-1 an exclusive queue will be deleted when the connection is closed, so auto-delete is true.
- // in 0-10 an exclusive queue outlasts the creating connection and so is not auto-delete
- // the queue only has owner as the client-id in 0-8/9/91 where exclusivity is taken to mean exclusive to the
- // client-id in perpetuity. For 0-10 exclusive means exclusive to a session.
- validateQueueProperties(results, false, !(isBroker010() || _durable), (_durable && !isBroker010()) ? clientID : null);
- }
-
- /**
- * Description:
- * When a simple transient queue is created then a QUE-1001 create message
- * is expected to be logged.
- * Input:
- * 1. Running broker
- * 2. Persistent Queue is created from a client
- * Output:
- *
- * <date> QUE-1001 : Create : Owner: '<name>' Durable
- *
- * Validation Steps:
- * 3. The QUE ID is correct
- * 4. The Durable tag is present in the message
- * 5. The Owner is as expected
- *
- * @throws javax.jms.JMSException
- * @throws javax.naming.NamingException
- * @throws java.io.IOException
- */
- public void testQueueCreateDurable() throws NamingException, JMSException, IOException
- {
- String queueName = getTestQueueName();
-
- // To force a queue Creation Event we need to create a consumer.
- Queue queue = (Queue) _session.createQueue("direct://amq.direct/" + queueName + "/" + queueName + "?durable='" + _durable + "'");
-
- _session.createConsumer(queue);
-
- List<String> results = waitForMesssage();
-
- validateQueueProperties(results, false, false, null);
- }
-
- /**
- * Description:
- * When a simple transient queue is created then a QUE-1001 create message
- * is expected to be logged.
- * Input:
- * 1. Running broker
- * 2. AutoDelete Persistent Queue is created from a client
- * Output:
- *
- * <date> QUE-1001 : Create : Owner: '<name>' AutoDelete Durable
- *
- * Validation Steps:
- * 3. The QUE ID is correct
- * 4. The Durable tag is present in the message
- * 5. The Owner is as expected
- * 6. The AutoDelete tag is present in the message
- *
- * @throws javax.jms.JMSException
- * @throws javax.naming.NamingException
- * @throws java.io.IOException
- */
- public void testQueueCreatePersistentAutoDelete() throws NamingException, JMSException, IOException
- {
- String queueName = getTestQueueName();
- // To force a queue Creation Event we need to create a consumer.
- Queue queue = (Queue) _session.createQueue("direct://amq.direct/"+queueName+"/"+queueName+"?durable='"+_durable+"'&autodelete='true'");
-
- _session.createConsumer(queue);
-
- List<String> results = waitForMesssage();
-
- validateQueueProperties(results, false, true, null);
- }
-
- /**
- * Description:
- * When a simple transient queue is created then a QUE-1001 create message
- * is expected to be logged.
- * Input:
- * 1. Running broker
- * 2. Persistent Queue is created from a client
- * Output:
- *
- * <date> QUE-1001 : Create : Owner: '<name>' Durable Priority:<levels>
- *
- * Validation Steps:
- * 3. The QUE ID is correct
- * 4. The Durable tag is present in the message
- * 5. The Owner is as expected
- * 6. The Priority level is correctly set
- *
- * @throws javax.jms.JMSException
- * @throws javax.naming.NamingException
- * @throws java.io.IOException
- */
- public void testCreateQueuePersistentPriority() throws NamingException, JMSException, IOException, QpidException
- {
- // To Create a Priority queue we need to use AMQSession specific code
- final Map<String, Object> arguments = new HashMap<String, Object>();
- arguments.put("x-qpid-priorities", PRIORITIES);
- // Need to create a queue that does not exist so use test name
- final String queueName = getTestQueueName();
- ((AMQSession) _session).createQueue(queueName, false, _durable, false, arguments);
-
- Queue queue = (Queue) _session.createQueue("direct://amq.direct/"+queueName+"/"+queueName+"?durable='"+_durable+"'&autodelete='false'");
-
-
- //Need to create a Consumer to ensure that the log has had time to write
- // as the above Create is Asynchronous
- _session.createConsumer(queue);
-
- List<String> results = waitForMesssage();
-
- // Only 1 Queue message should hav been logged
- assertEquals("Result set size not as expected", 1, results.size());
-
- validateQueueProperties(results, true, false, null);
- }
-
- /**
- * Description:
- * When a simple transient queue is created then a QUE-1001 create message
- * is expected to be logged.
- * Input:
- * 1. Running broker
- * 2. AutoDelete Persistent Queue is created from a client
- * Output:
- *
- * <date> QUE-1001 : Create : Owner: '<name>' Durable Priority:<levels>
- *
- * Validation Steps:
- * 3. The QUE ID is correct
- * 4. The Durable tag is present in the message
- * 5. The Owner is as expected
- * 6. The AutoDelete tag is present in the message
- * 7. The Priority level is correctly set
- *
- * @throws javax.jms.JMSException
- * @throws javax.naming.NamingException
- * @throws java.io.IOException
- */
- public void testCreateQueuePersistentAutoDeletePriority() throws NamingException, JMSException, IOException,
- QpidException
- {
- // To Create a Priority queue we need to use AMQSession specific code
- final Map<String, Object> arguments = new HashMap<String, Object>();
- arguments.put("x-qpid-priorities", PRIORITIES);
- // Need to create a queue that does not exist so use test name
- final String queueName = getTestQueueName() + "-autoDeletePriority";
- ((AMQSession) _session).createQueue(queueName, true, _durable, false, arguments);
-
- Queue queue = (Queue) _session.createQueue("direct://amq.direct/"+queueName+"/"+queueName+"?durable='"+_durable+"'&autodelete='true'");
-
-
- //Need to create a Consumer to ensure that the log has had time to write
- // as the above Create is Asynchronous
- _session.createConsumer(queue);
-
- List<String> results = waitForMesssage();
-
- validateQueueProperties(results, true, true, null);
- }
-
- private List<String> waitForMesssage() throws IOException
- {
- // Validation
- // Ensure we have received the QUE log msg.
- waitForMessage("QUE-1001");
-
- List<String> results = findMatches(QUEUE_PREFIX);
-
- // Only 1 Queue message should hav been logged
- assertEquals("Result set size not as expected", 1, results.size());
-
- return results;
- }
-
- public void validateQueueProperties(List<String> results, boolean hasPriority, boolean hasAutodelete, String clientID)
- {
- String log = getLogMessage(results, 0);
-
- // Message Should be a QUE-1001
- validateMessageID("QUE-1001", log);
-
- // Queue is Durable
- assertEquals(DURABLE + " keyword not correct in log entry",
- _durable, fromMessage(log).contains(DURABLE));
-
- assertEquals(TRANSIENT + " keyword not correct in log entry.",
- !_durable, fromMessage(log).contains(TRANSIENT));
-
- // Queue is Priority
- assertEquals("Unexpected priority status:" + fromMessage(log), hasPriority,
- fromMessage(log).contains("Priority: " + PRIORITIES));
-
- // Queue is AutoDelete
- assertEquals("Unexpected AutoDelete status:" + fromMessage(log), hasAutodelete,
- fromMessage(log).contains("AutoDelete"));
-
- if(clientID != null)
- {
- assertTrue("Queue does not have correct owner value:" + fromMessage(log),
- fromMessage(log).contains("Owner: " + clientID));
- }
- else
- {
- assertFalse("Queue should not contain Owner tag:" + fromMessage(log),
- fromMessage(log).contains("Owner"));
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/systests/src/test/java/org/apache/qpid/server/logging/ExchangeLoggingTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/server/logging/ExchangeLoggingTest.java b/systests/src/test/java/org/apache/qpid/server/logging/ExchangeLoggingTest.java
deleted file mode 100644
index c8b29a5..0000000
--- a/systests/src/test/java/org/apache/qpid/server/logging/ExchangeLoggingTest.java
+++ /dev/null
@@ -1,247 +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.server.logging;
-
-import java.io.IOException;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-import javax.jms.Topic;
-
-/**
- * Exchange
- *
- * The Exchange test suite validates that the follow log messages as specified in the Functional Specification.
- *
- * This suite of tests validate that the Exchange messages occur correctly and according to the following format:
- *
- * EXH-1001 : Create : [Durable] Type:<value> Name:<value>
- * EXH-1002 : Deleted
- */
-public class ExchangeLoggingTest extends AbstractTestLogging
-{
-
- static final String EXH_PREFIX = "EXH-";
-
- private Connection _connection;
- private Session _session;
- private Topic _topic;
- private String _name;
- private String _type;
- private String _topicName;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
-
- _connection = getConnection();
-
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- _type = "direct";
- _name = getTestQueueName()+ "-exchange";
-
- _topicName = isBroker10() ? _name + "/queue" : "ADDR: " + _name + "/queue" ;
- _topic = _session.createTopic(_topicName);
-
- }
-
- /**
- * Description:
- * When a durable exchange is created an EXH-1001 message is logged with the Durable tag. This will be the first message from this exchange.
- * Input:
- *
- * 1. Running broker
- * 2. Client requests a durable exchange be created.
- * Output:
- *
- * <date> EXH-1001 : Create : Durable Type:<value> Name:<value>
- *
- * Validation Steps:
- * 3. The EXH ID is correct
- * 4. The Durable tag is present in the message
- */
-
- public void testExchangeCreateDurable() throws JMSException, IOException
- {
-
- //Ignore broker startup messages
- _monitor.markDiscardPoint();
-
- createExchangeUsingAmqpManagement(_name, _type, true);
-
- // Ensure we have received the EXH log msg.
- waitForMessage("EXH-1001");
-
- List<String> results = findMatches(EXH_PREFIX);
-
- assertTrue("No Results found for Exchange.", results.size()==1);
-
- validateExchangeCreate(results, true, true);
- }
-
- private void createExchangeUsingAmqpManagement(final String name, final String type, final boolean durable)
- throws JMSException
- {
- final Map<String, Object> attributes = new LinkedHashMap();
- attributes.put("object-path", name);
- attributes.put("qpid-type", type);
- attributes.put("durable", durable);
-
- createEntityUsingAmqpManagement(name, _session, "org.apache.qpid.Exchange", attributes);
- }
-
- /**
- * Description:
- * When an exchange is created an EXH-1001 message is logged. This will be the first message from this exchange.
- * Input:
- *
- * 1. Running broker
- * 2. Client requests an exchange be created.
- * Output:
- *
- * <date> EXH-1001 : Create : Type:<value> Name:<value>
- *
- * Validation Steps:
- * 3. The EXH ID is correct
- */
- public void testExchangeCreate() throws JMSException, IOException
- {
- //Ignore broker startup messages
- _monitor.markDiscardPoint();
-
- createExchangeUsingAmqpManagement(_name, _type, false);
- // Ensure we have received the EXH log msg.
- waitForMessage("EXH-1001");
-
- List<String> results = findMatches(EXH_PREFIX);
-
- assertEquals("Result set larger than expected.", 1, results.size());
-
- validateExchangeCreate(results, false, true);
- }
-
- private void validateExchangeCreate(List<String> results, boolean durable, boolean checkNameAndType)
- {
- String log = getLogMessage(results, 0);
- String message = getMessageString(fromMessage(log));
-
- validateMessageID("EXH-1001", log);
-
- assertTrue("Log Message does not start with create:" + message,
- message.startsWith("Create"));
-
- assertEquals("Unexpected Durable state:" + message, durable,
- message.contains("Durable"));
-
- if(checkNameAndType)
- {
- assertTrue("Log Message does not contain Type:" + message,
- message.contains("Type: " + _type));
- assertTrue("Log Message does not contain Name:" + message,
- message.contains("Name: " + _name));
- }
- }
-
- /**
- * Description:
- * An Exchange can be deleted through an AMQP ExchangeDelete method. When this is successful an EXH-1002 Delete message will be logged. This will be the last message from this exchange.
- * Input:
- *
- * 1. Running broker
- * 2. A new Exchange has been created
- * 3. Client requests that the new exchange be deleted.
- * Output:
- *
- * <date> EXH-1002 : Deleted
- *
- * Validation Steps:
- * 4. The EXH ID is correct
- * 5. There is a corresponding EXH-1001 Create message logged.
- */
- public void testExchangeDelete() throws Exception, IOException
- {
- //Ignore broker startup messages
- _monitor.markDiscardPoint();
-
- createExchangeUsingAmqpManagement(_name, _type, false);
- deleteEntityUsingAmqpManagement(_name, _session, "org.apache.qpid.Exchange");
-
- //Wait and ensure we get our last EXH-1002 msg
- waitForMessage("EXH-1002");
-
- List<String> results = findMatches(EXH_PREFIX);
-
- assertEquals("Result set larger than expected.", 2, results.size());
-
- validateExchangeCreate(results, false, false);
-
- String log = getLogMessage(results, 1);
- validateMessageID("EXH-1002", log);
-
- String message = getMessageString(fromMessage(log));
- assertEquals("Log Message not as expected", "Deleted", message);
-
- }
-
- public void testDiscardedMessage() throws Exception
- {
- //Ignore broker startup messages
- _monitor.markDiscardPoint();
- createExchangeUsingAmqpManagement(_name, _type, false);
-
- if (!(isBroker010() || isBroker10()))
- {
- // Default 0-8..-0-9-1 behaviour is for messages to be rejected (returned to client).
- setTestClientSystemProperty("qpid.default_mandatory", "false");
- }
-
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // Do not create consumer so queue is not created and message will be discarded.
- final MessageProducer producer = _session.createProducer(_topic);
-
- // Sending message
- final TextMessage msg = _session.createTextMessage("msg");
- producer.send(msg);
-
- final String expectedMessageBody = "Discarded Message : Name: \"" + _name + "\" Routing Key: \"queue\"";
-
- // Ensure we have received the EXH log msg.
- waitForMessage("EXH-1003");
-
- List<String> results = findMatches(EXH_PREFIX);
- assertEquals("Result set larger than expected.", 2, results.size());
-
- final String log = getLogMessage(results, 1);
- validateMessageID("EXH-1003", log);
-
- final String message = getMessageString(fromMessage(log));
- assertEquals("Log Message not as expected", expectedMessageBody, message);
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/systests/src/test/java/org/apache/qpid/server/logging/QueueLoggingTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/server/logging/QueueLoggingTest.java b/systests/src/test/java/org/apache/qpid/server/logging/QueueLoggingTest.java
deleted file mode 100644
index 1a9238d..0000000
--- a/systests/src/test/java/org/apache/qpid/server/logging/QueueLoggingTest.java
+++ /dev/null
@@ -1,179 +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.server.logging;
-
-import org.apache.qpid.QpidException;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.failover.FailoverException;
-import org.apache.qpid.server.logging.subjects.AbstractTestLogSubject;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.naming.NamingException;
-import java.io.IOException;
-import java.util.List;
-
-/**
- * The Queue test suite validates that the follow log messages as specified in
- * the Functional Specification.
- *
- * This suite of tests validate that the Queue messages occur correctly and
- * according to the following format:
- *
- * QUE-1002 : Deleted
- */
-public class QueueLoggingTest extends AbstractTestLogging
-{
- protected Connection _connection;
- protected Session _session;
- private static final String QUEUE_PREFIX = "QUE-";
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- //Remove broker startup logging messages
- _monitor.markDiscardPoint();
-
- _connection = getConnection();
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- }
-
- /**
- * Description:
- * An explict QueueDelete request must result in a QUE-1002 Deleted message
- * being logged. This can be done via an explict AMQP QueueDelete method.
- * Input:
- *
- * 1. Running Broker
- * 2. Queue created on the broker with no subscribers
- * 3. Client requests the queue be deleted via a QueueDelete
- * Output:
- *
- * <date> QUE-1002 : Deleted
- *
- * Validation Steps:
- *
- * 4. The QUE ID is correct
- *
- * @throws java.io.IOException
- * @throws javax.jms.JMSException
- * @throws javax.naming.NamingException
- */
- public void testQueueDelete() throws NamingException, JMSException, IOException, FailoverException, QpidException
- {
- // To force a queue Creation Event we need to create a consumer.
- Queue queue = _session.createQueue(getTestQueueName());
-
- _session.createConsumer(queue);
-
- // Delete Queue
- ((AMQSession)_session).sendQueueDelete(queue.getQueueName());
-
- //Perform a synchronous action to ensure that the above log will be on disk
- _session.close();
-
- // Validation
- //Ensure that we wait for the QUE log message
- waitAndFindMatches("QUE-1002");
-
- List<String> results = findMatches(QUEUE_PREFIX);
-
- // Only 1 Queue message should hav been logged
- assertEquals("Result set size not as expected", 2, results.size());
-
- String log = getLogMessage(results, 0);
-
- // Message Should be a QUE-1001
- validateMessageID("QUE-1001", log);
-
- String createdQueueName = AbstractTestLogSubject.getSlice("qu", fromSubject(log));
-
- log = getLogMessage(results, 1);
- // Message Should be a QUE-1002
- validateMessageID("QUE-1002", log);
-
- final String actual = getMessageString(fromMessage(log));
- assertTrue("Log message does not contain expected message. actual : " + actual,
- actual.contains("Deleted"));
-
- assertEquals("Queue Delete not for created queue:", createdQueueName,
- AbstractTestLogSubject.getSlice("qu", fromSubject(log)));
- }
-
-
- /**
- * Description:
- * Closing a JMS connection should delete a temporary queue that it created
- * Input:
- *
- * 1. Running Broker
- * 2. Client creates a temporary queue then disconnects
- * Output:
- *
- * <date> QUE-1002 : Deleted
- *
- * Validation Steps:
- *
- * 3. The QUE ID is correct
- *
- * @throws java.io.IOException
- * @throws javax.jms.JMSException
- * @throws javax.naming.NamingException
- */
- public void testQueueAutoDelete() throws NamingException, JMSException, IOException
- {
- _session.createTemporaryQueue();
-
- _connection.close();
-
- // Validation
- //Ensure that we wait for the QUE log message
- waitAndFindMatches("QUE-1002");
-
- List<String> results = findMatches(QUEUE_PREFIX);
-
- // Only 1 Queue message should hav been logged
- assertEquals("Result set size not as expected", 2, results.size());
-
- String log = getLogMessage(results, 0);
-
- // Message Should be a QUE-1001
- validateMessageID("QUE-1001", log);
-
- String createdQueueName = AbstractTestLogSubject.getSlice("qu", fromSubject(log));
-
- log = getLogMessage(results, 1);
- // Message Should be a QUE-1002
- validateMessageID("QUE-1002", log);
-
- final String actual = getMessageString(fromMessage(log));
- assertTrue("Log message does not contain expected message. actual : " + actual,
- actual.contains("Deleted"));
-
- assertEquals("Queue Delete not for created queue:", createdQueueName,
- AbstractTestLogSubject.getSlice("qu", fromSubject(log)));
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/systests/src/test/java/org/apache/qpid/server/logging/TransientQueueLoggingTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/server/logging/TransientQueueLoggingTest.java b/systests/src/test/java/org/apache/qpid/server/logging/TransientQueueLoggingTest.java
deleted file mode 100644
index 0771c37..0000000
--- a/systests/src/test/java/org/apache/qpid/server/logging/TransientQueueLoggingTest.java
+++ /dev/null
@@ -1,31 +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.server.logging;
-
-public class TransientQueueLoggingTest extends DurableQueueLoggingTest
-{
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- _durable = false;
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/systests/src/test/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java b/systests/src/test/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java
deleted file mode 100644
index e081962..0000000
--- a/systests/src/test/java/org/apache/qpid/server/logging/VirtualHostLoggingTest.java
+++ /dev/null
@@ -1,129 +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.server.logging;
-
-import java.util.Arrays;
-import java.util.List;
-
-import junit.framework.AssertionFailedError;
-
-/**
- * Virtualhost Test Cases
- * The virtualhost test suite validates that the follow log messages as specified in the Functional Specification.
- * <p/>
- * This suite of tests validate that the management console messages occur correctly and according to the following format:
- * <p/>
- * VHT-1001 : Created : <name>
- * VHT-1002 : Work directory : <path>
- * VHT-1003 : Closed
- */
-public class VirtualHostLoggingTest extends AbstractTestLogging
-{
- private static final String VHT_PREFIX = "VHT-";
-
- /**
- * Description:
- * Testing can be performed using the default configuration. The goal is to validate that for each virtualhost defined in the configuration file a VHT-1001 Created message is provided.
- * Input:
- * The default configuration file
- * Output:
- * <p/>
- * <date> VHT-1001 : Created : <name>
- * Validation Steps:
- * <p/>
- * The VHT ID is correct
- * A VHT-1001 is printed for each virtualhost defined in the configuration file.
- * This must be the first message for the specified virtualhost.
- *
- * @throws Exception caused by broker startup
- */
- public void testVirtualhostCreation() throws Exception
- {
- //Wait for the correct VHT message to arrive.
- waitForMessage(VHT_PREFIX + "1001");
-
- //Validate each vhost logs a creation
- List<String> results = findMatches(VHT_PREFIX + "1001");
-
- try
- {
- List<String> vhosts = Arrays.asList("test");
-
- assertEquals("Each vhost did not create a store.", vhosts.size(), results.size());
-
- for (int index = 0; index < results.size(); index++)
- {
- // Retrieve the vhostname from the log entry message 'Created : <vhostname>'
- String result = getLogMessage(results, index);
- String vhostName = getMessageString(fromMessage(result)).split(" ")[2];
-
- assertTrue("Virtualhost named in log not found in config file:" + vhostName + ":" + vhosts, vhosts.contains(vhostName));
- }
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
-
- /**
- * Description:
- * Testing can be performed using the default configuration. During broker shutdown a VHT-1002 Closed message will be printed for each of the configured virtualhosts. For every virtualhost that was started a close must be logged. After the close message has been printed no further logging will be performed by this virtualhost.
- * Input:
- * The default configuration file
- * Output:
- * <p/>
- * <date> VHT-1002 : Closed
- * Validation Steps:
- * <p/>
- * The VHT ID is correct
- * This is the last VHT message for the given virtualhost.
- *
- * @throws Exception caused by broker startup
- */
- public void testVirtualhostClosure() throws Exception
- {
- if (isJavaBroker() && isInternalBroker())
- {
- stopDefaultBroker();
-
- // Wait for the correct VHT message to arrive.
- waitForMessage(VHT_PREFIX + "1002");
-
- // Validate each vhost logs a closure
- List<String> results = findMatches(VHT_PREFIX + "1002");
-
- try
- {
- assertEquals("Each vhost did not close their store.", 1, results.size());
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
- throw afe;
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/systests/src/test/java/org/apache/qpid/util/LogMonitor.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/util/LogMonitor.java b/systests/src/test/java/org/apache/qpid/util/LogMonitor.java
deleted file mode 100644
index 2203694..0000000
--- a/systests/src/test/java/org/apache/qpid/util/LogMonitor.java
+++ /dev/null
@@ -1,310 +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.util;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.LineNumberReader;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Utility to simplify the monitoring of the output of a log file
- */
-public class LogMonitor
-{
- private static final Logger LOGGER = LoggerFactory.getLogger(LogMonitor.class);
-
- // The file that the log statements will be written to.
- private final File _logfile;
-
- private int _linesToSkip = 0;
-
- /**
- * Create a new LogMonitor on the specified file if the file does not exist
- * or the value is null then a new Log4j appender will be added and
- * monitoring set up on that appender.
- *
- * NOTE: for the appender to receive any value the RootLogger will need to
- * have the level correctly configured.ng
- *
- * @param file the file to monitor
- */
- public LogMonitor(File file)
- {
- if (file != null)
- {
- if (file.exists())
- {
- _logfile = file;
- }
- else
- {
- throw new IllegalArgumentException("File to be monitored does not exist.");
- }
- }
- else
- {
- throw new IllegalArgumentException("File to be monitored is not specified.");
- }
-
- LOGGER.info("Created LogMonitor. Monitoring file: " + _logfile.getAbsolutePath());
- }
-
- /**
- * Checks the log file for a given message to appear and returns all
- * instances of that appearance.
- *
- * @param message the message to wait for in the log
- * @param wait the time in ms to wait for the message to occur
- * @return true if the message was found
- *
- * @throws java.io.FileNotFoundException if the Log file can no longer be found
- * @throws IOException thrown when reading the log file
- */
- public List<String> waitAndFindMatches(String message, long wait)
- throws FileNotFoundException, IOException
- {
- if (waitForMessage(message, wait))
- {
- return findMatches(message);
- }
- else
- {
- return new LinkedList<String>();
- }
- }
-
- /**
- * Checks the log for instances of the search string. If the caller
- * has previously called {@link #markDiscardPoint()}, lines up until the discard
- * point are not considered.
- *
- * The pattern parameter can take any valid argument used in String.contains()
- *
- * {@see String.contains(CharSequences)}
- *
- * @param pattern the search string
- *
- * @return a list of matching lines from the log
- *
- * @throws IOException if there is a problem with the file
- */
- public List<String> findMatches(String pattern) throws IOException
- {
-
- List<String> results = new LinkedList<String>();
-
- LineNumberReader reader = new LineNumberReader(new FileReader(_logfile));
- try
- {
- while (reader.ready())
- {
- String line = reader.readLine();
- if (reader.getLineNumber() > _linesToSkip && line.contains(pattern))
- {
- results.add(line);
- }
- }
- }
- finally
- {
- reader.close();
- }
-
- return results;
- }
-
- public Map<String, List<String>> findMatches(String... pattern) throws IOException
- {
-
- Map<String, List<String>> results= new HashMap<String, List<String>>();
- for (String p : pattern)
- {
- results.put(p, new LinkedList<String>());
- }
- LineNumberReader reader = new LineNumberReader(new FileReader(_logfile));
- try
- {
- while (reader.ready())
- {
- String line = reader.readLine();
- if (reader.getLineNumber() > _linesToSkip)
- {
- for (String p : pattern)
- {
- if (line.contains(p))
- {
- results.get(p).add(line);
- }
- }
- }
- }
- }
- finally
- {
- reader.close();
- }
-
- return results;
- }
- /**
- * Checks the log file for a given message to appear. If the caller
- * has previously called {@link #markDiscardPoint()}, lines up until the discard
- * point are not considered.
- *
- * @param message the message to wait for in the log
- * @param wait the time in ms to wait for the message to occur
- * @return true if the message was found
- *
- * @throws java.io.FileNotFoundException if the Log file can no longer be found
- * @throws IOException thrown when reading the log file
- */
- public boolean waitForMessage(String message, long wait)
- throws FileNotFoundException, IOException
- {
- // Loop through alerts until we're done or wait ms seconds have passed,
- // just in case the logfile takes a while to flush.
- LineNumberReader reader = null;
- try
- {
- reader = new LineNumberReader(new FileReader(_logfile));
-
- boolean found = false;
- long endtime = System.currentTimeMillis() + wait;
- while (!found && System.currentTimeMillis() < endtime)
- {
- boolean ready = true;
- while (ready = reader.ready())
- {
- String line = reader.readLine();
-
- if (reader.getLineNumber() > _linesToSkip)
- {
- if (line.contains(message))
- {
- found = true;
- break;
- }
- }
- }
- if (!ready)
- {
- try
- {
- Thread.sleep(50);
- }
- catch (InterruptedException ie)
- {
- Thread.currentThread().interrupt();
- }
- }
- }
- return found;
-
- }
- finally
- {
- if (reader != null)
- {
- reader.close();
- }
- }
- }
-
- /**
- * Read the log file in to memory as a String
- *
- * @return the current contents of the log file
- *
- * @throws java.io.FileNotFoundException if the Log file can no longer be found
- * @throws IOException thrown when reading the log file
- */
- public String readFile() throws FileNotFoundException, IOException
- {
- return FileUtils.readFileAsString(_logfile);
- }
-
- /**
- * Return a File reference to the monitored file
- *
- * @return the file being monitored
- */
- public File getMonitoredFile()
- {
- return _logfile;
- }
-
- /**
- * Marks the discard point in the log file.
- *
- * @throws java.io.FileNotFoundException if the Log file can no longer be found
- * @throws IOException thrown if there is a problem with the log file
- */
- public void markDiscardPoint() throws FileNotFoundException, IOException
- {
- _linesToSkip = countLinesInFile();
- }
-
- private int countLinesInFile() throws IOException
- {
- int lineCount = 0;
- BufferedReader br = null;
- try
- {
- br = new BufferedReader(new FileReader(_logfile));
- while(br.readLine() != null)
- {
- lineCount++;
- }
-
- return lineCount;
- }
- finally
- {
- if (br != null)
- {
- br.close();
- }
- }
- }
-
- /**
- * Stop monitoring this file.
- *
- * This is required to be called incase we added a new logger.
- *
- * If we don't call close then the new logger will continue to get log entries
- * after our desired test has finished.
- */
- public void close()
- {
- }
-
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/systests/src/test/java/org/apache/qpid/util/LogMonitorTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/util/LogMonitorTest.java b/systests/src/test/java/org/apache/qpid/util/LogMonitorTest.java
deleted file mode 100644
index 0b8b922..0000000
--- a/systests/src/test/java/org/apache/qpid/util/LogMonitorTest.java
+++ /dev/null
@@ -1,227 +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.util;
-
-import org.apache.qpid.test.utils.QpidTestCase;
-import org.apache.qpid.test.utils.TestFileUtils;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.List;
-
-public class LogMonitorTest extends QpidTestCase
-{
-
- private LogMonitor _monitor;
- private File _testFile;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- _testFile = TestFileUtils.createTempFile(this);
- _monitor = new LogMonitor(_testFile);
- _monitor.getMonitoredFile().deleteOnExit(); // Make sure we clean up
- }
-
- @Override
- protected void tearDown() throws Exception
- {
- super.tearDown();
- _testFile.delete();
- }
-
- public void testMonitorNormalFile() throws IOException
- {
- assertEquals(_testFile, _monitor.getMonitoredFile());
- }
-
- public void testMonitorNullFileThrows()
- {
- try
- {
- new LogMonitor(null);
- fail("It should not be possible to monitor null.");
- }
- catch (IllegalArgumentException e)
- {
- // pass
- }
- }
-
- public void testMonitorNonExistentFileThrows() throws IOException
- {
- assertTrue("Unable to delete file for our test", _testFile.delete());
- assertFalse("Unable to test as our test file exists.", _testFile.exists());
-
- try
- {
- new LogMonitor(_testFile);
- fail("It should not be possible to monitor non existing file.");
- }
- catch (IllegalArgumentException e)
- {
- // pass
- }
- }
-
- public void testFindMatches_Match() throws IOException
- {
- String message = getName() + ": Test Message";
- appendTestMessage(message);
- validateLogContainsMessage(_monitor, message);
- }
-
- public void testFindMatches_NoMatch() throws IOException
- {
- String message = getName() + ": Test Message";
- String notLogged = "This text was not logged";
- appendTestMessage(message);
- validateLogDoesNotContainMessage(_monitor, notLogged);
- }
-
- public void testWaitForMessage_Timeout() throws IOException
- {
- String message = getName() + ": Test Message";
-
- long TIME_OUT = 2000;
-
- logMessageWithDelay(message, TIME_OUT);
-
- // Verify that we can time out waiting for a message
- assertFalse("Message was logged ",
- _monitor.waitForMessage(message, 100));
-
- // Verify that the message did eventually get logged.
- assertTrue("Message was never logged.",
- _monitor.waitForMessage(message, TIME_OUT * 2));
- }
-
- public void testDiscardPoint() throws IOException
- {
- String firstMessage = getName() + ": Test Message1";
- appendTestMessage(firstMessage);
-
- validateLogContainsMessage(_monitor, firstMessage);
-
- _monitor.markDiscardPoint();
-
- validateLogDoesNotContainMessage(_monitor, firstMessage);
-
- String secondMessage = getName() + ": Test Message2";
- appendTestMessage(secondMessage);
- validateLogContainsMessage(_monitor, secondMessage);
- }
-
- public void testRead() throws IOException
- {
- String message = getName() + ": Test Message";
- appendTestMessage(message);
- String fileContents = _monitor.readFile();
-
- assertTrue("Logged message not found when reading file.",
- fileContents.contains(message));
- }
-
- /****************** Helpers ******************/
-
- /**
- * Validate that the LogMonitor does not match the given string in the log
- *
- * @param log The LogMonitor to check
- * @param message The message to check for
- *
- * @throws IOException if a problems occurs
- */
- protected void validateLogDoesNotContainMessage(LogMonitor log, String message)
- throws IOException
- {
- List<String> results = log.findMatches(message);
-
- assertNotNull("Null results returned.", results);
-
- assertEquals("Incorrect result set size", 0, results.size());
- }
-
- /**
- * Validate that the LogMonitor can match the given string in the log
- *
- * @param log The LogMonitor to check
- * @param message The message to check for
- *
- * @throws IOException if a problems occurs
- */
- protected void validateLogContainsMessage(LogMonitor log, String message)
- throws IOException
- {
- List<String> results = log.findMatches(message);
-
- assertNotNull("Null results returned.", results);
-
- assertEquals("Incorrect result set size", 1, results.size());
-
- assertTrue("Logged Message'" + message + "' not present in results:"
- + results.get(0), results.get(0).contains(message));
- }
-
- /**
- * Create a new thread to log the given message after the set delay
- *
- * @param message the messasge to log
- * @param delay the delay (ms) to wait before logging
- */
- private void logMessageWithDelay(final String message, final long delay)
- {
- new Thread(new Runnable()
- {
-
- @Override
- public void run()
- {
- try
- {
- Thread.sleep(delay);
- }
- catch (InterruptedException e)
- {
- //ignore
- }
-
- appendTestMessage(message);
- }
- }).start();
- }
-
-
- private void appendTestMessage(String msg)
- {
- try (OutputStream outputStream = new FileOutputStream(_testFile, true))
- {
- outputStream.write(String.format("%s%n", msg).getBytes());
- }
- catch (IOException e)
- {
- fail("Cannot write to test file '" + _testFile.getAbsolutePath() + "'");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/test-profiles/Java010Excludes
----------------------------------------------------------------------
diff --git a/test-profiles/Java010Excludes b/test-profiles/Java010Excludes
index e72790c..aff6fb5 100755
--- a/test-profiles/Java010Excludes
+++ b/test-profiles/Java010Excludes
@@ -17,10 +17,6 @@
// under the License.
//
-// 0-10 and 0-9 connections dont generate the exact same logging due to protocol differences
-org.apache.qpid.server.logging.ChannelLoggingTest#testChannelStartsFlowStopped
-org.apache.qpid.server.logging.ChannelLoggingTest#testChannelStartConsumerFlowStarted
-
// QPID-3432: These tests test the behaviour of 0-8..-0-9-1 specific system property (amqj.default_syncwrite_timeout)
org.apache.qpid.test.client.timeouts.SyncWaitTimeoutDelayTest#*
org.apache.qpid.test.client.timeouts.SyncWaitDelayTest#*
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/test-profiles/Java10Excludes
----------------------------------------------------------------------
diff --git a/test-profiles/Java10Excludes b/test-profiles/Java10Excludes
index 3265d94..72d3d31 100644
--- a/test-profiles/Java10Excludes
+++ b/test-profiles/Java10Excludes
@@ -17,23 +17,9 @@
// under the License.
//
-// The binding logging tests focus on the behaviour of the old client with regard to creating (and binding) queues on
-// the creation of consumers.
-org.apache.qpid.server.logging.BindingLoggingTest#*
-
-// These tests are 0-8/9/9-1 specific and are also excluded in the 0-10 profile
-org.apache.qpid.server.logging.ChannelLoggingTest#testChannelStartsFlowStopped
-org.apache.qpid.server.logging.ChannelLoggingTest#testChannelStartConsumerFlowStarted
-// This test is testing AMQP 0-x specific behaviour
-org.apache.qpid.server.logging.ChannelLoggingTest#testChannelClosedOnExclusiveQueueDeclaredOnDifferentSession
-
// Tests the interaction between the Broker's supported protocols and what the 0-x client agrees to
org.apache.qpid.server.SupportedProtocolVersionsTest#*
-// Durable topic subscriptions will be reimplemented with the shared topic subscriptions (QPID-7569)
-org.apache.qpid.server.logging.ConsumerLoggingTest#testSubscriptionCreateDurable
-org.apache.qpid.server.logging.ConsumerLoggingTest#testSubscriptionCreateDurableWithArguments
-
// These tests assume names of queues backing durable subscriptions
org.apache.qpid.server.store.berkeleydb.BDBUpgradeTest#testConsumptionOfUpgradedMessages
org.apache.qpid.server.store.berkeleydb.BDBUpgradeTest#testDurableSubscriptionWithoutSelector
@@ -42,9 +28,4 @@ org.apache.qpid.server.store.berkeleydb.BDBUpgradeTest#testSelectorDurability
// this test makes assumptions about the way the client uses sessions.
org.apache.qpid.systest.rest.SessionRestTest#*
-// Tests verify the 0-x client's ability to create queues and that the server logs creation/deletion faithfully
-org.apache.qpid.server.logging.DurableQueueLoggingTest#*
-org.apache.qpid.server.logging.QueueLoggingTest#*
-org.apache.qpid.server.logging.TransientQueueLoggingTest#*
-
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/test-profiles/JavaPersistentExcludes
----------------------------------------------------------------------
diff --git a/test-profiles/JavaPersistentExcludes b/test-profiles/JavaPersistentExcludes
index 240f6dc..969b927 100644
--- a/test-profiles/JavaPersistentExcludes
+++ b/test-profiles/JavaPersistentExcludes
@@ -17,5 +17,3 @@
// under the License.
//
-//These tests require the MemoryMessageStore
-org.apache.qpid.server.logging.MemoryMessageStoreLoggingTest#*
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/test-profiles/JavaPre010Excludes
----------------------------------------------------------------------
diff --git a/test-profiles/JavaPre010Excludes b/test-profiles/JavaPre010Excludes
index 7d3925e..61616c6 100644
--- a/test-profiles/JavaPre010Excludes
+++ b/test-profiles/JavaPre010Excludes
@@ -23,7 +23,6 @@
// Those tests are written against the 0.10 path
org.apache.qpid.client.SynchReceiveTest#testReceiveNoWait
-org.apache.qpid.server.logging.ChannelLoggingTest#testChannelClosedOnExclusiveQueueDeclaredOnDifferentSession
# Exclude the JMS 2.0 test suite
org.apache.qpid.systests.jms_2_0.*
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org
[2/8] qpid-broker-j git commit: NO-JIRA: [Broker-J] [System Tests]
Remove logging tests
Posted by kw...@apache.org.
NO-JIRA: [Broker-J] [System Tests] Remove logging tests
Project: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/commit/b21a8f56
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/b21a8f56
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/b21a8f56
Branch: refs/heads/master
Commit: b21a8f564e9d914a41564fa0041f7355340cacaf
Parents: 6b31d0f
Author: Keith Wall <kw...@apache.org>
Authored: Mon Mar 12 14:17:13 2018 +0000
Committer: Keith Wall <kw...@apache.org>
Committed: Mon Mar 12 16:24:17 2018 +0000
----------------------------------------------------------------------
.../apache/qpid/server/BrokerStartupTest.java | 84 --
.../server/logging/AbstractTestLogging.java | 412 ---------
.../logging/AccessControlLoggingTest.java | 194 -----
.../qpid/server/logging/AlertingTest.java | 180 ----
.../qpid/server/logging/BrokerLoggingTest.java | 861 -------------------
.../qpid/server/logging/ChannelLoggingTest.java | 384 ---------
.../server/logging/ConnectionLoggingTest.java | 209 -----
.../server/logging/ConsumerLoggingTest.java | 352 --------
.../server/logging/DurableQueueLoggingTest.java | 312 -------
.../server/logging/ExchangeLoggingTest.java | 247 ------
.../qpid/server/logging/QueueLoggingTest.java | 179 ----
.../logging/TransientQueueLoggingTest.java | 31 -
.../server/logging/VirtualHostLoggingTest.java | 129 ---
.../java/org/apache/qpid/util/LogMonitor.java | 310 -------
.../org/apache/qpid/util/LogMonitorTest.java | 227 -----
test-profiles/Java010Excludes | 4 -
test-profiles/Java10Excludes | 19 -
test-profiles/JavaPersistentExcludes | 2 -
test-profiles/JavaPre010Excludes | 1 -
19 files changed, 4137 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/systests/src/test/java/org/apache/qpid/server/BrokerStartupTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/server/BrokerStartupTest.java b/systests/src/test/java/org/apache/qpid/server/BrokerStartupTest.java
deleted file mode 100644
index 8b7443e..0000000
--- a/systests/src/test/java/org/apache/qpid/server/BrokerStartupTest.java
+++ /dev/null
@@ -1,84 +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.server;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-
-import org.apache.qpid.server.logging.AbstractTestLogging;
-import org.apache.qpid.server.model.Port;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-
-/**
- * Series of tests to validate the external Apache Qpid Broker-J starts up as expected.
- */
-public class BrokerStartupTest extends AbstractTestLogging
-{
- @Override
- public void startDefaultBroker()
- {
- // noop; we do not want to start broker
- }
-
- /**
- * This test simply tests that the broker will startup even if there is no config file (i.e. that it can use the
- * currently packaged initial config file (all system tests by default generate their own config file).
- *
- * @throws Exception
- */
- public void testStartupWithNoConfig() throws Exception
- {
- if (isJavaBroker())
- {
- super.startDefaultBroker();
- Connection conn = getConnection();
- assertNotNull(conn);
- }
- }
-
- public void testStartupWithErroredChildrenCanBeConfigured() throws Exception
- {
- if (isJavaBroker())
- {
- // Purposely set the HTTP port to -1 so that the port object becomes ERRORED
- final int invalidHttpPort = -1;
- setTestSystemProperty("test.hport", String.valueOf(invalidHttpPort));
- getDefaultBrokerConfiguration().addHttpManagementConfiguration();
- getDefaultBrokerConfiguration().setObjectAttribute(Port.class, TestBrokerConfiguration.ENTRY_NAME_HTTP_PORT, Port.PORT, invalidHttpPort);
-
- // Set broker to fail on startup if it has ERRORED children
- setTestSystemProperty("broker.failStartupWithErroredChild", String.valueOf(Boolean.TRUE));
-
- super.startDefaultBroker();
-
- try
- {
- Connection conn = getConnection();
- fail("Connection should fail as broker startup should have failed due to ERRORED children (port)");
- }
- catch (JMSException jmse)
- {
- //pass
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/systests/src/test/java/org/apache/qpid/server/logging/AbstractTestLogging.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/server/logging/AbstractTestLogging.java b/systests/src/test/java/org/apache/qpid/server/logging/AbstractTestLogging.java
deleted file mode 100644
index 96b009e..0000000
--- a/systests/src/test/java/org/apache/qpid/server/logging/AbstractTestLogging.java
+++ /dev/null
@@ -1,412 +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.server.logging;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.text.NumberFormat;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-
-import org.apache.qpid.server.logging.subjects.AbstractTestLogSubject;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.util.LogMonitor;
-
-/**
- * Abstract superclass for logging test set up and utility methods.
- *
- * So named to prevent it being selected itself as a test to run by the test suite.
- */
-public class AbstractTestLogging extends QpidBrokerTestCase
-{
- public static final long DEFAULT_LOG_WAIT = 2000;
- public static final String TEST_LOG_PREFIX = "MESSAGE";
- protected LogMonitor _monitor;
-
- @Override
- public void setUp() throws Exception
- {
- setLogMessagePrefix();
-
- super.setUp();
- _monitor = new LogMonitor(getOutputFile());
- }
-
- protected void setLogMessagePrefix()
- {
- //set the message prefix to facilitate scraping from the munged test output.
- setSystemProperty("qpid.logging.prefix", TEST_LOG_PREFIX);
- }
-
- @Override
- public void tearDown() throws Exception
- {
- _monitor.close();
- super.tearDown();
- }
-
- /**
- * assert that the requested log message has not occured
- *
- * @param log
- *
- * @throws IOException
- */
- public void assertLoggingNotYetOccured(String log) throws IOException
- {
- // Ensure the alert has not occured yet
- assertEquals("Message has already occured:" + log, 0,
- findMatches(log).size());
- }
-
- protected void validateMessageID(String id, String log)
- {
- assertEquals("Incorrect message", id, getMessageID(log));
- }
-
- protected String getMessageID(String log)
- {
- String message = fromMessage(log);
-
- return message.substring(0, message.indexOf(" "));
- }
-
- /**
- * Return the first channel id from the log string
- * ' ch;X' if there is no channel id return -1.
- *
- * @param log the log string to search.
- *
- * @return channel id or -1 if no channel id exists.
- */
- protected int getChannelID(String log)
- {
- int start = log.indexOf("ch:") + 3;
-
- // If we do a check for ] as the boundary we will get cases where log
- // is presented with the bounding. If we don't match a ] then we can use
- // the end of the string as the boundary.
- int end = log.indexOf("]", start);
- if (end == -1)
- {
- end = log.length();
- }
- return parseInt(log, start, end);
- }
-
- protected String fromMessage(String log)
- {;
- int startSubject = log.indexOf("]") + 1;
- int start = log.indexOf("]", startSubject) + 1;
-
- // If we don't have a subject then the second indexOf will return 0
- // in which case we can use the end of the actor as the index.
- if (start == 0)
- {
- start = startSubject;
- }
-
- return log.substring(start).trim();
- }
-
- /**
- * Extract the Subject from the Log Message.
- *
- * The subject is the second block inclosed in brackets '[ ]'.
- *
- * If there is no Subject or the second block of brackets '[ ]' cannot be
- * identified then an empty String ("") is returned.
- *
- * The brackets '[ ]' are not included in the returned String.
- *
- * @param log The log message to process
- *
- * @return the Subject string or the empty string ("") if the subject can't be identified.
- */
- protected String fromSubject(String log)
- {
- int start = log.indexOf("[") + 1;
- // Take the second index
- start = log.indexOf("[", start) + 1;
-
- // There may not be a subject so in that case return nothing.
- if (start == 0)
- {
- return "";
- }
-
- int end = log.indexOf("]", start);
- try
- {
- return log.substring(start, end);
- }
- catch (IndexOutOfBoundsException iobe)
- {
- return "";
- }
- }
-
- /**
- * Extract the actor segment from the log message.
- * The Actor segment is the first section enclosed in '[ ]'.
- *
- * No analysis is performed to ensure that the first '[ ]' section of the
- * given log is really an Actor segment.
- *
- * The brackets '[ ]' are not included in the returned String.
- *
- * @param log the Log Message
- *
- * @return the Actor segment or "" if unable to locate '[ ]' section
- */
- protected String fromActor(String log)
- {
- int start = log.indexOf("[") + 1;
- int end = log.indexOf("]", start);
- try
- {
- return log.substring(start, end).trim();
- }
- catch (IndexOutOfBoundsException iobe)
- {
- return "";
- }
- }
-
- /**
- * Return the message String from the given message section
- *
- * @param log the Message Section
- *
- * @return the Message String.
- */
- protected String getMessageString(String log)
- {
- // Remove the Log ID from the returned String
- int start = log.indexOf(":") + 1;
-
- return log.substring(start).trim();
- }
-
- /**
- * Given our log message extract the connection ID:
- *
- * The log string will contain the connectionID identified by 'con:'
- *
- * So extract the value shown here by X:
- *
- * 'con:X('
- *
- * Extract the value between the ':' and '(' and process it as an Integer
- *
- * If we are unable to find the right index or process the substring as an
- * Integer then return -1.
- *
- * @param log the log String to process
- *
- * @return the connection ID or -1.
- */
- protected int getConnectionID(String log)
- {
- int conIDStart = log.indexOf("con:") + 4;
- int conIDEnd = log.indexOf("(", conIDStart);
- return parseInt(log, conIDStart, conIDEnd);
- }
-
- /**
- * Extract the log entry from the raw log.
- *
- * This formatting may impead our testing process so extract the log message
- * as we know it to be formatted.
- *
- * This starts with the string MESSAGE
- *
- * @param rawLog the raw log
- *
- * @return the log we are expecting to be printed without the log formating prefixes
- */
- protected String getLog(String rawLog)
- {
- int start = rawLog.indexOf(TEST_LOG_PREFIX);
- return rawLog.substring(start);
- }
-
- /**
- * Extract the log entry from the result set. Positions are 0-based.
- *
- * @param results list of log message results to extract from
- * @param position position in the list of the message to extract
- * @return the message string
- */
- protected String getLogMessage(List<String> results, int position)
- {
- return getLog(results.get(position));
- }
-
- /**
- * Extract the nth-from-last log entry from the result set.
- *
- * @param results list of log message results to extract from
- * @param positionFromEnd position from end of the message list to extract (eg 0 for last)
- * @return the message string
- */
- protected String getLogMessageFromEnd(List<String> results, int positionFromEnd)
- {
- int resultSize = results.size();
- return getLogMessage(results, resultSize - 1 - positionFromEnd);
- }
-
- protected List<String> findMatches(String toFind) throws IOException
- {
- return _monitor.findMatches(toFind);
- }
-
- protected List<String> waitAndFindMatches(String toFind) throws IOException
- {
- return waitAndFindMatches(toFind, DEFAULT_LOG_WAIT);
- }
-
- protected List<String> waitAndFindMatches(String toFind, long wait) throws IOException
- {
- return _monitor.waitAndFindMatches(toFind, wait);
- }
-
- public boolean waitForMessage(String message) throws FileNotFoundException, IOException
- {
- return waitForMessage(message, DEFAULT_LOG_WAIT);
- }
-
- public boolean waitForMessage(String message, long wait) throws FileNotFoundException, IOException
- {
- return _monitor.waitForMessage(message, wait);
- }
-
- /**
- * Given a list of messages that have been pulled out of a log file
- * Process the results splitting the log statements in to lists based on the
- * actor's connection ID.
- *
- * So for each log entry extract the Connecition ID from the Actor of the log
- *
- * Then use that as a key to a HashMap storing the list of log messages for
- * that connection.
- *
- * @param logMessages The list of mixed connection log messages
- *
- * @return Map indexed by connection id to a list of log messages just for that connection.
- */
- protected HashMap<Integer, List<String>> splitResultsOnConnectionID(List<String> logMessages)
- {
- HashMap<Integer, List<String>> connectionSplitList = new HashMap<Integer, List<String>>();
-
- for (String log : logMessages)
- {
- // Get the connectionID from the Actor in the Message Log.
- int cID = getConnectionID(fromActor(getLog(log)));
-
- List<String> connectionData = connectionSplitList.get(cID);
-
- // Create the initial List if we don't have one already
- if (connectionData == null)
- {
- connectionData = new LinkedList<String>();
- connectionSplitList.put(cID, connectionData);
- }
-
- // Store the log
- connectionData.add(log);
- }
-
- return connectionSplitList;
- }
-
- /**
- * Filter the give result set by the specficifed virtualhost.
- * This is done using the getSlice to identify the virtualhost (vh) in the
- * log message
- *
- * @param results full list of logs
- * @param virtualHostName the virtualhostName to filter on
- *
- * @return the list of messages only for that virtualhost
- */
- protected List<String> filterResultsByVirtualHost(List<String> results, String virtualHostName)
- {
- List<String> filteredResults = new LinkedList<String>();
- Iterator<String> iterator = results.iterator();
-
- while (iterator.hasNext())
- {
- String log = iterator.next();
-
- if (AbstractTestLogSubject.getSlice("vh", log).equals(virtualHostName))
- {
- filteredResults.add(log);
- }
- }
-
- return filteredResults;
- }
-
- /**
- * Dump the log results.
- */
- protected void dumpLogs(List<String> results) throws IOException
- {
- dumpLogs(results, null);
- }
-
- /**
- * Dump the log results or if there are none, the contents of the
- * monitored log file if the monitor is non-null.
- */
- protected void dumpLogs(List<String> results, LogMonitor monitor) throws IOException
- {
- System.err.println("Log Dump:");
- for (String log : results)
- {
- System.err.println(log);
- }
-
- if (results.isEmpty() && monitor != null)
- {
- System.err.println("Monitored file contents:");
- System.err.println(monitor.readFile());
- }
- }
-
- private int parseInt(final String logSubstring, final int start, final int end)
- {
- try
- {
- final NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
- final Number number = format.parse(logSubstring.substring(start, end));
- return number.intValue();
- }
- catch (Exception e)
- {
- return -1;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/systests/src/test/java/org/apache/qpid/server/logging/AccessControlLoggingTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/server/logging/AccessControlLoggingTest.java b/systests/src/test/java/org/apache/qpid/server/logging/AccessControlLoggingTest.java
deleted file mode 100644
index fa366b4..0000000
--- a/systests/src/test/java/org/apache/qpid/server/logging/AccessControlLoggingTest.java
+++ /dev/null
@@ -1,194 +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.server.logging;
-
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Session;
-
-import org.apache.qpid.server.model.ConfiguredObject;
-import org.apache.qpid.server.model.ExclusivityPolicy;
-import org.apache.qpid.server.model.LifetimePolicy;
-import org.apache.qpid.server.model.Queue;
-import org.apache.qpid.test.utils.TestUtils;
-
-/**
- * ACL version 2/3 file testing to verify that ACL actor logging works correctly.
- *
- * This suite of tests validate that the AccessControl messages occur correctly
- * and according to the following format:
- *
- * <pre>
- * ACL-1001 : Allowed Operation Object {PROPERTIES}
- * ACL-1002 : Denied Operation Object {PROPERTIES}
- * </pre>
- */
-public class AccessControlLoggingTest extends AbstractTestLogging
-{
- private static final String ACL_LOG_PREFIX = "ACL-";
- private static final String USER = "client";
- private static final String PASS = "guest";
- private Connection _connection;
- private Session _session;
-
- @Override
- public void setUp() throws Exception
- {
- // Write out ACL for this test
- TestUtils.writeACLFileUtil(this, "ACL ALLOW client ACCESS VIRTUALHOST",
- "ACL ALLOW client CREATE QUEUE name='allow'",
- "ACL ALLOW-LOG client CREATE QUEUE name='allow-log'",
- "ACL DENY client CREATE QUEUE name='deny'",
- "ACL DENY-LOG client CREATE QUEUE name='deny-log'",
- "ACL ALLOW client PUBLISH EXCHANGE name='' routingkey='$management");
-
- super.setUp();
-
- _connection = getConnection(USER, PASS);
- _session = _connection.createSession(true, Session.SESSION_TRANSACTED);
- _connection.start();
-
- }
-
- @Override
- public void tearDown() throws Exception
- {
- try
- {
- _connection.close();
- super.tearDown();
- }
- catch (JMSException e)
- {
- //we're throwing this away as it can happen in this test as the state manager remembers exceptions
- //that we provoked with authentication failures, where the test passes - we can ignore on con close
- }
- }
-
- /**
- * Test that {@code allow} ACL entries do not log anything.
- */
- public void testAllow() throws Exception
- {
- String name = "allow";
- boolean autoDelete = false;
- boolean durable = false;
- boolean exclusive = false;
- createQueue(name, autoDelete, durable, exclusive);
-
- List<String> matches = findMatches(ACL_LOG_PREFIX + 1001);
-
- assertTrue("Should be no ACL log messages", matches.isEmpty());
- }
-
- protected void createQueue(final String name,
- final boolean autoDelete,
- final boolean durable, final boolean exclusive)
- throws JMSException
- {
- Map<String,Object> attributes = new LinkedHashMap<>();
- attributes.put(ConfiguredObject.NAME, name);
- attributes.put(ConfiguredObject.DURABLE, durable);
- LifetimePolicy lifetimePolicy;
- ExclusivityPolicy exclusivityPolicy;
-
- if (exclusive)
- {
- lifetimePolicy = autoDelete
- ? LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS
- : durable ? LifetimePolicy.PERMANENT : LifetimePolicy.DELETE_ON_CONNECTION_CLOSE;
- exclusivityPolicy = durable ? ExclusivityPolicy.CONTAINER : ExclusivityPolicy.CONNECTION;
- }
- else
- {
- lifetimePolicy = autoDelete ? LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS : LifetimePolicy.PERMANENT;
- exclusivityPolicy = ExclusivityPolicy.NONE;
- }
-
- attributes.put(Queue.EXCLUSIVE, exclusivityPolicy.toString());
- attributes.put(Queue.LIFETIME_POLICY, lifetimePolicy.toString());
- createEntityUsingAmqpManagement(name, _session, "org.apache.qpid.Queue", attributes);
- }
-
- /**
- * Test that {@code allow-log} ACL entries log correctly.
- */
- public void testAllowLog() throws Exception
- {
- createQueue("allow-log", false, false, false);
-
- List<String> matches = findMatches(ACL_LOG_PREFIX + 1001);
-
- assertEquals("Should only be one ACL log message", 1, matches.size());
-
- String log = getLogMessage(matches, 0);
- String actor = fromActor(log);
- String subject = fromSubject(log);
- String message = getMessageString(fromMessage(log));
-
- validateMessageID(ACL_LOG_PREFIX + 1001, log);
-
- assertTrue("Actor " + actor + " should contain the user identity: " + USER, actor.contains(USER));
- assertTrue("Subject should be empty", subject.length() == 0);
- assertTrue("Message should start with 'Allowed'", message.startsWith("Allowed"));
- assertTrue("Message should contain 'Create Queue'", message.contains("Create Queue"));
- assertTrue("Message should have contained the queue name", message.contains("allow-log"));
- }
-
- /**
- * Test that {@code deny-log} ACL entries log correctly.
- */
- public void testDenyLog() throws Exception
- {
- createQueue("deny-log", false, false, false);
-
- List<String> matches = findMatches(ACL_LOG_PREFIX + 1002);
-
- assertEquals("Should only be one ACL log message", 1, matches.size());
-
- String log = getLogMessage(matches, 0);
- String actor = fromActor(log);
- String subject = fromSubject(log);
- String message = getMessageString(fromMessage(log));
-
- validateMessageID(ACL_LOG_PREFIX + 1002, log);
-
- assertTrue("Actor " + actor + " should contain the user identity: " + USER, actor.contains(USER));
- assertTrue("Subject should be empty", subject.length() == 0);
- assertTrue("Message should start with 'Denied'", message.startsWith("Denied"));
- assertTrue("Message should contain 'Create Queue'", message.contains("Create Queue"));
- assertTrue("Message should have contained the queue name", message.contains("deny-log"));
- }
-
- /**
- * Test that {@code deny} ACL entries do not log anything.
- */
- public void testDeny() throws Exception
- {
- createQueue("deny", false, false, false);
-
- List<String> matches = findMatches(ACL_LOG_PREFIX + 1002);
-
- assertTrue("Should be no ACL log messages", matches.isEmpty());
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/systests/src/test/java/org/apache/qpid/server/logging/AlertingTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/server/logging/AlertingTest.java b/systests/src/test/java/org/apache/qpid/server/logging/AlertingTest.java
deleted file mode 100644
index 3830f96..0000000
--- a/systests/src/test/java/org/apache/qpid/server/logging/AlertingTest.java
+++ /dev/null
@@ -1,180 +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.server.logging;
-
-import java.util.Collections;
-
-import javax.jms.Connection;
-import javax.jms.Queue;
-import javax.jms.Session;
-
-import org.apache.qpid.systest.rest.RestTestHelper;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-
-public class AlertingTest extends AbstractTestLogging
-{
-
- private Session _session;
- private Connection _connection;
- private Queue _destination;
- private int _numMessages;
-
- private static final int ALERT_LOG_WAIT_PERIOD = 5000;
- private static final String MESSAGE_COUNT_ALERT = "MESSAGE_COUNT_ALERT";
-
- @Override
- public void setUp() throws Exception
- {
- _numMessages = 50;
- setTestSystemProperty("virtualhost.housekeepingCheckPeriod", String.valueOf(ALERT_LOG_WAIT_PERIOD));
- setTestSystemProperty("queue.alertThresholdQueueDepthMessages", String.valueOf(_numMessages));
-
- // Then we do the normal setup stuff like starting the broker, getting a connection etc.
- super.setUp();
-
- setupConnection();
- }
-
- /**
- * Create a new connection and ensure that our destination queue is created
- * and bound.
- *
- * Note that the tests here that restart the broker rely on persistence.
- * However, the queue creation here is transient. So the queue will not be
- * rebound on restart. Hence the consumer creation here rather than just the
- * once.
- *
- * The persistent messages will recreate the queue but not bind it (as it
- * was not a durable queue) However, the consumer creation here will ensure
- * that the queue is correctly bound and can receive new messages.
- *
- * @throws Exception
- */
- private void setupConnection()
- throws Exception
- {
- _connection = getConnection();
- _connection.start();
- _session = _connection.createSession(true, Session.SESSION_TRANSACTED);
- _destination = createTestQueue(_session);
-
- }
-
- /**
- * Checks the log file for MESSAGE_COUNT_ALERT, fails() the test if it's not found and
- * places the entire contents in the message to help debug cruise control failures.
- *
- * @throws Exception
- */
- private void wasAlertFired() throws Exception
- {
- if (!waitForMessage(MESSAGE_COUNT_ALERT, ALERT_LOG_WAIT_PERIOD))
- {
- StringBuffer message = new StringBuffer("Could not find 'MESSAGE_COUNT_ALERT' in log file: " + _monitor.getMonitoredFile().getAbsolutePath());
- fail(message.toString());
- }
- }
-
- public void testAlertingReallyWorks() throws Exception
- {
- // Send 5 messages, make sure that the alert was fired properly.
- sendMessage(_session, _destination, _numMessages + 1);
- _session.commit();
- wasAlertFired();
- }
-
- public void testAlertingReallyWorksWithRestart() throws Exception
- {
- sendMessage(_session, _destination, _numMessages + 1);
- _session.commit();
- _connection.close();
- stopDefaultBroker();
-
- startDefaultBroker();
- wasAlertFired();
- }
-
- /**
- * Test that if the alert value is change from the previous value we can
- * still get alerts.
- *
- * Test sends two messages to the broker then restarts the broker with new
- * configuration.
- *
- * Validates that we only have two messages on the queue and then sends
- * enough messages to trigger the alert.
- *
- * The alert is then validate.
- *
- *
- * @throws Exception
- */
- public void testAlertingReallyWorksWithChanges() throws Exception
- {
- // send some messages and nuke the logs
- sendMessage(_session, _destination, 2);
- _session.commit();
- // To prevent any failover/retry/connection dropped errors
- _connection.close();
-
- stopDefaultBroker();
-
- TestBrokerConfiguration config = getDefaultBrokerConfiguration();
- config.addHttpManagementConfiguration();
- config.setSaved(false);
-
- startDefaultBroker();
-
- setupConnection();
-
- // Validate the queue depth is as expected
- long messageCount = getQueueDepth(_connection, _destination);
- assertEquals("Broker has invalid message count for test", 2, messageCount);
-
- // Ensure the alert has not occurred yet
- assertLoggingNotYetOccured(MESSAGE_COUNT_ALERT);
-
- // Change max message count to 5, start broker and make sure that that's triggered at the right time
- TestBrokerConfiguration brokerConfiguration = getDefaultBrokerConfiguration();
- setTestSystemProperty("queue.alertThresholdQueueDepthMessages","5");
- brokerConfiguration.setSaved(false);
-
- RestTestHelper restTestHelper = new RestTestHelper(getDefaultBroker().getHttpPort());
- try
- {
- restTestHelper.submitRequest("queue/test/test/" + getTestQueueName(),
- "PUT",
- Collections.<String, Object>singletonMap(org.apache.qpid.server.model.Queue.ALERT_THRESHOLD_QUEUE_DEPTH_MESSAGES,
- 5));
- }
- finally
- {
- restTestHelper.tearDown();
- }
-
- // Trigger the new value
- sendMessage(_session, _destination, 3);
- _session.commit();
-
- // Validate that the alert occurred.
- wasAlertFired();
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/systests/src/test/java/org/apache/qpid/server/logging/BrokerLoggingTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/server/logging/BrokerLoggingTest.java b/systests/src/test/java/org/apache/qpid/server/logging/BrokerLoggingTest.java
deleted file mode 100644
index 9e1fc07..0000000
--- a/systests/src/test/java/org/apache/qpid/server/logging/BrokerLoggingTest.java
+++ /dev/null
@@ -1,861 +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.server.logging;
-
-import java.io.IOException;
-import java.net.Socket;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import junit.framework.AssertionFailedError;
-
-import org.apache.qpid.server.model.Port;
-import org.apache.qpid.server.model.Transport;
-import org.apache.qpid.test.utils.BrokerHolder;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-import org.apache.qpid.transport.ConnectionException;
-import org.apache.qpid.util.LogMonitor;
-
-/**
- * Broker Test Suite
- *
- * The Broker test suite validates that the follow log messages as specified in the Functional Specification.
- *
- * BRK-1001 : Startup : Version: <Version> Build: <Build>
- * BRK-1002 : Starting : Listening on <Transport> port <Port>
- * BRK-1003 : Shutting down : <Transport> port <Port>
- * BRK-1004 : Ready
- * BRK-1005 : Stopped
- * BRK-1006 : Using configuration : <path>
- * BRK-1007 : Using logging configuration : <path>
- *
- * These messages should only occur during startup. The tests need to verify the order of messages. In the case of the BRK-1002 and BRK-1003 the respective ports should only be available between the two log messages.
- */
-public class BrokerLoggingTest extends AbstractTestLogging
-{
- private static final String BROKER_MESSAGE_LOG_REG_EXP = ".*\\[\\w*\\] (BRK\\-\\d*) .*";
- 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 startDefaultBroker()
- {
- // noop. we do not want to start broker
- }
-
- /**
- * Description:
- * On startup the broker must report the active configuration file. The
- * logging system must output this so that we can know what configuration
- * is being used for this broker instance.
- *
- * Input:
- * The value of -c specified on the command line.
- * Output:
- * <date> MESSAGE BRK-1006 : Using configuration : <config file>
- * Constraints:
- * This MUST BE the first BRK log message.
- *
- * Validation Steps:
- * 1. This is first BRK log message.
- * 2. The BRK ID is correct
- * 3. The config file is the full path to the file specified on
- * the commandline.
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerStartupConfiguration() throws Exception
- {
- String TESTID="BRK-1006";
-
- if (isJavaBroker())
- {
- super.startDefaultBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(getOutputFile());
-
-
- String configFilePath = getDefaultBroker().getConfigurationPath();
-
- // Ensure we wait for TESTID to be logged
- waitAndFindMatches(TESTID);
-
- List<String> results = waitAndFindMatches(BRK_LOG_PREFIX);
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- String log = getLogMessage(results, 0);
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- results = findMatches(TESTID);
- assertEquals("More than one configuration message found.",
- 1, results.size());
-
- //3
- assertTrue("Config file details not correctly logged, got "
- + log + " but expected it to end with " + configFilePath,
- log.endsWith(configFilePath));
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
-
- /**
- * Description: On startup the broker reports the broker version number and svn build revision. This information is retrieved from the resource 'qpidversion.properties' which is located via the classloader.
- * Input: The 'qpidversion.properties' file located on the classpath.
- * Output:
- *
- * <date> MESSAGE BRK-1001 : Startup : qpid Version: 0.6 Build: 767150
- *
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. This occurs before any BRK-1002 listening messages are reported.
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerStartupStartup() throws Exception
- {
- // This logging startup code only occurs when you run a Apache Qpid Broker-J,
- // that broker must be started via Main so not an InVM broker.
- if (isJavaBroker())
- {
- String TESTID = "BRK-1001";
-
- super.startDefaultBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(getOutputFile());
-
- // Ensure we wait for TESTID to be logged
- waitAndFindMatches(TESTID);
-
- // Retrieve all BRK- log messages so we can check for an erroneous
- // BRK-1002 message.
- List<String> results = findMatches(BRK_LOG_PREFIX);
-
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- boolean validation = false;
- for (String rawLog : results)
- {
- if (validation)
- {
- //Stop checking once we have got to our startup test
- break;
- }
- String log = getLog(rawLog);
-
- // Ensure we do not have a BRK-1002 message
- if (!getMessageID(log).equals(TESTID))
- {
- assertFalse(getMessageID(log).equals("BRK-1002"));
- continue;
- }
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- //There will be 2 copies of the startup message (one via SystemOut, and one via Log4J)
- assertEquals("Unexpected startup message count",
- 1, findMatches(TESTID).size());
-
- validation = true;
- }
-
- assertTrue("Validation not performed: " + TESTID + " not logged", validation);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Description:
- * On startup the broker may listen on a number of ports and protocols. Each of these must be reported as they are made available.
- * Input:
- * The default configuration with no SSL
- * Output:
- *
- * <date> MESSAGE BRK-1002 : Starting : Listening on TCP port 5672
- *
- * Constraints:
- * Additional broker configuration will occur between the Startup(BRK-1001) and Starting(BRK-1002) messages depending on what VirtualHosts are configured.
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. This occurs after the BRK-1001 startup message
- * 3. Using the default configuration a single BRK-1002 will be printed showing values TCP / 5672
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerStartupListeningTCPDefault() throws Exception
- {
- if (isJavaBroker())
- {
- String TESTID = "BRK-1002";
-
- super.startDefaultBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(getOutputFile());
-
- // Ensure broker has fully started up.
- getConnection();
-
- // Ensure we wait for TESTID to be logged
- waitAndFindMatches(TESTID);
-
- // Retrieve all BRK- log messages so we can check for an erroneous
- // BRK-1002 message.
- List<String> results = findMatches(BRK_LOG_PREFIX);
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- boolean validation = false;
- boolean foundBRK1001 = false;
- for (String rawLog : results)
- {
- String log = getLog(rawLog);
-
- // using custom method to get id as getMessageId() fails to correctly identify id
- // because of using brackets for protocols
- String id = getBrokerLogId(log);
- // Ensure we do not have a BRK-1002 message
- if (!id.equals(TESTID))
- {
- if (id.equals("BRK-1001"))
- {
- foundBRK1001 = true;
- }
- continue;
- }
-
- assertTrue("BRK-1001 not logged before this message", foundBRK1001);
-
- //1
- assertEquals("Incorrect message", TESTID, id);
-
- //2
- assertEquals("Unexpected listen message count",
- 1, findMatches(TESTID).size());
-
- //3
- String message = getMessageString(log);
- assertTrue("Expected Listen log not correct" + message,
- message.endsWith("Listening on TCP port " + getDefaultBroker().getAmqpPort()));
-
- validation = true;
- }
-
- assertTrue("Validation not performed: " + TESTID + " not logged", validation);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- private String getBrokerLogId(String log)
- {
- Matcher m = BROKER_MESSAGE_LOG_PATTERN.matcher(log);
- if (m.matches())
- {
- return m.group(1);
- }
- return getMessageID(log);
- }
-
- /**
- * Description:
- * On startup the broker may listen on a number of ports and protocols. Each of these must be reported as they are made available.
- * Input:
- * The default configuration with SSL enabled
- * Output:
- *
- * <date> MESSAGE BRK-1002 : Starting : Listening on TCP port 5672
- * <date> MESSAGE BRK-1002 : Starting : Listening on TCP/SSL port 8672
- *
- * Constraints:
- * Additional broker configuration will occur between the Startup(BRK-1001) and Starting(BRK-1002) messages depending on what VirtualHosts are configured.
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. This occurs after the BRK-1001 startup message
- * 3. With SSL enabled in the configuration two BRK-1002 will be printed (order is not specified)
- * 1. One showing values [TCP] 5672
- * 2. One showing values [SSL] 5671
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerStartupListeningTCPSSL() throws Exception
- {
- if (isJavaBroker())
- {
- String TESTID = "BRK-1002";
-
- // Enable SSL on the connection
- Map<String, Object> sslPortAttributes = new HashMap<String, Object>();
- 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);
- getDefaultBrokerConfiguration().addObjectConfiguration(Port.class, sslPortAttributes);
-
- super.startDefaultBroker();
-
- final BrokerHolder defaultBroker = getDefaultBroker();
- int amqpTlsPort = defaultBroker.getAmqpTlsPort();
- int amqpPort = defaultBroker.getAmqpPort();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(getOutputFile());
-
- // Ensure broker has fully started up.
- getConnection();
-
- // Ensure we wait for TESTID to be logged
- waitAndFindMatches(TESTID);
-
- // Retrieve all BRK- log messages so we can check for an erroneous
- // BRK-1002 message.
- List<String> results = findMatches(BRK_LOG_PREFIX);
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- boolean validation = false;
- boolean foundBRK1001 = false;
- for (String rawLog : results)
- {
- String log = getLog(rawLog);
-
- String id = getBrokerLogId(log);
- // Ensure we do not have a BRK-1002 message
- if (!id.equals(TESTID))
- {
- if (id.equals("BRK-1001"))
- {
- foundBRK1001 = true;
- }
- continue;
- }
-
- assertTrue("BRK-1001 not logged before this message", foundBRK1001);
-
- //1
- assertEquals("Incorrect message", TESTID, id);
-
- //2
- //There will be 4 copies of the startup message (two via SystemOut, and two via Log4J)
- List<String> listenMessages = findMatches(TESTID);
- assertEquals("Four listen messages should be found.",
- 2, listenMessages .size());
-
- int tcpStarted = 0;
- int sslStarted = 0;
-
- for (String message : listenMessages)
- {
- if (message.endsWith("Listening on TCP port " + amqpPort))
- {
- tcpStarted++;
- }
- if (message.endsWith("Listening on SSL port " + amqpTlsPort))
- {
- 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(amqpPort);
- testSocketOpen(amqpTlsPort);
-
- validation = true;
- }
-
- assertTrue("Validation not performed: " + TESTID + " not logged", validation);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Description:
- * The final message the broker will print when it has performed all initialisation and listener startups will be to log the BRK-1004 Ready message
- * Input:
- * No input, all successful broker startups will show BRK-1004 messages.
- * Output:
- *
- * 2009-07-09 15:50:20 +0100 MESSAGE BRK-1004 : Qpid Broker Ready
- *
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. This occurs after the BRK-1001 startup message
- * 3. This must be the last message the broker prints after startup. Currently, if there is no further interaction with the broker then there should be no more logging.
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerStartupReady() throws Exception
- {
- if (isJavaBroker())
- {
- String TESTID = "BRK-1004";
-
- super.startDefaultBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(getOutputFile());
-
- //Ensure the broker has fully started up.
- getConnection();
- // Ensure we wait for TESTID to be logged
- waitAndFindMatches(TESTID);
-
- // Retrieve all BRK- log messages so we can check for an erroneous
- // BRK-1001 message.
- List<String> results = findMatches(BRK_LOG_PREFIX);
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- boolean validationComplete = false;
- boolean foundBRK1001 = false;
-
- for (int i=0; i < results.size(); i++)
- {
- String rawLog = results.get(i);
- String log = getLog(rawLog);
-
- // Ensure we do not have a BRK-1001 message
- if (!getMessageID(log).equals(TESTID))
- {
- if (getMessageID(log).equals("BRK-1001"))
- {
- foundBRK1001 = true;
- }
- continue;
- }
-
- assertTrue("BRK-1001 not logged before this message", foundBRK1001);
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- assertEquals("Ready message not present", "Qpid Broker Ready", getMessageString(log));
-
- assertEquals("Unexpected ready message count",
- 1, findMatches(TESTID).size());
- assertEquals("The ready messages should have been the last 2 messages", results.size() - 1, i);
-
- validationComplete = true;
- break;
- }
-
- assertTrue("Validation not performed: " + TESTID + " not logged", validationComplete);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Description:
- * On startup the broker may listen on a number of ports and protocols. Each of these must then report a shutting down message as they stop listening.
- * Input:
- * The default configuration with no SSL
- * Output:
- *
- * <date> MESSAGE BRK-1003 : Shutting down : TCP port 5672
- *
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. Only TCP is reported with the default configuration with no SSL.
- * 3. The default port is correct
- * 4. The port is not accessible after this message
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerShutdownListeningTCPDefault() throws Exception
- {
- if (isJavaBroker() && isInternalBroker())
- {
- String TESTID = "BRK-1003";
-
- super.startDefaultBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(getOutputFile());
-
- stopDefaultBroker();
-
- //Give broker time to shutdown and flush log
- checkSocketClosed(getDefaultBroker().getAmqpPort());
-
- List<String> results = waitAndFindMatches(BRK_LOG_PREFIX);
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- boolean validation = false;
- boolean foundBRK1001 = false;
- for (String rawLog : results)
- {
- String log = getLog(rawLog);
-
- // Ensure we do not have a BRK-1002 message
- if (!getMessageID(log).equals(TESTID))
- {
- if (getMessageID(log).equals("BRK-1001"))
- {
- foundBRK1001 = true;
- }
- continue;
- }
-
- assertTrue("BRK-1001 not logged before this message", foundBRK1001);
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- assertEquals("More than one listen message found.",
- 1, findMatches(TESTID).size());
-
- //3
- String message = getMessageString(log);
- final int amqpPort = getDefaultBroker().getAmqpPort();
- assertTrue("Expected shutdown log not correct" + message,
- message.endsWith("TCP port " + amqpPort));
-
- //4
- checkSocketClosed(amqpPort);
-
- validation = true;
- }
-
- assertTrue("Validation not performed: " + TESTID + " not logged", validation);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Description:
- * On startup the broker may listen on a number of ports and protocols. Each of these must be reported as they are made available.
- * Input:
- * The default configuration with SSL enabled
- * Output:
- *
- * <date> MESSAGE BRK-1002 : Starting : Listening on TCP port 5672
- * <date> MESSAGE BRK-1002 : Starting : Listening on TCP/SSL port 8672
- *
- * Constraints:
- * Additional broker configuration will occur between the Startup(BRK-1001) and Starting(BRK-1002) messages depending on what VirtualHosts are configured.
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. This occurs after the BRK-1001 startup message
- * 3. With SSL enabled in the configuration two BRK-1002 will be printed (order is not specified)
- * 1. One showing values TCP / 5672
- * 2. One showing values TCP/SSL / 5672
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerShutdownListeningTCPSSL() throws Exception
- {
- if (isJavaBroker() && isInternalBroker())
- {
- String TESTID = "BRK-1003";
-
- // Enable SSL on the connection
- Map<String, Object> sslPortAttributes = new HashMap<String, Object>();
- 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);
- getDefaultBrokerConfiguration().addObjectConfiguration(Port.class, sslPortAttributes);
-
- super.startDefaultBroker();
-
- final BrokerHolder defaultBroker = getDefaultBroker();
- int amqpTlsPort = defaultBroker.getAmqpTlsPort();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(getOutputFile());
-
-
-// //Clear any startup messages as we don't need them for validation
-// _monitor.reset();
- //Stop the broker to get the log messages for testing
- stopDefaultBroker();
-
- //Give broker time to shutdown and flush log
- final int amqpPort = getDefaultBroker().getAmqpPort();
- checkSocketClosed(amqpPort);
-
- List<String> results = waitAndFindMatches(TESTID);
- try
- {
- // Validation
-
- assertTrue(TESTID + " messages not logged", results.size() > 0);
-
- String log = getLog(results.get(0));
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- List<String> listenMessages = findMatches(TESTID);
- assertEquals("Two shutdown messages should be found.",
- 2, listenMessages.size());
-
- int tcpShuttingDown = 0;
- int sslShuttingDown = 0;
-
- for (String m : listenMessages)
- {
- if (m.endsWith("Shutting down : TCP port " + amqpPort))
- {
- tcpShuttingDown++;
- }
- if (m.endsWith("Shutting down : SSL port " + amqpTlsPort))
- {
- sslShuttingDown++;
- }
- }
-
- assertEquals("Unexpected number of logs 'Shutting down : TCP port'", 1, tcpShuttingDown);
- assertEquals("Unexpected number of logs 'Shutting down : SSL port'", 1, sslShuttingDown);
-
- //4
- //Test Port closed
- checkSocketClosed(amqpPort);
- //Test SSL Port closed
- checkSocketClosed(amqpTlsPort);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Description:
- * Input:
- * No input, all clean broker shutdowns will show BRK-1005 messages.
- * Output:
- *
- * <date> MESSAGE BRK-1005 : Stopped
- *
- * Constraints:
- * This is the LAST message the broker will log.
- * Validation Steps:
- *
- * 1. The BRK ID is correct
- * 2. This is the last message the broker will log.
- *
- * @throws Exception caused by broker startup
- */
- public void testBrokerShutdownStopped() throws Exception
- {
- if (isJavaBroker() && isInternalBroker())
- {
- String TESTID = "BRK-1005";
-
- super.startDefaultBroker();
-
- // Now we can create the monitor as _outputFile will now be defined
- _monitor = new LogMonitor(getOutputFile());
-
- getConnection().close();
-
- stopDefaultBroker();
-
- final int amqpPort = getDefaultBroker().getAmqpPort();
-
- // Ensure the broker has shutdown before retreving results
- checkSocketClosed(amqpPort);
-
- waitAndFindMatches(TESTID);
-
- List<String> results = waitAndFindMatches(BRK_LOG_PREFIX);
- try
- {
- // Validation
-
- assertTrue("BRKer message not logged", results.size() > 0);
-
- boolean validation = false;
- for (String rawLog : results)
- {
- assertFalse("More broker log statements present after ready message", validation);
- String log = getLog(rawLog);
-
- // Ignore all logs until we get to the test id.
- if (!getMessageID(log).equals(TESTID))
- {
- continue;
- }
-
- //1
- validateMessageID(TESTID, log);
-
- //2
- assertEquals("More than one ready message found.",
- 1, findMatches(TESTID).size());
-
- //3
- assertEquals("Stopped message not present", "Stopped", getMessageString(log));
-
- validation = true;
- }
-
- assertTrue("Validation not performed: " + TESTID + " not logged", validation);
- }
- catch (AssertionFailedError afe)
- {
- dumpLogs(results, _monitor);
-
- throw afe;
- }
- }
- }
-
- /**
- * Test that a socket on the given port is closed.
- *
- * Does this by attempting to connect to the port and expecting a
- * ConnectionRefused IOException or a ConnectionException
- *
- * @param port the port number
- */
- private void checkSocketClosed(int port)
- {
- try
- {
- Socket socket = new Socket((String) null, port);
- fail("Socket not closed on port:" + port);
- }
- catch (ConnectionException e)
- {
- //normal path
- }
- catch (IOException e)
- {
- if (!e.getMessage().startsWith("Connection refused"))
- {
- fail("Socket not closed on port:" + port + ":" + e.getMessage());
- // Keep stack trace for diagnosis.
- e.printStackTrace(System.err);
- }
- }
- }
-
- /**
- * Test that a socket on the given port is open.
- *
- * Does this by attempting to connect to the port and expecting a
- * The connection to succeed.
- * It then closes the socket and expects that to work cleanly.
- *
- * @param port the port number
- */
- private void testSocketOpen(int port)
- {
- try
- {
- Socket socket = new Socket((String) null, port);
- socket.close();
- }
- catch (IOException e)
- {
- fail("Unable to open and close socket to port:" + port
- + ". Due to:" + e.getMessage());
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/systests/src/test/java/org/apache/qpid/server/logging/ChannelLoggingTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/server/logging/ChannelLoggingTest.java b/systests/src/test/java/org/apache/qpid/server/logging/ChannelLoggingTest.java
deleted file mode 100644
index f16398c..0000000
--- a/systests/src/test/java/org/apache/qpid/server/logging/ChannelLoggingTest.java
+++ /dev/null
@@ -1,384 +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.server.logging;
-
-import java.util.List;
-import java.util.regex.Pattern;
-
-import javax.jms.Connection;
-import javax.jms.MessageConsumer;
-import javax.jms.Queue;
-import javax.jms.Session;
-
-import org.apache.qpid.QpidException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.server.virtualhost.VirtualHostPropertiesNodeCreator;
-
-public class ChannelLoggingTest extends AbstractTestLogging
-{
- private static final String CHANNEL_CLOSE_FORCED_MESSAGE_PATTERN = "CHN-1003 : Close : \\d* - .*";
- private static final String CHANNEL_PREFIX = "CHN-";
-
- @Override
- public void setUp() throws Exception
- {
-
- // disable the virtualhostPropertiesNode as it messes with the logging since it causes the client to
- // create a session and then it sends a message
- setTestSystemProperty("qpid.plugin.disabled:systemnodecreator."+ VirtualHostPropertiesNodeCreator.TYPE, "true");
- super.setUp();
- }
-
- /**
- * Description:
- * When a new Channel (JMS Session) is created this will be logged as a CHN-1001 Create message. The messages will contain the prefetch details about this new Channel.
- * Input:
- *
- * 1. Running Broker
- * 2. New JMS Session/Channel creation
- *
- * Output:
- * <date> CHN-1001 : Create
- * <date> CHN-1004 : Prefetch Size (bytes) {0,number} : Count {1,number}
- *
- * Validation Steps:
- * 1. The CHN ID is correct
- * 2. The prefetch value matches that defined by the requesting client.
- *
- * @throws Exception - if an error occurs
- */
- public void testChannelCreate() throws Exception
- {
- assertLoggingNotYetOccured(CHANNEL_PREFIX);
-
- Connection connection = getConnection();
-
- int PREFETCH = 12;
-
- if(!(isBroker010() || isBroker10()))
- {
- // Test that calling session.close gives us the expected output
- ((AMQConnection) connection).createSession(false, Session.AUTO_ACKNOWLEDGE, PREFETCH);
- }
- else
- {
- connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- }
-
- // Wait to ensure that the CHN-1001 message is logged
- waitForMessage("CHN-1001");
-
- List<String> results = findMatches("CHN-1001");
-
- // Validation
- assertEquals("CHN-1001 messages not logged", isBroker10() ? 2 : 1, results.size());
-
- String log = getLogMessage(results, isBroker10() ? 1 : 0);
- // MESSAGE [con:0(guest@anonymous(3273383)/test)/ch:1] CHN-1001 : Create
- validateMessageID("CHN-1001", log);
- final String fromActor = fromActor(log);
- final int channelID = getChannelID(fromActor);
- assertEquals("Incorrect Channel in actor:"+fromActor(log), isBroker010()? 0 : 1, channelID);
-
- if (!(isBroker010() || isBroker10()))
- {
- // Wait to ensure that the CHN-1004 message is logged
- waitForMessage("CHN-1004");
-
- results = findMatches("CHN-1004");
-
- // Validation
- assertEquals("CHN-1004 messages not logged", 1, results.size());
- log = getLogMessage(results, 0);
- // MESSAGE [con:0(guest@anonymous(3273383)/test)/ch:1] CHN-1004 : Prefetch Size (bytes) {0,number} : Count {1,number}
- validateMessageID("CHN-1004", log);
- assertEquals("Incorrect Channel in actor:"+fromActor(log), 1, getChannelID(fromActor(log)));
- assertTrue("Prefetch Count not correct",getMessageString(fromMessage(log)).endsWith("Count "+PREFETCH));
- }
-
- connection.close();
- }
-
- /**
- * Description:
- * The Apache Qpid Broker-J implements consumer flow control for all ack modes except
- * No-Ack. When a client connects the session's flow is initially set to
- * Stopped. Verify this message appears
- *
- * Input:
- * 1. Running broker
- * 2. Create consumer
- * Output:
- *
- * <date> CHN-1002 : Flow Stopped
- *
- * Validation Steps:
- * 4. The CHN ID is correct
- *
- * @throws Exception - if an error occurs
- */
-
- public void testChannelStartsFlowStopped() throws Exception
- {
- assertLoggingNotYetOccured(CHANNEL_PREFIX);
-
- Connection connection = getConnection();
-
- // Create a session to fill up
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Queue queue = createTestQueue(session);
-
- connection.start();
-
- // Wait to ensure that the CHN-1002 message is logged
- waitForMessage("CHN-1002");
-
- List<String> results = findMatches(CHANNEL_PREFIX);
-
- assertTrue("No CHN messages logged", results.size() > 0);
-
- // The last channel message should be:
- //
- // INFO - MESSAGE [con:0(guest@anonymous(4205299)/test)/ch:1] [con:0(guest@anonymous(4205299)/test)/ch:1] CHN-1002 : Flow Stopped
-
- // Verify the last channel message is stopped
- validateChannelStart(results, false);
- }
-
- private void validateChannelStart(List<String> results, boolean flowStarted)
- {
- String log = getLogMessageFromEnd(results, 0);
-
- String flow = flowStarted ? "Started" : "Stopped";
- validateMessageID("CHN-1002", log);
- assertEquals("Message should be Flow " + flow, "Flow " + flow, getMessageString(fromMessage(log)));
- }
-
- /**
- * Description:
- * The Apache Qpid Broker-J implements consumer flow control for all ack modes except
- * No-Ack. When the client first attempts to receive a message then the Flow
- * status of the Session is set to Started.
- *
- * Input:
- * 1. Running broker
- * 2. Create a consumer
- * 3. Attempt to receive a message
- * Output:
- *
- * <date> CHN-1002 : Flow Started
- *
- * Validation Steps:
- * 4. The CHN ID is correct
- *
- * @throws Exception - if an error occurs
- */
-
- public void testChannelStartConsumerFlowStarted() throws Exception
- {
- assertLoggingNotYetOccured(CHANNEL_PREFIX);
-
- Connection connection = getConnection();
-
- // Create a session to fill up
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Queue queue = createTestQueue(session);
-
- MessageConsumer consumer = session.createConsumer(queue);
-
- connection.start();
-
- //Call receive to send the Flow On message
- consumer.receiveNoWait();
-
- //Wait for up to 2 seconds for message to appear
- // ignore response as we will use the findMatches afterwards just
- // incase it did take more than 2 seconds to log.
- _monitor.waitForMessage(CHANNEL_PREFIX, 2000);
-
- // Wait to ensure that the CHN-1002 message is logged
- waitForMessage("CHN-1002");
-
- List<String> results = findMatches(CHANNEL_PREFIX);
-
- assertTrue("No CHN messages logged", results.size() > 0);
-
- // The last two channel messages(before the close) should be:
- //
- // INFO [qpid.message] MESSAGE [con:1(guest@/127.0.0.1:49869/test)/ch:1] [con:1(guest@/127.0.0.1:49869/test)/ch:1] CHN-1002 : Flow Stopped
- // INFO [qpid.message] MESSAGE [con:1(guest@/127.0.0.1:49869/test)/ch:1] [con:1(guest@/127.0.0.1:49869/test)/ch:1] CHN-1002 : Flow Started
-
- // Verify the last channel msg is Started.
- validateChannelStart(results, true);
- }
-
- /**
- * Description:
- * When the client gracefully closes the Connection then a CHN-1003 Close
- * message will be issued. This must be the last message logged for this
- * Channel.
- * Input:
- * 1. Running Broker
- * 2. Connected Client
- * 3. Client then requests that the Connection is closed
- * Output:
- *
- * <date> CHN-1003 : Close
- *
- * Validation Steps:
- * 4. The MST ID is correct
- * 5. This must be the last message logged for this Channel.
- *
- * @throws Exception - if an error occurs
- */
- public void testChannelCloseViaConnectionClose() throws Exception
- {
- assertLoggingNotYetOccured(CHANNEL_PREFIX);
-
- Connection connection = getConnection();
-
- // Create a session
- connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // Close the connection to verify the created session closing is logged.
- connection.close();
-
- // Wait to ensure that the CHN-1003 message is logged
- waitForMessage("CHN-1003");
-
- List<String> results = findMatches(CHANNEL_PREFIX);
-
- assertTrue("No CHN messages logged", results.size() > 0);
-
- // The last two channel messages should be:
- //
- // INFO - MESSAGE [con:0(guest@anonymous(4205299)/test)/ch:1] [con:0(guest@anonymous(4205299)/test)/ch:1] CHN-1002 : Flow On
-
- // Verify
- validateChannelClose(results);
- }
-
- /**
- * Description:
- * When the client gracefully closes the Connection then a CHN-1003 Close
- * message will be issued. This must be the last message logged for this
- * Channel.
- * Input:
- * 1. Running Broker
- * 2. Connected Client
- * 3. Client then requests that the Channel is closed
- * Output:
- *
- * <date> CHN-1003 : Close
- *
- * Validation Steps:
- * 4. The MST ID is correct
- * 5. This must be the last message logged for this Channel.
- *
- * @throws Exception - if an error occurs
- */
- public void testChannelCloseViaChannelClose() throws Exception
- {
- assertLoggingNotYetOccured(CHANNEL_PREFIX);
-
- Connection connection = getConnection();
-
- // Create a session and then close it
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- waitForMessage("CHN-1001");
-
- // Wait to ensure that the CHN-1003 message is logged
- session.close();
- waitForMessage("CHN-1003");
-
- List<String> results = findMatches(CHANNEL_PREFIX);
-
- assertTrue("No CHN messages logged", results.size() > 0);
-
- // Verify
- validateChannelClose(results);
- }
-
- public void testChannelClosedOnExclusiveQueueDeclaredOnDifferentSession() throws Exception
- {
- assertLoggingNotYetOccured(CHANNEL_PREFIX);
-
- Connection connection = getConnection();
-
- // Create a session and then close it
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- waitForMessage("CHN-1001");
-
- Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- waitForMessage("CHN-1001");
-
- String testQueueName = getTestQueueName();
-
- Queue queue = (Queue) session.createQueue("direct://amq.direct/" + testQueueName + "/" + testQueueName
- + "?exclusive='true'");
-
- ((AMQSession<?,?>)session).declareAndBind((AMQDestination)queue);
-
- try
- {
- ((AMQSession<?,?>)session2).declareAndBind((AMQDestination) queue);
- fail("Exception not thrown");
- }
- catch (QpidException acce)
- {
- // pass
- }
- catch (Exception e)
- {
- fail("Wrong exception thrown " + e);
- }
- waitForMessage("CHN-1003");
-
- List<String> results = findMatches(CHANNEL_PREFIX);
- assertTrue("No CHN messages logged", results.size() > 0);
-
- String closeLog = results.get(results.size() -1);
- int closeMessageID = closeLog.indexOf("CHN-1003");
- assertFalse("CHN-1003 is not found", closeMessageID == -1);
-
- String closeMessage = closeLog.substring(closeMessageID);
- assertTrue("Unexpected close channel message :" + closeMessage, Pattern.matches(CHANNEL_CLOSE_FORCED_MESSAGE_PATTERN, closeMessage));
-
- session.close();
- connection.close();
- }
- private void validateChannelClose(List<String> results)
- {
- String open = getLogMessage(results, isBroker10() ? 1 : 0);
- String close = getLogMessageFromEnd(results, 0);
-
- validateMessageID("CHN-1001", open);
- validateMessageID("CHN-1003", close);
- assertEquals("Message should be Close", "Close", getMessageString(fromMessage(close)));
- assertEquals("Incorrect Channel ID closed: " + close, isBroker010()? 0 : 1, getChannelID(fromSubject(close)));
- assertEquals("Channel IDs should be the same", getChannelID(fromActor(open)), getChannelID(fromSubject(close)));
- assertEquals("Connection IDs should be the same", getConnectionID(fromActor(open)), getConnectionID(fromSubject(close)));
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b21a8f56/systests/src/test/java/org/apache/qpid/server/logging/ConnectionLoggingTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/server/logging/ConnectionLoggingTest.java b/systests/src/test/java/org/apache/qpid/server/logging/ConnectionLoggingTest.java
deleted file mode 100644
index d38665b..0000000
--- a/systests/src/test/java/org/apache/qpid/server/logging/ConnectionLoggingTest.java
+++ /dev/null
@@ -1,209 +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.server.logging;
-
-import java.util.List;
-import java.util.Map;
-import java.util.TreeSet;
-
-import javax.jms.Connection;
-
-import org.apache.qpid.configuration.CommonProperties;
-
-public class ConnectionLoggingTest extends AbstractTestLogging
-{
- private static final String CONNECTION_PREFIX = "CON-";
-
- // No explicit startup configuration is required for this test
- // so no setUp() method
-
- /**
- * Description:
- * When a new connection is made to the broker this must be logged.
- *
- * Input:
- * 1. Running Broker
- * 2. Connecting client
- * Output:
- * <date> CON-1001 : Open ....
- *
- * Validation Steps:
- * 1. The CON ID is correct
- * 2. This is the first CON message for that Connection
- *
- * @throws Exception - if an error occurs
- */
- public void testConnectionOpen() throws Exception
- {
- assertLoggingNotYetOccured(CONNECTION_PREFIX);
-
- Connection connection = getConnection();
- String clientid = connection.getClientID();
-
- // Wait until opened
- waitForMessage("CON-1001");
-
- // Close the connection
- connection.close();
-
- // Wait to ensure that the desired message is logged
- waitForMessage("CON-1002");
-
- List<String> results = waitAndFindMatches("CON-1001");
-
- // MESSAGE [con:1(/127.0.0.1:46927)] CON-1001 : Open : Destination : amqp(127.0.0.1:15672) : Protocol Version : 0-10
- // MESSAGE [con:1(guest@/127.0.0.1:46927/test)] CON-1001 : Open : Destination : amqp(127.0.0.1:15672) : Protocol Version : 0-10 : Client ID : clientid : Client Version : 6.0.0-SNAPSHOT : Client Product : qpid
- // MESSAGE [con:1(guest@/127.0.0.1:46927/test)] CON-1002 : Close
-
- Map<Integer, List<String>> connectionData = splitResultsOnConnectionID(results);
-
- // Get the last Integer from keySet of the ConnectionData
- int connectionID = new TreeSet<>(connectionData.keySet()).last();
-
- //Use just the data from the last connection for the test
- results = connectionData.get(connectionID);
-
- assertEquals("Unexpected CON-1001 messages count", 2, results.size());
-
- // validate the two CON-1001 messages.
- // MESSAGE [con:1(guest@/127.0.0.1:46927/test)] CON-1001 : Open : Destination : amqp(127.0.0.1:15672) : Protocol Version : 0-10 : Client ID : clientid : Client Version : 6.0.0-SNAPSHOT : Client Product : qpid
- validateConnectionOpen(results, 0,
- true, getBrokerProtocol().getProtocolVersion(),
- true, clientid,
- true, CommonProperties.getReleaseVersion(),
- true, CommonProperties.getProductName());
-
- // MESSAGE [con:1(/127.0.0.1:46927)] CON-1001 : Open : Destination : amqp(127.0.0.1:15672) : Protocol Version : 0-10
- validateConnectionOpen(results, 1,
- true, getBrokerProtocol().getProtocolVersion(),
- false, null,
- false, null,
- false, null);
- }
-
- private void validateConnectionOpen(List<String> results, int positionFromEnd,
- boolean protocolVersionPresent, final String protocolVersionValue,
- boolean clientIdOptionPresent, String clientIdValue,
- boolean clientVersionPresent, String clientVersionValue,
- boolean clientProductPresent, String clientProductValue)
- {
- String log = getLogMessageFromEnd(results, positionFromEnd);
-
- validateMessageID("CON-1001", log);
-
- String message = fromMessage(log);
-
- assertTrue("Destination not present", message.contains("Destination :"));
-
- assertEquals("unexpected Protocol Version option state",
- protocolVersionPresent, message.contains("Protocol Version :"));
- if(protocolVersionPresent && protocolVersionValue != null)
- {
- assertTrue("Protocol Version value is not present: " + protocolVersionValue, message.contains(protocolVersionValue));
- }
-
- assertEquals("unexpected Client ID option state", clientIdOptionPresent, message.contains("Client ID :"));
-
- if(clientIdOptionPresent && clientIdValue != null)
- {
- assertTrue("Client ID value is not present: " + clientIdValue, message.contains(clientIdValue));
- }
-
-
- assertEquals("unexpected Client Version option state", clientVersionPresent, message.contains(
- "Client Version :"));
-
- if(clientVersionPresent && clientVersionValue != null && !isBroker10())
- {
- assertTrue("Client version value is not present: " + clientVersionValue, message.contains(
- clientVersionValue));
- }
-
- assertEquals("unexpected Client Product option state", clientVersionPresent, message.contains(
- "Client Product :"));
-
- if(clientProductPresent && clientProductValue != null && !isBroker10())
- {
- assertTrue("Client product value is not present: " + clientProductValue, message.contains(
- clientProductValue));
- }
- }
-
- /**
- * Description:
- * When a connected client closes the connection this will be logged as a CON-1002 message.
- * Input:
- *
- * 1. Running Broker
- * 2. Connected Client
- * Output:
- *
- * <date> CON-1002 : Close
- *
- * Validation Steps:
- * 3. The CON ID is correct
- * 4. This must be the last CON message for the Connection
- * 5. It must be preceded by a CON-1001 for this Connection
- */
- public void testConnectionClose() throws Exception
- {
- assertLoggingNotYetOccured(CONNECTION_PREFIX);
-
- Connection connection = getConnection();
-
- // Wait until opened
- waitForMessage("CON-1001");
-
- // Close the conneciton
- connection.close();
-
- // Wait to ensure that the desired message is logged
- waitForMessage("CON-1002");
-
- List<String> results = findMatches(CONNECTION_PREFIX);
-
- // Validation
-
- assertEquals("CON messages not logged:" + results.size(), 3, results.size());
-
- // Validate Close message occurs
- String log = getLogMessageFromEnd(results, 0);
- validateMessageID("CON-1002",log);
- assertTrue("Message does not end with close:" + log, log.endsWith("Close"));
-
- // Extract connection ID to validate there is a CON-1001 message for it
- final String logSubject = fromActor(log);
- int closeConnectionID = getConnectionID(logSubject);
- assertTrue("Could not get the connection id from CLOSE message: " + logSubject, closeConnectionID != -1);
-
- //Previous log message should be the open
- log = getLogMessageFromEnd(results, 1);
- // MESSAGE [con:1(/127.0.0.1:52540)] CON-1001 : Open : Client ID : clientid : Protocol Version : 0-9
- validateMessageID("CON-1001",log);
-
- // Extract connection ID to validate it matches the CON-1002 messasge
- int openConnectionID = getConnectionID(fromActor(log));
- assertTrue("Could not find connection id in OPEN", openConnectionID != -1);
-
- // Check connection ids match
- assertEquals("Connection IDs do not match", closeConnectionID, openConnectionID);
- }
-}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org
[6/8] qpid-broker-j git commit: NO-JIRA: [Broker-J] [System Tests]
Remove Rest ACL Tests
Posted by kw...@apache.org.
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/test/java/org/apache/qpid/systest/rest/acl/UserRestACLTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/systest/rest/acl/UserRestACLTest.java b/systests/src/test/java/org/apache/qpid/systest/rest/acl/UserRestACLTest.java
deleted file mode 100644
index 6fe6d06..0000000
--- a/systests/src/test/java/org/apache/qpid/systest/rest/acl/UserRestACLTest.java
+++ /dev/null
@@ -1,183 +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.systest.rest.acl;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.Map;
-import java.util.Properties;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.qpid.systest.rest.QpidRestTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-import org.apache.qpid.test.utils.TestUtils;
-
-public class UserRestACLTest extends QpidRestTestCase
-{
- private static final String ALLOWED_GROUP = "allowedGroup";
- private static final String DENIED_GROUP = "deniedGroup";
- private static final String OTHER_GROUP = "otherGroup";
-
- private static final String ALLOWED_USER = "webadmin";
- private static final String DENIED_USER = "admin";
- private static final String OTHER_USER = "other";
-
- private File _groupFile;
-
- @Override
- public void startDefaultBroker() throws Exception
- {
- // starting broker in tests
- }
-
- @Override
- protected void customizeConfiguration() throws Exception
- {
- super.customizeConfiguration();
- _groupFile = createTemporaryGroupFile();
- final TestBrokerConfiguration brokerConfiguration = getDefaultBrokerConfiguration();
- brokerConfiguration.addGroupFileConfiguration(_groupFile.getAbsolutePath());
- brokerConfiguration.configureTemporaryPasswordFile(ALLOWED_USER, DENIED_USER, OTHER_USER);
- }
-
- @Override
- public void tearDown() throws Exception
- {
- super.tearDown();
-
- if (_groupFile != null)
- {
- if (_groupFile.exists())
- {
- _groupFile.delete();
- }
- }
- }
-
- private File createTemporaryGroupFile() throws Exception
- {
- File groupFile = File.createTempFile("group", "grp");
- groupFile.deleteOnExit();
-
- Properties props = new Properties();
- props.put(ALLOWED_GROUP + ".users", ALLOWED_USER);
- props.put(DENIED_GROUP + ".users", DENIED_USER);
- props.put(OTHER_GROUP + ".users", OTHER_USER);
-
- props.store(new FileOutputStream(groupFile), "test group file");
-
- return groupFile;
- }
-
- public void testAddUser() throws Exception
- {
- TestUtils.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT",
- "ACL ALLOW-LOG " + ALLOWED_GROUP + " CREATE USER",
- "ACL DENY-LOG " + DENIED_GROUP + " CREATE USER");
-
- super.startDefaultBroker();
-
- String newUser = "newUser";
- String password = "password";
-
- assertUserDoesNotExist(newUser);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- getRestTestHelper().createOrUpdateUser(newUser, password, HttpServletResponse.SC_FORBIDDEN);
- assertUserDoesNotExist(newUser);
-
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
- getRestTestHelper().createOrUpdateUser(newUser, password);
- assertUserExists(newUser);
- }
-
- public void testDeleteUser() throws Exception
- {
- TestUtils.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT",
- "ACL ALLOW-LOG " + ALLOWED_GROUP + " DELETE USER",
- "ACL DENY-LOG " + DENIED_GROUP + " DELETE USER");
-
- super.startDefaultBroker();
-
- assertUserExists(OTHER_USER);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- getRestTestHelper().removeUser(OTHER_USER, HttpServletResponse.SC_FORBIDDEN);
- assertUserExists(OTHER_USER);
-
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
- getRestTestHelper().removeUser(OTHER_USER);
- assertUserDoesNotExist(OTHER_USER);
- }
-
- public void testUpdateUser() throws Exception
- {
- TestUtils.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT",
- "ACL ALLOW-LOG " + ALLOWED_GROUP + " UPDATE USER",
- "ACL DENY-LOG " + DENIED_GROUP + " UPDATE USER");
-
- super.startDefaultBroker();
-
- String newPassword = "newPassword";
-
- checkPassword(OTHER_USER, OTHER_USER, true);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- getRestTestHelper().createOrUpdateUser(OTHER_USER, newPassword, HttpServletResponse.SC_FORBIDDEN);
-
- checkPassword(OTHER_USER, newPassword, false);
-
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
- getRestTestHelper().createOrUpdateUser(OTHER_USER, newPassword, HttpServletResponse.SC_OK); // expect SC_OK rather than the default SC_CREATED
-
- checkPassword(OTHER_USER, newPassword, true);
- checkPassword(OTHER_USER, OTHER_USER, false);
- }
-
- private void checkPassword(String username, String password, boolean passwordExpectedToBeCorrect) throws IOException
- {
- getRestTestHelper().setUsernameAndPassword(username, password);
-
- int responseCode = getRestTestHelper().submitRequest("user/"
- + TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER + "/", "GET", (byte[])null);
- boolean passwordIsCorrect = responseCode == HttpServletResponse.SC_OK;
-
- assertEquals(passwordExpectedToBeCorrect, passwordIsCorrect);
- }
-
- private void assertUserDoesNotExist(String newUser) throws IOException
- {
- String path = "user/" + TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER + "/" + newUser;
- getRestTestHelper().submitRequest(path, "GET", HttpServletResponse.SC_NOT_FOUND);
- }
-
- private void assertUserExists(String username) throws IOException
- {
- String path = "user/" + TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER + "/" + username;
- Map<String, Object> userDetails = getRestTestHelper().getJsonAsMap(path);
-
- assertEquals(
- "User returned by " + path + " should have name=" + username + ". The returned JSON was: " + userDetails,
- username,
- userDetails.get("name"));
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/test/java/org/apache/qpid/systest/rest/acl/VirtualHostACLTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/systest/rest/acl/VirtualHostACLTest.java b/systests/src/test/java/org/apache/qpid/systest/rest/acl/VirtualHostACLTest.java
deleted file mode 100644
index e117cc3..0000000
--- a/systests/src/test/java/org/apache/qpid/systest/rest/acl/VirtualHostACLTest.java
+++ /dev/null
@@ -1,188 +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.systest.rest.acl;
-
-import java.io.File;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.qpid.server.logging.logback.VirtualHostFileLogger;
-import org.apache.qpid.server.model.ConfiguredObject;
-import org.apache.qpid.server.model.VirtualHost;
-import org.apache.qpid.server.model.VirtualHostLogger;
-import org.apache.qpid.server.model.VirtualHostNode;
-import org.apache.qpid.server.virtualhost.ProvidedStoreVirtualHostImpl;
-import org.apache.qpid.server.virtualhostnode.JsonVirtualHostNode;
-import org.apache.qpid.systest.rest.QpidRestTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-import org.apache.qpid.test.utils.TestUtils;
-
-public class VirtualHostACLTest extends QpidRestTestCase
-{
- private static final String VHN_WITHOUT_VH = "myVhnWithoutVh";
-
- private static final String ALLOWED_USER = "user1";
- private static final String DENIED_USER = "user2";
- private static final String RESTRICTED_USER = "restricted";
-
- @Override
- protected void customizeConfiguration() throws Exception
- {
- super.customizeConfiguration();
- final TestBrokerConfiguration defaultBrokerConfiguration = getDefaultBrokerConfiguration();
- defaultBrokerConfiguration.configureTemporaryPasswordFile(ALLOWED_USER, DENIED_USER, RESTRICTED_USER);
-
- TestUtils.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT",
- "ACL ALLOW-LOG " + ALLOWED_USER + " ALL VIRTUALHOST",
- "ACL ALLOW-LOG " + RESTRICTED_USER + " ALL VIRTUALHOST attributes=\"description\"",
- "ACL DENY-LOG " + DENIED_USER + " ALL VIRTUALHOST",
- "ACL DENY-LOG ALL ALL");
-
- Map<String, Object> virtualHostNodeAttributes = new HashMap<>();
- virtualHostNodeAttributes.put(VirtualHostNode.NAME, VHN_WITHOUT_VH);
- virtualHostNodeAttributes.put(VirtualHostNode.TYPE, getTestProfileVirtualHostNodeType());
- // TODO need better way to determine the VHN's optional attributes
- virtualHostNodeAttributes.put(JsonVirtualHostNode.STORE_PATH, getStoreLocation(VHN_WITHOUT_VH));
-
- defaultBrokerConfiguration.addObjectConfiguration(VirtualHostNode.class, virtualHostNodeAttributes);
- }
-
- public void testCreateVirtualHostAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String hostName = getTestName();
-
- int responseCode = createVirtualHost(VHN_WITHOUT_VH, hostName);
- assertEquals("Virtual host creation should be allowed", HttpServletResponse.SC_CREATED, responseCode);
-
- assertVirtualHostExists(VHN_WITHOUT_VH, hostName);
- }
-
- public void testCreateVirtualHostDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- String hostName = getTestName();
-
- int responseCode = createVirtualHost(VHN_WITHOUT_VH, hostName);
- assertEquals("Virtual host creation should be denied", HttpServletResponse.SC_FORBIDDEN, responseCode);
-
- assertVirtualHostDoesNotExist(VHN_WITHOUT_VH, hostName);
- }
-
- public void testDeleteVirtualHostDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- getRestTestHelper().submitRequest("virtualhost/" + TEST2_VIRTUALHOST + "/" + TEST2_VIRTUALHOST, "DELETE", HttpServletResponse.SC_FORBIDDEN);
-
- assertVirtualHostExists(TEST2_VIRTUALHOST, TEST2_VIRTUALHOST);
- }
-
- public void testUpdateRestrictedAttributes() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(RESTRICTED_USER, RESTRICTED_USER);
-
- String virtualHostUrl = "virtualhost/" + TEST2_VIRTUALHOST + "/" + TEST2_VIRTUALHOST;
- getRestTestHelper().submitRequest(virtualHostUrl,
- "PUT",
- Collections.singletonMap(VirtualHost.CONTEXT,
- Collections.singletonMap("test1", "test2")),
- HttpServletResponse.SC_FORBIDDEN);
-
- getRestTestHelper().submitRequest(virtualHostUrl,
- "PUT",
- Collections.singletonMap(VirtualHost.DESCRIPTION, "Test Description"),
- HttpServletResponse.SC_OK);
- }
-
- public void testUpdateVirtualHostDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(VirtualHost.NAME, TEST2_VIRTUALHOST);
- attributes.put(VirtualHost.DESCRIPTION, "new description");
-
- getRestTestHelper().submitRequest("virtualhost/" + TEST2_VIRTUALHOST + "/" + TEST2_VIRTUALHOST, "PUT", attributes, HttpServletResponse.SC_FORBIDDEN);
- }
-
- public void testDownloadVirtualHostLoggerFileAllowedDenied() throws Exception
- {
- final String virtualHostName = "testVirtualHost";
- final String loggerName = "testFileLogger";
- final String loggerPath = "virtualhostlogger/" + VHN_WITHOUT_VH + "/" + virtualHostName + "/" + loggerName;
-
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- createVirtualHost(VHN_WITHOUT_VH, virtualHostName);
-
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(VirtualHostLogger.NAME, loggerName);
- attributes.put(ConfiguredObject.TYPE, VirtualHostFileLogger.TYPE);
- getRestTestHelper().submitRequest("virtualhostlogger/" + VHN_WITHOUT_VH + "/" + virtualHostName, "PUT", attributes, HttpServletResponse.SC_CREATED);
-
- getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_OK);
- getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_OK);
- getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_OK);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN);
- getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN);
- getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_FORBIDDEN);
- }
-
- /* === Utility Methods === */
-
- private int createVirtualHost(final String testVirtualHostNode, String virtualHostName) throws Exception
- {
- Map<String, Object> data = new HashMap<>();
- data.put(VirtualHost.NAME, virtualHostName);
- data.put(VirtualHost.TYPE, ProvidedStoreVirtualHostImpl.VIRTUAL_HOST_TYPE);
-
- return getRestTestHelper().submitRequest("virtualhost/" + testVirtualHostNode + "/" + virtualHostName, "PUT", data);
- }
-
- private void assertVirtualHostDoesNotExist(final String virtualHostNodeName, String virtualHostName) throws Exception
- {
- assertVirtualHostExistence(virtualHostNodeName, virtualHostName, false);
- }
-
- private void assertVirtualHostExists(final String virtualHostNodeName, String virtualHostName) throws Exception
- {
- assertVirtualHostExistence(virtualHostNodeName, virtualHostName, true);
- }
-
- private void assertVirtualHostExistence(final String virtualHostNodeName, String virtualHostName, boolean exists) throws Exception
- {
- String path = "virtualhost/" + virtualHostNodeName + "/" + virtualHostName;
- int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND;
- getRestTestHelper().submitRequest(path, "GET", expectedResponseCode);
- }
-
- private String getStoreLocation(String hostName)
- {
- return new File(TMP_FOLDER, "store-" + hostName + "-" + System.currentTimeMillis()).getAbsolutePath();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/test/java/org/apache/qpid/systest/rest/acl/VirtualHostAccessControlProviderRestTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/systest/rest/acl/VirtualHostAccessControlProviderRestTest.java b/systests/src/test/java/org/apache/qpid/systest/rest/acl/VirtualHostAccessControlProviderRestTest.java
deleted file mode 100644
index c37b1f2..0000000
--- a/systests/src/test/java/org/apache/qpid/systest/rest/acl/VirtualHostAccessControlProviderRestTest.java
+++ /dev/null
@@ -1,287 +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.systest.rest.acl;
-
-
-
-import static org.apache.qpid.server.security.access.plugins.RuleOutcome.*;
-import static org.apache.qpid.server.security.access.config.LegacyOperation.*;
-import static org.apache.qpid.server.security.access.config.ObjectType.*;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.qpid.server.model.ConfiguredObject;
-import org.apache.qpid.server.model.Queue;
-import org.apache.qpid.server.model.VirtualHostAccessControlProvider;
-import org.apache.qpid.server.security.access.config.LegacyOperation;
-import org.apache.qpid.server.security.access.config.ObjectProperties;
-import org.apache.qpid.server.security.access.config.ObjectType;
-import org.apache.qpid.server.security.access.plugins.AclRule;
-import org.apache.qpid.server.security.access.plugins.RuleBasedVirtualHostAccessControlProvider;
-import org.apache.qpid.server.security.access.plugins.RuleOutcome;
-import org.apache.qpid.systest.rest.QpidRestTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-
-public class VirtualHostAccessControlProviderRestTest extends QpidRestTestCase
-{
- private static final String ADMIN = "admin";
-
- private static final String USER1 = "user1";
- private static final String USER2 = "user2";
- private static final String USER3 = "user3";
- private static final String USER4 = "user4";
- private static final String USER5 = "user5";
- private static final String USER6 = "user6";
-
-
- private String _queueUrl;
- private String _queueName;
- private String _virtualHostRuleProviderUrl;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- _queueName = getTestName();
- _queueUrl = "queue/test/test/" + _queueName;
- _virtualHostRuleProviderUrl = VirtualHostAccessControlProvider.class.getSimpleName().toLowerCase() + "/test/test/rules";
-
- getRestTestHelper().setUsernameAndPassword(ADMIN, ADMIN);
- final Map<String, Object> attributes = new HashMap<>();
- attributes.put(ConfiguredObject.NAME, "rules");
- attributes.put(ConfiguredObject.TYPE, RuleBasedVirtualHostAccessControlProvider.RULE_BASED_TYPE);
- final AclRule[] rules = {
- new TestAclRule(USER1, ObjectType.QUEUE, CREATE, DENY_LOG),
- new TestAclRule(USER3, ObjectType.QUEUE, CREATE, ALLOW_LOG),
- new TestAclRule(USER4, ObjectType.QUEUE, CREATE, ALLOW_LOG),
-
- new TestAclRule(USER1, ObjectType.QUEUE, UPDATE, DENY_LOG),
- new TestAclRule(USER3, ObjectType.QUEUE, UPDATE, ALLOW_LOG),
- new TestAclRule(USER4, ObjectType.QUEUE, UPDATE, ALLOW_LOG),
-
- new TestAclRule(USER1, ObjectType.QUEUE, DELETE, DENY_LOG),
- new TestAclRule(USER3, ObjectType.QUEUE, DELETE, ALLOW_LOG),
- new TestAclRule(USER4, ObjectType.QUEUE, DELETE, ALLOW_LOG),
-
- };
- attributes.put(RuleBasedVirtualHostAccessControlProvider.RULES, rules);
- getRestTestHelper().submitRequest(_virtualHostRuleProviderUrl, "PUT", attributes);
-
- }
-
- @Override
- protected void customizeConfiguration() throws Exception
- {
- super.customizeConfiguration();
- final TestBrokerConfiguration defaultBrokerConfiguration = getDefaultBrokerConfiguration();
- defaultBrokerConfiguration.configureTemporaryPasswordFile(ADMIN, USER1, USER2, USER3, USER4, USER5, USER6);
- final AclRule[] rules = {
- new TestAclRule(ADMIN, ObjectType.ALL, LegacyOperation.ALL, ALLOW_LOG),
-
- new TestAclRule("ALL", MANAGEMENT, ACCESS, ALLOW_LOG),
- new TestAclRule(USER1, ObjectType.QUEUE, CREATE, ALLOW_LOG),
- new TestAclRule(USER2, ObjectType.QUEUE, CREATE, DENY_LOG),
- new TestAclRule(USER3, ObjectType.QUEUE, CREATE, DENY_LOG),
- new TestAclRule(USER5, ObjectType.QUEUE, CREATE, ALLOW_LOG),
-
- new TestAclRule(USER1, ObjectType.QUEUE, UPDATE, ALLOW_LOG),
- new TestAclRule(USER2, ObjectType.QUEUE, UPDATE, DENY_LOG),
- new TestAclRule(USER3, ObjectType.QUEUE, UPDATE, DENY_LOG),
- new TestAclRule(USER5, ObjectType.QUEUE, UPDATE, ALLOW_LOG),
-
- new TestAclRule(USER1, ObjectType.QUEUE, DELETE, ALLOW_LOG),
- new TestAclRule(USER2, ObjectType.QUEUE, DELETE, DENY_LOG),
- new TestAclRule(USER3, ObjectType.QUEUE, DELETE, DENY_LOG),
- new TestAclRule(USER5, ObjectType.QUEUE, DELETE, ALLOW_LOG)
-
- };
- defaultBrokerConfiguration.addAclRuleConfiguration(rules);
-
- }
-
- public void testCreateAndDeleteQueueAllowedFromBrokerRule() throws Exception
- {
- assertCreateAndDeleteQueueSucceeds(USER5);
- }
-
- public void testCreateDeleteQueueAllowedFromVirtualHostRule() throws Exception
- {
- assertCreateAndDeleteQueueSucceeds(USER4);
- }
-
- public void testCreateDeleteQueueAllowedFromVirtualHostOverridingBrokerRule() throws Exception
- {
- assertCreateAndDeleteQueueSucceeds(USER3);
- }
-
- public void testCreateQueueDeniedFromVirtualHostRule() throws Exception
- {
- assertCreateQueueDenied(USER1);
- }
-
- public void testCreateQueueDeniedFromBrokerRule() throws Exception
- {
- assertCreateQueueDenied(USER2);
- }
-
-
- public void testCreateQueueDeniedFromDefault() throws Exception
- {
- assertCreateQueueDenied(USER6);
- }
-
- @SuppressWarnings("unchecked")
- public void testUpdateVirtualHostRule() throws Exception
- {
- // Denied by virtualhost rule
- assertCreateQueueDenied(USER1);
-
- Map<String, Object> providerDetails = getRestTestHelper().getJsonAsMap(_virtualHostRuleProviderUrl);
-
- List<Map<String, Object>> currentRules = ((List<Map<String, Object>>) providerDetails.get(RuleBasedVirtualHostAccessControlProvider.RULES));
-
- List<Map<String, Object>> filteredRulesWithoutUser1 = currentRules.stream()
- .filter(rule ->
- !rule.get("identity").equals(USER1))
- .collect(Collectors.toList());
-
- Map<String, Object> update = Collections.singletonMap(RuleBasedVirtualHostAccessControlProvider.RULES, filteredRulesWithoutUser1);
- getRestTestHelper().setUsernameAndPassword(ADMIN, ADMIN);
- getRestTestHelper().submitRequest(_virtualHostRuleProviderUrl, "PUT", update, HttpServletResponse.SC_OK);
-
- // Now allowed by the rule at the broker
- assertCreateQueueAllowed(USER1);
- }
-
- private void assertCreateAndDeleteQueueSucceeds(final String username) throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(username, username);
-
- int responseCode = createQueue();
- assertEquals("Queue creation should be allowed", HttpServletResponse.SC_CREATED, responseCode);
-
- assertQueueExists();
-
- responseCode = getRestTestHelper().submitRequest(_queueUrl, "DELETE");
- assertEquals("Queue deletion should be allowed", HttpServletResponse.SC_OK, responseCode);
-
- assertQueueDoesNotExist();
- }
-
-
-
- private void assertCreateQueueDenied(String username) throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(username, username);
-
- int responseCode = createQueue();
- assertEquals("Queue creation should be denied", HttpServletResponse.SC_FORBIDDEN, responseCode);
-
- assertQueueDoesNotExist();
- }
-
- private void assertCreateQueueAllowed(String username) throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(username, username);
-
- int responseCode = createQueue();
- assertEquals("Queue creation should be allowed", HttpServletResponse.SC_CREATED, responseCode);
- }
-
- private int createQueue() throws Exception
- {
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(Queue.NAME, _queueName);
-
- return getRestTestHelper().submitRequest(_queueUrl, "PUT", attributes);
- }
-
- private void assertQueueDoesNotExist() throws Exception
- {
- assertQueueExistence(false);
- }
-
- private void assertQueueExists() throws Exception
- {
- assertQueueExistence(true);
- }
-
- private void assertQueueExistence(boolean exists) throws Exception
- {
- int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND;
- getRestTestHelper().submitRequest(_queueUrl, "GET", expectedResponseCode);
- }
-
- public static class TestAclRule implements AclRule
- {
- private String _identity;
- private ObjectType _objectType;
- private LegacyOperation _operation;
- private RuleOutcome _outcome;
-
- TestAclRule(final String identity,
- final ObjectType objectType,
- final LegacyOperation operation,
- final RuleOutcome outcome)
- {
- _identity = identity;
- _objectType = objectType;
- _operation = operation;
- _outcome = outcome;
- }
-
- @Override
- public String getIdentity()
- {
- return _identity;
- }
-
- @Override
- public ObjectType getObjectType()
- {
- return _objectType;
- }
-
- @Override
- public LegacyOperation getOperation()
- {
- return _operation;
- }
-
- @Override
- public Map<ObjectProperties.Property, String> getAttributes()
- {
- return Collections.emptyMap();
- }
-
- @Override
- public RuleOutcome getOutcome()
- {
- return _outcome;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/test/java/org/apache/qpid/systest/rest/acl/VirtualHostNodeACLTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/systest/rest/acl/VirtualHostNodeACLTest.java b/systests/src/test/java/org/apache/qpid/systest/rest/acl/VirtualHostNodeACLTest.java
deleted file mode 100644
index 859c263..0000000
--- a/systests/src/test/java/org/apache/qpid/systest/rest/acl/VirtualHostNodeACLTest.java
+++ /dev/null
@@ -1,125 +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.systest.rest.acl;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.qpid.server.model.VirtualHostNode;
-import org.apache.qpid.server.virtualhostnode.JsonVirtualHostNode;
-import org.apache.qpid.systest.rest.QpidRestTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-import org.apache.qpid.test.utils.TestUtils;
-
-public class VirtualHostNodeACLTest extends QpidRestTestCase
-{
- private static final String TEST_VIRTUAL_HOST_NODE = "myTestVirtualHostNode";
- private static final String ALLOWED_USER = "user1";
- private static final String DENIED_USER = "user2";
-
- @Override
- protected void customizeConfiguration() throws Exception
- {
- super.customizeConfiguration();
- final TestBrokerConfiguration defaultBrokerConfiguration = getDefaultBrokerConfiguration();
- defaultBrokerConfiguration.configureTemporaryPasswordFile(ALLOWED_USER, DENIED_USER);
-
- TestUtils.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT",
- "ACL ALLOW-LOG " + ALLOWED_USER + " ALL VIRTUALHOSTNODE",
- "ACL DENY-LOG " + DENIED_USER + " ALL VIRTUALHOSTNODE",
- "ACL DENY-LOG ALL ALL");
-
- Map<String, Object> virtualHostNodeAttributes = new HashMap<>();
- virtualHostNodeAttributes.put(VirtualHostNode.NAME, TEST_VIRTUAL_HOST_NODE);
- virtualHostNodeAttributes.put(VirtualHostNode.TYPE, getTestProfileVirtualHostNodeType());
- // TODO need better way to determine the VHN's optional attributes
- virtualHostNodeAttributes.put(JsonVirtualHostNode.STORE_PATH, getStoreLocation(TEST_VIRTUAL_HOST_NODE));
-
- defaultBrokerConfiguration.addObjectConfiguration(VirtualHostNode.class, virtualHostNodeAttributes);
- }
-
- public void testCreateVirtualHostNodeAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String hostName = getTestName();
-
- int responseCode = createVirtualHostNode(hostName);
- assertEquals("Virtual host node creation should be allowed", HttpServletResponse.SC_CREATED, responseCode);
-
- assertVirtualHostNodeExists(hostName);
- }
-
- public void testCreateVirtualHostNodeDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- String hostName = getTestName();
-
- int responseCode = createVirtualHostNode(hostName);
- assertEquals("Virtual host node creation should be denied", HttpServletResponse.SC_FORBIDDEN, responseCode);
-
- assertVirtualHostNodeDoesNotExist(hostName);
- }
-
- public void testDeleteVirtualHostNodeDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- getRestTestHelper().submitRequest("virtualhostnode/" + TEST_VIRTUAL_HOST_NODE, "DELETE", HttpServletResponse.SC_FORBIDDEN);
-
- assertVirtualHostNodeExists(TEST_VIRTUAL_HOST_NODE);
- }
-
- /* === Utility Methods === */
-
- private int createVirtualHostNode(String virtualHostNodeName) throws Exception
- {
- Map<String, Object> data = new HashMap<>();
- data.put(VirtualHostNode.NAME, virtualHostNodeName);
- data.put(VirtualHostNode.TYPE, getTestProfileVirtualHostNodeType());
- data.put(JsonVirtualHostNode.STORE_PATH, getStoreLocation(virtualHostNodeName));
-
- return getRestTestHelper().submitRequest("virtualhostnode/" + virtualHostNodeName, "PUT", data);
- }
-
- private void assertVirtualHostNodeDoesNotExist(String name) throws Exception
- {
- assertVirtualHostNodeExistence(name, false);
- }
-
- private void assertVirtualHostNodeExists(String name) throws Exception
- {
- assertVirtualHostNodeExistence(name, true);
- }
-
- private void assertVirtualHostNodeExistence(String name, boolean exists) throws Exception
- {
- int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND;
- getRestTestHelper().submitRequest("virtualhostnode/" + name, "GET", expectedResponseCode);
- }
-
- private String getStoreLocation(String hostName)
- {
- return new File(TMP_FOLDER, "store-" + hostName + "-" + System.currentTimeMillis()).getAbsolutePath();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/test/java/org/apache/qpid/test/utils/BrokerCommandHelperTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/test/utils/BrokerCommandHelperTest.java b/systests/src/test/java/org/apache/qpid/test/utils/BrokerCommandHelperTest.java
deleted file mode 100644
index 793da66..0000000
--- a/systests/src/test/java/org/apache/qpid/test/utils/BrokerCommandHelperTest.java
+++ /dev/null
@@ -1,57 +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.utils;
-
-import java.io.File;
-
-public class BrokerCommandHelperTest extends QpidTestCase
-{
- private static final String PATH_TO_QPID_EXECUTABLE = "/path / to (/qpid";
- private static final String ARGUMENT_WITH_SPACES = " blah / blah /blah";
- private static final String ARGUMENT_PORT = "-p";
- private static final String ARGUMENT_PORT_VALUE = "@PORT";
- private static final String ARGUMENT_STORE_PATH = "-sp";
- private static final String ARGUMENT_STORE_PATH_VALUE = "@STORE_PATH";
- private static final String ARGUMENT_STORE_TYPE = "-st";
- private static final String ARGUMENT_STORE_TYPE_VALUE = "@STORE_TYPE";
-
- private BrokerCommandHelper _brokerCommandHelper;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- _brokerCommandHelper = new BrokerCommandHelper("\"" + PATH_TO_QPID_EXECUTABLE + "\" " + ARGUMENT_PORT + " "
- + ARGUMENT_PORT_VALUE + " " + ARGUMENT_STORE_PATH + " " + ARGUMENT_STORE_PATH_VALUE + " " + ARGUMENT_STORE_TYPE
- + " " + ARGUMENT_STORE_TYPE_VALUE + " '" + ARGUMENT_WITH_SPACES
- + "'");
- }
-
- public void testGetBrokerCommand()
- {
- String[] brokerCommand = _brokerCommandHelper.getBrokerCommand(1, TMP_FOLDER + File.separator + "work-dir", "path to config file", "json");
-
- String[] expected = { PATH_TO_QPID_EXECUTABLE, ARGUMENT_PORT, "1", ARGUMENT_STORE_PATH, "path to config file",
- ARGUMENT_STORE_TYPE, "json", ARGUMENT_WITH_SPACES };
- assertEquals("Unexpected broker command", expected.length, brokerCommand.length);
- for (int i = 0; i < expected.length; i++)
- {
- assertEquals("Unexpected command part value at " + i,expected[i], brokerCommand[i] );
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/test/java/org/apache/qpid/test/utils/SpawnedBrokerHolderTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/test/utils/SpawnedBrokerHolderTest.java b/systests/src/test/java/org/apache/qpid/test/utils/SpawnedBrokerHolderTest.java
deleted file mode 100644
index 237f9a4..0000000
--- a/systests/src/test/java/org/apache/qpid/test/utils/SpawnedBrokerHolderTest.java
+++ /dev/null
@@ -1,38 +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.utils;
-
-public class SpawnedBrokerHolderTest extends QpidBrokerTestCase
-{
- @Override
- public void startDefaultBroker() throws Exception
- {
- // Don't start default broker
- }
-
- public void testRestartOnSamePort() throws Exception
- {
- BrokerHolder broker = createSpawnedBroker();
- broker.start();
- int port = broker.getAmqpPort();
- broker.restart();
- assertEquals("broker not restarted on same port", port, broker.getAmqpPort());
- }
-}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org
[5/8] qpid-broker-j git commit: QPID-8123: [Broker-J] [BDB System
Tests] Refactor MultiNodeTest and TwoNodeTest to remove knowledge of Qpid JMS
AMQP 0-x client (code dependency and format of failover url).
Posted by kw...@apache.org.
QPID-8123: [Broker-J] [BDB System Tests] Refactor MultiNodeTest and TwoNodeTest to remove knowledge of Qpid JMS AMQP 0-x client (code dependency and format of failover url).
Project: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/commit/c09a9a31
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/c09a9a31
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/c09a9a31
Branch: refs/heads/master
Commit: c09a9a316fdadcf3b8af21661fbc5ccb3e1baa0a
Parents: 7ce5480
Author: Keith Wall <kw...@apache.org>
Authored: Sat Mar 10 00:04:37 2018 +0000
Committer: Keith Wall <kw...@apache.org>
Committed: Mon Mar 12 16:24:17 2018 +0000
----------------------------------------------------------------------
.../berkeleydb/replication/GroupCreator.java | 62 ++-
.../berkeleydb/replication/MultiNodeTest.java | 426 +++++++++----------
.../berkeleydb/replication/TwoNodeTest.java | 78 +++-
.../apache/qpid/systests/ConnectionBuilder.java | 8 +-
.../systests/GenericConnectionListener.java | 29 ++
.../org/apache/qpid/systests/JmsProvider.java | 5 +
.../QpidJmsClient0xConnectionBuilder.java | 141 +++---
.../qpid/systests/QpidJmsClient0xProvider.java | 75 +++-
.../QpidJmsClientConnectionBuilder.java | 64 ++-
.../qpid/systests/QpidJmsClientProvider.java | 64 +++
.../qpid/test/utils/QpidBrokerTestCase.java | 8 +-
test-profiles/CPPExcludes | 2 -
test-profiles/Java010Excludes | 2 -
test-profiles/Java10Excludes | 10 -
14 files changed, 628 insertions(+), 346 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c09a9a31/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupCreator.java
----------------------------------------------------------------------
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupCreator.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupCreator.java
index 357c28d..2cc5484 100644
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupCreator.java
+++ b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupCreator.java
@@ -50,8 +50,8 @@ import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.server.model.Port;
+import org.apache.qpid.server.model.Protocol;
import org.apache.qpid.server.model.VirtualHost;
import org.apache.qpid.server.model.VirtualHostNode;
import org.apache.qpid.server.virtualhost.berkeleydb.BDBHAVirtualHostImpl;
@@ -60,20 +60,18 @@ import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBHARemoteReplicationN
import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBHAVirtualHostNode;
import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBHAVirtualHostNodeImpl;
import org.apache.qpid.systest.rest.RestTestHelper;
+import org.apache.qpid.systests.ConnectionBuilder;
import org.apache.qpid.test.utils.BrokerHolder;
import org.apache.qpid.test.utils.QpidBrokerTestCase;
import org.apache.qpid.test.utils.TestBrokerConfiguration;
public class GroupCreator
{
- protected static final Logger LOGGER = LoggerFactory.getLogger(GroupCreator.class);
-
- private static final String MANY_BROKER_URL_FORMAT = "amqp://guest:guest@/%s?brokerlist='%s'&failover='roundrobin?cyclecount='%d''";
- private static final String BROKER_PORTION_FORMAT = "tcp://localhost:%d?connectdelay='%d',retries='%d'";
+ private static final Logger LOGGER = LoggerFactory.getLogger(GroupCreator.class);
private static final int FAILOVER_CYCLECOUNT = 40;
private static final int FAILOVER_RETRIES = 0;
- private static final int FAILOVER_CONNECTDELAY = 250;
+ private static final int FAILOVER_CONNECTDELAY = 1000;
private final QpidBrokerTestCase _testcase;
private final String _virtualHostName;
@@ -258,8 +256,7 @@ public class GroupCreator
public int getBrokerPortNumberFromConnection(Connection connection)
{
- final AMQConnection amqConnection = (AMQConnection)connection;
- return amqConnection.getActiveBrokerDetails().getPort();
+ return _testcase.getJmsProvider().getConnectedURI(connection).getPort();
}
public int getPortNumberOfAnInactiveBroker(final Connection activeConnection)
@@ -282,27 +279,43 @@ public class GroupCreator
return ports;
}
- public String getConnectionUrlForAllClusterNodes() throws Exception
+ public ConnectionBuilder getConnectionBuilderForAllClusterNodes() throws Exception
{
- return getConnectionUrlForAllClusterNodes(FAILOVER_CONNECTDELAY, FAILOVER_RETRIES, FAILOVER_CYCLECOUNT);
+ return getConnectionBuilderForAllClusterNodes(FAILOVER_CONNECTDELAY, FAILOVER_RETRIES, FAILOVER_CYCLECOUNT);
}
- public String getConnectionUrlForAllClusterNodes(int connectDelay, int retries, final int cyclecount) throws Exception
+ public ConnectionBuilder getConnectionBuilderForAllClusterNodes(int connectDelay, int retries, final int cyclecount) throws Exception
{
- final StringBuilder brokerList = new StringBuilder();
+ final ConnectionBuilder connectionBuilder = _testcase.getConnectionBuilder();
+ connectionBuilder.setFailoverReconnectDelay(connectDelay);
+ connectionBuilder.setVirtualHost(_virtualHostName);
+ connectionBuilder.setFailover(true);
+
+ final int reconnectAttempts = (retries == 0 ? 1 : retries) * (cyclecount == 0 ? 1 : cyclecount);
+ connectionBuilder.setFailoverReconnectAttempts(reconnectAttempts);
- for(Iterator<Integer> itr = _members.keySet().iterator(); itr.hasNext(); )
+ final Iterator<Integer> iterator = _members.keySet().iterator();
+ if (iterator.hasNext())
{
- int brokerPortNumber = itr.next();
+ final int firstBroker = iterator.next();
+ connectionBuilder.setPort(firstBroker);
+ }
- brokerList.append(String.format(BROKER_PORTION_FORMAT, brokerPortNumber, connectDelay, retries));
- if (itr.hasNext())
- {
- brokerList.append(";");
- }
+ while (iterator.hasNext())
+ {
+ int brokerPortNumber = iterator.next();
+ connectionBuilder.addFailoverPort(brokerPortNumber);
+ }
+
+ if (_testcase.getBrokerProtocol().equals(Protocol.AMQP_1_0))
+ {
+ connectionBuilder.setOptions(Collections.singletonMap("failover.warnAfterReconnectAttempts", "1"));
+ // TODO - workaround for the fact that the client does not respect reconnectDelay if the
+ // server closes the connection gracefully.
+ connectionBuilder.setOptions(Collections.singletonMap("failover.initialReconnectDelay", "15000"));
}
- return String.format(MANY_BROKER_URL_FORMAT, _virtualHostName, brokerList, cyclecount);
+ return connectionBuilder;
}
public String getGroupName()
@@ -453,8 +466,13 @@ public class GroupCreator
Thread.sleep(1000);
}
}
- LOGGER.debug("Node '" + getNodeNameForBrokerPort(remoteNodePort) + "' attribute '" + attributeName + "' is " + attributeValue);
- Assert.assertTrue("Unexpected " + attributeName + " at " + localNodePort, desiredValues.contains(attributeValue));
+ LOGGER.debug("Node '{}' attribute '{}' value '{}'", getNodeNameForBrokerPort(remoteNodePort), attributeName, attributeValue);
+ Assert.assertTrue(String.format("Node port %d: Attribute '%s' has unexpected value '%s', desired values [%s]",
+ localNodePort,
+ attributeName,
+ attributeValue,
+ desiredValues),
+ desiredValues.contains(attributeValue));
}
public RestTestHelper createRestTestHelper(int brokerPort)
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c09a9a31/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/MultiNodeTest.java
----------------------------------------------------------------------
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/MultiNodeTest.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/MultiNodeTest.java
index f86f467..d541e1a 100644
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/MultiNodeTest.java
+++ b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/MultiNodeTest.java
@@ -20,6 +20,7 @@
package org.apache.qpid.server.store.berkeleydb.replication;
import java.io.File;
+import java.net.URI;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
@@ -38,7 +39,6 @@ import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
@@ -51,33 +51,35 @@ import com.sleepycat.je.rep.ReplicationConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.jms.ConnectionListener;
import org.apache.qpid.server.model.Broker;
+import org.apache.qpid.server.model.Protocol;
import org.apache.qpid.server.model.State;
+import org.apache.qpid.server.util.FileUtils;
import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBHARemoteReplicationNode;
import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBHAVirtualHostNode;
import org.apache.qpid.server.virtualhostnode.berkeleydb.NodeRole;
+import org.apache.qpid.systests.ConnectionBuilder;
+import org.apache.qpid.systests.GenericConnectionListener;
import org.apache.qpid.test.utils.QpidBrokerTestCase;
import org.apache.qpid.test.utils.TestUtils;
-import org.apache.qpid.util.FileUtils;
public class MultiNodeTest extends QpidBrokerTestCase
{
- protected static final Logger LOGGER = LoggerFactory.getLogger(MultiNodeTest.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(MultiNodeTest.class);
private static final String VIRTUAL_HOST = "test";
private static final int NUMBER_OF_NODES = 3;
+ private static final int FAILOVER_COMPLETION_TIMEOUT = 60000;
private GroupCreator _groupCreator;
private FailoverAwaitingListener _failoverListener;
/** Used when expectation is client will (re)-connect */
- private String _positiveFailoverUrl;
+ private ConnectionBuilder _positiveFailoverBuilder;
/** Used when expectation is client will not (re)-connect */
- private String _negativeFailoverUrl;
+ private ConnectionBuilder _negativeFailoverBuilder;
@Override
protected void setUp() throws Exception
@@ -88,8 +90,8 @@ public class MultiNodeTest extends QpidBrokerTestCase
_groupCreator = new GroupCreator(this, VIRTUAL_HOST, NUMBER_OF_NODES);
_groupCreator.configureClusterNodes();
- _positiveFailoverUrl = _groupCreator.getConnectionUrlForAllClusterNodes();
- _negativeFailoverUrl = _groupCreator.getConnectionUrlForAllClusterNodes(200, 0, 2);
+ _positiveFailoverBuilder = _groupCreator.getConnectionBuilderForAllClusterNodes();
+ _negativeFailoverBuilder = _groupCreator.getConnectionBuilderForAllClusterNodes(200, 0, 2);
_groupCreator.startCluster();
_failoverListener = new FailoverAwaitingListener();
@@ -105,16 +107,15 @@ public class MultiNodeTest extends QpidBrokerTestCase
public void testLossOfMasterNodeCausesClientToFailover() throws Exception
{
- final Connection connection = getConnection(_positiveFailoverUrl);
-
- ((AMQConnection)connection).setConnectionListener(_failoverListener);
+ final Connection connection = _positiveFailoverBuilder.build();
+ getJmsProvider().addGenericConnectionListener(connection, _failoverListener);
final int activeBrokerPort = _groupCreator.getBrokerPortNumberFromConnection(connection);
- LOGGER.info("Active connection port " + activeBrokerPort);
+ LOGGER.info("Active connection port {}", activeBrokerPort);
_groupCreator.stopNode(activeBrokerPort);
LOGGER.info("Node is stopped");
- _failoverListener.awaitFailoverCompletion(20000);
+ _failoverListener.awaitFailoverCompletion(FAILOVER_COMPLETION_TIMEOUT);
LOGGER.info("Listener has finished");
// any op to ensure connection remains
connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -122,25 +123,36 @@ public class MultiNodeTest extends QpidBrokerTestCase
public void testLossOfReplicaNodeDoesNotCauseClientToFailover() throws Exception
{
- final Connection connection = getConnection(_positiveFailoverUrl);
+ final Connection connection = _positiveFailoverBuilder.build();
+ getJmsProvider().addGenericConnectionListener(connection, _failoverListener);
- ((AMQConnection)connection).setConnectionListener(_failoverListener);
final int activeBrokerPort = _groupCreator.getBrokerPortNumberFromConnection(connection);
- LOGGER.info("Active connection port " + activeBrokerPort);
- final int inactiveBrokerPort = _groupCreator.getPortNumberOfAnInactiveBroker(connection);
+ LOGGER.info("Active connection port {}", activeBrokerPort);
- LOGGER.info("Stopping inactive broker on port " + inactiveBrokerPort);
+ final int inactiveBrokerPort = _groupCreator.getPortNumberOfAnInactiveBroker(connection);
+ LOGGER.info("Stopping inactive broker on port {} ", inactiveBrokerPort);
_groupCreator.stopNode(inactiveBrokerPort);
_failoverListener.assertNoFailoverCompletionWithin(2000);
- assertProducingConsuming(connection);
+ // any op to ensure connection remains
+ connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
}
public void testLossOfQuorumCausesClientDisconnection() throws Exception
{
- final Connection connection = getConnection(_negativeFailoverUrl);
+ if (getBrokerProtocol().equals(Protocol.AMQP_1_0))
+ {
+ // TODO - there seems to be a client defect when a JMS operation is interrupted
+ // by a graceful connection close from the client side.
+ return;
+ }
+
+ final Connection connection = _negativeFailoverBuilder.build();
+ Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
+ Destination destination = session.createQueue(getTestQueueName());
+ getJmsProvider().createQueue(session, getTestQueueName());
Set<Integer> ports = _groupCreator.getBrokerPortNumbersForNodes();
@@ -155,10 +167,9 @@ public class MultiNodeTest extends QpidBrokerTestCase
try
{
- Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
- Destination destination = session.createQueue(getTestQueueName());
- session.createConsumer(destination).close();
- fail("Exception not thrown - creating durable queue should fail without quorum");
+
+ sendMessage(session, destination, 1);
+ fail("Exception not thrown - sending message within a transaction should fail without quorum");
}
catch(JMSException jms)
{
@@ -168,7 +179,7 @@ public class MultiNodeTest extends QpidBrokerTestCase
// New connections should now fail as vhost will be unavailable
try
{
- Connection unexpectedConnection = getConnection(_negativeFailoverUrl);
+ Connection unexpectedConnection = _negativeFailoverBuilder.build();
fail("Got unexpected connection to node in group without quorum " + unexpectedConnection);
}
catch (JMSException je)
@@ -184,9 +195,13 @@ public class MultiNodeTest extends QpidBrokerTestCase
*/
public void testQuorumLostAndRestored_OriginalMasterRejoinsTheGroup() throws Exception
{
- final Connection connection = getConnection(_positiveFailoverUrl);
+ final Connection connection = _positiveFailoverBuilder.build();
+ getJmsProvider().addGenericConnectionListener(connection, _failoverListener);
- ((AMQConnection)connection).setConnectionListener(_failoverListener);
+ Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
+ getJmsProvider().createQueue(session, getTestQueueName());
+ Destination dest = session.createQueue(getTestQueueName());
+ session.close();
Set<Integer> ports = _groupCreator.getBrokerPortNumbersForNodes();
@@ -196,7 +211,6 @@ public class MultiNodeTest extends QpidBrokerTestCase
Session session1 = connection.createSession(true, Session.SESSION_TRANSACTED);
Session session2 = connection.createSession(true, Session.SESSION_TRANSACTED);
- Destination dest = session1.createQueue(getTestQueueName());
session1.createConsumer(dest).close();
MessageProducer producer1 = session1.createProducer(dest);
@@ -221,32 +235,34 @@ public class MultiNodeTest extends QpidBrokerTestCase
_groupCreator.startNode(p);
}
- _failoverListener.awaitFailoverCompletion(20000);
+ _failoverListener.awaitFailoverCompletion(FAILOVER_COMPLETION_TIMEOUT);
_groupCreator.awaitNodeToAttainRole(activeBrokerPort, "MASTER", "REPLICA");
}
public void testPersistentMessagesAvailableAfterFailover() throws Exception
{
- final Connection connection = getConnection(_positiveFailoverUrl);
+ final Connection connection = _positiveFailoverBuilder.build();
+ getJmsProvider().addGenericConnectionListener(connection, _failoverListener);
- ((AMQConnection)connection).setConnectionListener(_failoverListener);
+ Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
+ getJmsProvider().createQueue(session, getTestQueueName());
+ Destination queue = session.createQueue(getTestQueueName());
+ session.close();
final int activeBrokerPort = _groupCreator.getBrokerPortNumberFromConnection(connection);
Session producingSession = connection.createSession(true, Session.SESSION_TRANSACTED);
- Destination queue = producingSession.createQueue(getTestQueueName());
- producingSession.createConsumer(queue).close();
sendMessage(producingSession, queue, 10);
_groupCreator.stopNode(activeBrokerPort);
- LOGGER.info("Old master (broker port " + activeBrokerPort + ") is stopped");
+ LOGGER.info("Old master (broker port {}) is stopped", activeBrokerPort);
- _failoverListener.awaitFailoverCompletion(20000);
+ _failoverListener.awaitFailoverCompletion(FAILOVER_COMPLETION_TIMEOUT);
LOGGER.info("Failover has finished");
final int activeBrokerPortAfterFailover = _groupCreator.getBrokerPortNumberFromConnection(connection);
- LOGGER.info("New master (broker port " + activeBrokerPort + ") after failover");
+ LOGGER.info("New master (broker port {}) after failover", activeBrokerPortAfterFailover);
Session consumingSession = connection.createSession(true, Session.SESSION_TRANSACTED);
MessageConsumer consumer = consumingSession.createConsumer(queue);
@@ -254,7 +270,7 @@ public class MultiNodeTest extends QpidBrokerTestCase
connection.start();
for(int i = 0; i < 10; i++)
{
- Message m = consumer.receive(RECEIVE_TIMEOUT);
+ Message m = consumer.receive(getReceiveTimeout());
assertNotNull("Message " + i + " is not received", m);
assertEquals("Unexpected message received", i, m.getIntProperty(INDEX));
}
@@ -263,13 +279,17 @@ public class MultiNodeTest extends QpidBrokerTestCase
public void testTransferMasterFromLocalNode() throws Exception
{
- final Connection connection = getConnection(_positiveFailoverUrl);
+ final Connection connection = _positiveFailoverBuilder.build();
+
+ Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
+ getJmsProvider().createQueue(session, getTestQueueName());
+ session.close();
final int activeBrokerPort = _groupCreator.getBrokerPortNumberFromConnection(connection);
- LOGGER.info("Active connection port " + activeBrokerPort);
+ LOGGER.info("Active connection port {}", activeBrokerPort);
final int inactiveBrokerPort = _groupCreator.getPortNumberOfAnInactiveBroker(connection);
- LOGGER.info("Update role attribute on inactive broker on port " + inactiveBrokerPort);
+ LOGGER.info("Update role attribute on inactive broker on port {}", inactiveBrokerPort);
// transfer mastership 3 times in order to verify
// that repeated mastership transfer to the same node works, See QPID-6996
@@ -283,14 +303,13 @@ public class MultiNodeTest extends QpidBrokerTestCase
final int activeBrokerPort) throws Exception
{
_failoverListener = new FailoverAwaitingListener();
- ((AMQConnection)connection).setConnectionListener(_failoverListener);
+ getJmsProvider().addGenericConnectionListener(connection, _failoverListener);
Map<String, Object> attributes = _groupCreator.getNodeAttributes(inactiveBrokerPort);
assertEquals("Inactive broker has unexpected role", "REPLICA", attributes.get(BDBHAVirtualHostNode.ROLE));
- _groupCreator.setNodeAttributes(inactiveBrokerPort,
- Collections.<String, Object>singletonMap(BDBHAVirtualHostNode.ROLE, "MASTER"));
+ _groupCreator.setNodeAttributes(inactiveBrokerPort, Collections.singletonMap(BDBHAVirtualHostNode.ROLE, "MASTER"));
- _failoverListener.awaitFailoverCompletion(20000);
+ _failoverListener.awaitFailoverCompletion(FAILOVER_COMPLETION_TIMEOUT);
LOGGER.info("Listener has finished");
attributes = _groupCreator.getNodeAttributes(inactiveBrokerPort);
@@ -303,15 +322,17 @@ public class MultiNodeTest extends QpidBrokerTestCase
public void testTransferMasterFromRemoteNode() throws Exception
{
- final Connection connection = getConnection(_positiveFailoverUrl);
+ final Connection connection = _positiveFailoverBuilder.build();
- ((AMQConnection)connection).setConnectionListener(_failoverListener);
+ Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
+ getJmsProvider().createQueue(session, getTestQueueName());
+ session.close();
final int activeBrokerPort = _groupCreator.getBrokerPortNumberFromConnection(connection);
- LOGGER.info("Active connection port " + activeBrokerPort);
+ LOGGER.info("Active connection port {}", activeBrokerPort);
final int inactiveBrokerPort = _groupCreator.getPortNumberOfAnInactiveBroker(connection);
- LOGGER.info("Update role attribute on inactive broker on port " + inactiveBrokerPort);
+ LOGGER.info("Update role attribute on inactive broker on port {}", inactiveBrokerPort);
// transfer mastership 3 times in order to verify
// that repeated mastership transfer to the same node works, See QPID-6996
@@ -325,15 +346,15 @@ public class MultiNodeTest extends QpidBrokerTestCase
final int inactiveBrokerPort) throws Exception
{
_failoverListener = new FailoverAwaitingListener();
- ((AMQConnection)connection).setConnectionListener(_failoverListener);
+ getJmsProvider().addGenericConnectionListener(connection, _failoverListener);
_groupCreator.awaitNodeToAttainRole(activeBrokerPort, inactiveBrokerPort, "REPLICA");
Map<String, Object> attributes = _groupCreator.getNodeAttributes(activeBrokerPort, inactiveBrokerPort);
assertEquals("Inactive broker has unexpected role", "REPLICA", attributes.get(BDBHAVirtualHostNode.ROLE));
- _groupCreator.setNodeAttributes(activeBrokerPort, inactiveBrokerPort, Collections.<String, Object>singletonMap(BDBHAVirtualHostNode.ROLE, "MASTER"));
+ _groupCreator.setNodeAttributes(activeBrokerPort, inactiveBrokerPort, Collections.singletonMap(BDBHAVirtualHostNode.ROLE, "MASTER"));
- _failoverListener.awaitFailoverCompletion(20000);
+ _failoverListener.awaitFailoverCompletion(FAILOVER_COMPLETION_TIMEOUT);
LOGGER.info("Listener has finished");
attributes = _groupCreator.getNodeAttributes(inactiveBrokerPort);
@@ -346,12 +367,11 @@ public class MultiNodeTest extends QpidBrokerTestCase
public void testTransferMasterWhilstMessagesInFlight() throws Exception
{
- final Connection connection = getConnection(_positiveFailoverUrl);
- ((AMQConnection) connection).setConnectionListener(_failoverListener);
-
- final Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
+ final Connection connection = _positiveFailoverBuilder.build();
+ getJmsProvider().addGenericConnectionListener(connection, _failoverListener);
+ Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
+ getJmsProvider().createQueue(session, getTestQueueName());
final Destination destination = session.createQueue(getTestQueueName());
- session.createConsumer(destination).close();
final AtomicBoolean masterTransferred = new AtomicBoolean(false);
final AtomicBoolean keepRunning = new AtomicBoolean(true);
@@ -360,58 +380,52 @@ public class MultiNodeTest extends QpidBrokerTestCase
final CountDownLatch producedOneAfter = new CountDownLatch(1);
final CountDownLatch workerShutdown = new CountDownLatch(1);
- Runnable producer = new Runnable()
- {
- @Override
- public void run()
+ Runnable producer = () -> {
+ try
{
- try
- {
- int count = 0;
- MessageProducer producer = session.createProducer(destination);
+ int count = 0;
+ MessageProducer producer1 = session.createProducer(destination);
- while (keepRunning.get())
+ while (keepRunning.get())
+ {
+ String messageText = "message" + count;
+ try
{
- String messageText = "message" + count;
- try
- {
- Message message = session.createTextMessage(messageText);
- producer.send(message);
- session.commit();
- LOGGER.debug("Sent message " + count);
+ Message message = session.createTextMessage(messageText);
+ producer1.send(message);
+ session.commit();
+ LOGGER.debug("Sent message " + count);
- producedOneBefore.countDown();
+ producedOneBefore.countDown();
- if (masterTransferred.get())
- {
- producedOneAfter.countDown();
- }
- count++;
- }
- catch (javax.jms.IllegalStateException ise)
- {
- throw ise;
- }
- catch (TransactionRolledBackException trbe)
- {
- // Pass - failover in prgoress
- }
- catch(JMSException je)
+ if (masterTransferred.get())
{
- // Pass - failover in progress
+ producedOneAfter.countDown();
}
+ count++;
+ }
+ catch (javax.jms.IllegalStateException ise)
+ {
+ throw ise;
+ }
+ catch (TransactionRolledBackException trbe)
+ {
+ // Pass - failover in prgoress
+ }
+ catch(JMSException je)
+ {
+ // Pass - failover in progress
}
- }
- catch (Exception e)
- {
- workerException.set(e);
- }
- finally
- {
- workerShutdown.countDown();
}
}
-
+ catch (Exception e)
+ {
+ workerException.set(e);
+ }
+ finally
+ {
+ workerShutdown.countDown();
+ }
};
Thread backgroundWorker = new Thread(producer);
@@ -421,18 +435,18 @@ public class MultiNodeTest extends QpidBrokerTestCase
assertTrue(workerRunning);
final int activeBrokerPort = _groupCreator.getBrokerPortNumberFromConnection(connection);
- LOGGER.info("Active connection port " + activeBrokerPort);
+ LOGGER.info("Active connection port {}", activeBrokerPort);
final int inactiveBrokerPort = _groupCreator.getPortNumberOfAnInactiveBroker(connection);
- LOGGER.info("Update role attribute on inactive broker on port " + inactiveBrokerPort);
+ LOGGER.info("Update role attribute on inactive broker on port {}", inactiveBrokerPort);
_groupCreator.awaitNodeToAttainRole(activeBrokerPort, inactiveBrokerPort, "REPLICA");
Map<String, Object> attributes = _groupCreator.getNodeAttributes(activeBrokerPort, inactiveBrokerPort);
assertEquals("Inactive broker has unexpected role", "REPLICA", attributes.get(BDBHAVirtualHostNode.ROLE));
- _groupCreator.setNodeAttributes(activeBrokerPort, inactiveBrokerPort, Collections.<String, Object>singletonMap(BDBHAVirtualHostNode.ROLE, "MASTER"));
+ _groupCreator.setNodeAttributes(activeBrokerPort, inactiveBrokerPort, Collections.singletonMap(BDBHAVirtualHostNode.ROLE, "MASTER"));
- _failoverListener.awaitFailoverCompletion(20000);
+ _failoverListener.awaitFailoverCompletion(FAILOVER_COMPLETION_TIMEOUT);
LOGGER.info("Failover has finished");
attributes = _groupCreator.getNodeAttributes(inactiveBrokerPort);
@@ -454,35 +468,39 @@ public class MultiNodeTest extends QpidBrokerTestCase
assertNull(workerException.get());
assertNotNull(session.createTemporaryQueue());
-
}
public void testInFlightTransactionsWhilstMajorityIsLost() throws Exception
{
+ if (getBrokerProtocol().equals(Protocol.AMQP_1_0))
+ {
+ // TODO - there seems to be a client defect when a JMS operation is interrupted
+ // by a graceful connection close from the client side.
+ return;
+ }
+
int connectionNumber = Integer.getInteger("MultiNodeTest.testInFlightTransactionsWhilstMajorityIsLost.numberOfConnections", 20);
- ExecutorService executorService = Executors.newFixedThreadPool(connectionNumber + NUMBER_OF_NODES -1);
+ ExecutorService executorService = Executors.newFixedThreadPool(connectionNumber + NUMBER_OF_NODES - 1);
try
{
- String connectionUrl = _groupCreator.getConnectionUrlForAllClusterNodes(100, 0, 100);
+ final ConnectionBuilder builder = _groupCreator.getConnectionBuilderForAllClusterNodes(100, 0, 100);
+ final Connection consumerConnection = builder.build();
+ Session s = consumerConnection.createSession(true, Session.SESSION_TRANSACTED);
+ getJmsProvider().createQueue(s, getTestQueueName());
+ s.close();
- final Connection consumerConnection = getConnection(connectionUrl);
consumerConnection.start();
final Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
final Destination destination = consumerSession.createQueue(getTestQueueName());
- consumerSession.createConsumer(destination).setMessageListener(new MessageListener()
- {
- @Override
- public void onMessage(final Message message)
+ consumerSession.createConsumer(destination).setMessageListener(message -> {
+ try
{
- try
- {
- LOGGER.info("Message received: " + ((TextMessage) message).getText());
- }
- catch (JMSException e)
- {
- LOGGER.error("Failure to get message text", e);
- }
+ LOGGER.info("Message received: " + ((TextMessage) message).getText());
+ }
+ catch (JMSException e)
+ {
+ LOGGER.error("Failure to get message text", e);
}
});
@@ -490,7 +508,7 @@ public class MultiNodeTest extends QpidBrokerTestCase
final Session[] sessions = new Session[connectionNumber];
for (int i = 0; i < sessions.length; i++)
{
- connections[i] = getConnection(connectionUrl);
+ connections[i] = builder.build();
sessions[i] = connections[i].createSession(true, Session.SESSION_TRANSACTED);
LOGGER.info("Session {} is created", i);
}
@@ -512,8 +530,8 @@ public class MultiNodeTest extends QpidBrokerTestCase
for (int i = 0; i < sessions.length; i++)
{
- AMQConnection connection = (AMQConnection)connections[i];
- connection.setConnectionListener(failoverListener);
+ Connection connection = connections[i];
+ getJmsProvider().addGenericConnectionListener(connection, failoverListener);
MessageProducer producer = sessions[i].createProducer(destination);
Message message = sessions[i].createTextMessage(messageText + "-" + i);
@@ -523,7 +541,7 @@ public class MultiNodeTest extends QpidBrokerTestCase
LOGGER.info("All publishing sessions have uncommitted transactions");
final int activeBrokerPort = _groupCreator.getBrokerPortNumberFromConnection(connections[0]);
- LOGGER.info("Active connection port " + activeBrokerPort);
+ LOGGER.info("Active connection port {}", activeBrokerPort);
List<Integer> inactivePorts = new ArrayList<>(ports);
inactivePorts.remove(new Integer(activeBrokerPort));
@@ -534,27 +552,22 @@ public class MultiNodeTest extends QpidBrokerTestCase
final int inactiveBrokerPort = port;
LOGGER.info("Stop node for inactive broker on port " + inactiveBrokerPort);
- executorService.submit(new Runnable()
- {
- @Override
- public void run()
+ executorService.submit(() -> {
+ try
{
- try
- {
- _groupCreator.setNodeAttributes(inactiveBrokerPort,
- inactiveBrokerPort,
- Collections.<String, Object>singletonMap(
- BDBHAVirtualHostNode.DESIRED_STATE,
- State.STOPPED.name()));
- }
- catch (Exception e)
- {
- LOGGER.error("Failed to stop node on broker with port " + inactiveBrokerPort, e);
- }
- finally
- {
- latch.countDown();
- }
+ _groupCreator.setNodeAttributes(inactiveBrokerPort,
+ inactiveBrokerPort,
+ Collections.singletonMap(
+ BDBHAVirtualHostNode.DESIRED_STATE,
+ State.STOPPED.name()));
+ }
+ catch (Exception e)
+ {
+ LOGGER.error("Failed to stop node on broker with port {}", inactiveBrokerPort, e);
+ }
+ finally
+ {
+ latch.countDown();
}
});
}
@@ -562,22 +575,16 @@ public class MultiNodeTest extends QpidBrokerTestCase
latch.await(500, TimeUnit.MILLISECONDS);
LOGGER.info("Committing transactions in parallel to provoke a lot of syncing to disk");
- for (int i = 0; i < sessions.length; i++)
+ for (final Session session : sessions)
{
- final Session session = sessions[i];
- executorService.submit(new Runnable()
- {
- @Override
- public void run()
+ executorService.submit(() -> {
+ try
+ {
+ session.commit();
+ }
+ catch (JMSException e)
{
- try
- {
- session.commit();
- }
- catch (JMSException e)
- {
- // majority of commits might fail due to insufficient replicas
- }
+ // majority of commits might fail due to insufficient replicas
}
});
}
@@ -596,7 +603,7 @@ public class MultiNodeTest extends QpidBrokerTestCase
{
_groupCreator.setNodeAttributes(port,
port,
- Collections.<String, Object>singletonMap(
+ Collections.singletonMap(
BDBHAVirtualHostNode.DESIRED_STATE,
State.ACTIVE.name()));
}
@@ -635,8 +642,11 @@ public class MultiNodeTest extends QpidBrokerTestCase
*/
public void testQuorumOverride() throws Exception
{
- final Connection connection = getConnection(_positiveFailoverUrl);
- ((AMQConnection)connection).setConnectionListener(_failoverListener);
+ final Connection connection = _positiveFailoverBuilder.build();
+ getJmsProvider().addGenericConnectionListener(connection, _failoverListener);
+ Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
+ getJmsProvider().createQueue(session, getTestQueueName());
+ session.close();
Set<Integer> ports = _groupCreator.getBrokerPortNumbersForNodes();
@@ -650,17 +660,17 @@ public class MultiNodeTest extends QpidBrokerTestCase
}
LOGGER.info("Awaiting failover to start");
- _failoverListener.awaitPreFailover(20000);
+ _failoverListener.awaitPreFailover(FAILOVER_COMPLETION_TIMEOUT);
LOGGER.info("Failover has begun");
Map<String, Object> attributes = _groupCreator.getNodeAttributes(activeBrokerPort);
assertEquals("Broker has unexpected quorum override", new Integer(0), attributes.get(BDBHAVirtualHostNode.QUORUM_OVERRIDE));
- _groupCreator.setNodeAttributes(activeBrokerPort, Collections.<String, Object>singletonMap(BDBHAVirtualHostNode.QUORUM_OVERRIDE, 1));
+ _groupCreator.setNodeAttributes(activeBrokerPort, Collections.singletonMap(BDBHAVirtualHostNode.QUORUM_OVERRIDE, 1));
attributes = _groupCreator.getNodeAttributes(activeBrokerPort);
assertEquals("Broker has unexpected quorum override", new Integer(1), attributes.get(BDBHAVirtualHostNode.QUORUM_OVERRIDE));
- _failoverListener.awaitFailoverCompletion(20000);
+ _failoverListener.awaitFailoverCompletion(FAILOVER_COMPLETION_TIMEOUT);
LOGGER.info("Failover has finished");
assertProducingConsuming(connection);
@@ -668,12 +678,14 @@ public class MultiNodeTest extends QpidBrokerTestCase
public void testPriority() throws Exception
{
- final Connection connection = getConnection(_positiveFailoverUrl);
-
- ((AMQConnection)connection).setConnectionListener(_failoverListener);
+ final Connection connection = _positiveFailoverBuilder.build();
+ getJmsProvider().addGenericConnectionListener(connection, _failoverListener);
+ Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
+ getJmsProvider().createQueue(session, getTestQueueName());
+ session.close();
final int activeBrokerPort = _groupCreator.getBrokerPortNumberFromConnection(connection);
- LOGGER.info("Active connection port " + activeBrokerPort);
+ LOGGER.info("Active connection port {}", activeBrokerPort);
int priority = 1;
Integer highestPriorityBrokerPort = null;
@@ -690,7 +702,7 @@ public class MultiNodeTest extends QpidBrokerTestCase
}
}
- LOGGER.info("Broker on port " + highestPriorityBrokerPort + " has the highest priority of " + priority);
+ LOGGER.info("Broker on port {} has the highest priority of {}", highestPriorityBrokerPort, priority);
// make sure all remote nodes are materialized on the master
// in order to make sure that DBPing is not invoked
@@ -725,7 +737,7 @@ public class MultiNodeTest extends QpidBrokerTestCase
LOGGER.info("Shutting down the MASTER");
_groupCreator.stopNode(activeBrokerPort);
- _failoverListener.awaitFailoverCompletion(20000);
+ _failoverListener.awaitFailoverCompletion(FAILOVER_COMPLETION_TIMEOUT);
LOGGER.info("Listener has finished");
Map<String, Object> attributes = _groupCreator.getNodeAttributes(highestPriorityBrokerPort, highestPriorityBrokerPort);
@@ -756,25 +768,14 @@ public class MultiNodeTest extends QpidBrokerTestCase
Durability.SyncPolicy.WRITE_NO_SYNC,
Durability.ReplicaAckPolicy.SIMPLE_MAJORITY));
- ReplicatedEnvironment intruder = null;
final String currentThreadName = Thread.currentThread().getName();
- try
+ try(ReplicatedEnvironment intruder = new ReplicatedEnvironment(environmentPathFile, replicationConfig, envConfig))
{
- intruder = new ReplicatedEnvironment(environmentPathFile, replicationConfig, envConfig);
+ LOGGER.debug("Intruder started");
}
finally
{
- try
- {
- if (intruder != null)
- {
- intruder.close();
- }
- }
- finally
- {
- Thread.currentThread().setName(currentThreadName);
- }
+ Thread.currentThread().setName(currentThreadName);
}
for (int port : _groupCreator.getBrokerPortNumbersForNodes())
@@ -802,29 +803,7 @@ public class MultiNodeTest extends QpidBrokerTestCase
}
}
- private void awaitNextTransaction(final int brokerPort) throws Exception
- {
- Map<String, Object> attributes = _groupCreator.getNodeAttributes(brokerPort);
- final int originalTransactionId = (int) attributes.get(BDBHAVirtualHostNode.LAST_KNOWN_REPLICATION_TRANSACTION_ID);
- int currentTransactionId = 0;
- long timeout = System.currentTimeMillis() + 60000;
- LOGGER.debug("Awaiting next transaction. Original transaction id {}", originalTransactionId);
- do
- {
- Thread.sleep(250);
- attributes = _groupCreator.getNodeAttributes(brokerPort);
- currentTransactionId = (int) attributes.get(BDBHAVirtualHostNode.LAST_KNOWN_REPLICATION_TRANSACTION_ID);
- LOGGER.debug("Current transaction id {}", currentTransactionId);
- }
- while (originalTransactionId >= currentTransactionId && timeout > System.currentTimeMillis());
-
- assertTrue("Group transaction has not occurred within timeout."
- + "Current transaction id " + currentTransactionId
- + "Original transaction id " + originalTransactionId,
- currentTransactionId > originalTransactionId);
- }
-
- private final class FailoverAwaitingListener implements ConnectionListener
+ private final class FailoverAwaitingListener implements GenericConnectionListener
{
private final CountDownLatch _failoverCompletionLatch;
private final CountDownLatch _preFailoverLatch;
@@ -842,20 +821,19 @@ public class MultiNodeTest extends QpidBrokerTestCase
}
@Override
- public boolean preResubscribe()
+ public void onConnectionInterrupted(URI uri)
{
- return true;
+ _failoverStarted = true;
+ _preFailoverLatch.countDown();
}
@Override
- public synchronized boolean preFailover(boolean redirect)
+ public void onConnectionRestored(URI uri)
{
- _failoverStarted = true;
- _preFailoverLatch.countDown();
- return true;
+ _failoverCompletionLatch.countDown();
}
- public void awaitFailoverCompletion(long delay) throws InterruptedException
+ void awaitFailoverCompletion(long delay) throws InterruptedException
{
if (!_failoverCompletionLatch.await(delay, TimeUnit.MILLISECONDS))
{
@@ -869,35 +847,19 @@ public class MultiNodeTest extends QpidBrokerTestCase
assertEquals("Failover did not occur", 0, _failoverCompletionLatch.getCount());
}
- public void assertNoFailoverCompletionWithin(long delay) throws InterruptedException
+ void assertNoFailoverCompletionWithin(long delay) throws InterruptedException
{
_failoverCompletionLatch.await(delay, TimeUnit.MILLISECONDS);
assertEquals("Failover occurred unexpectedly", 1L, _failoverCompletionLatch.getCount());
}
- public void awaitPreFailover(long delay) throws InterruptedException
+ void awaitPreFailover(long delay) throws InterruptedException
{
boolean complete = _preFailoverLatch.await(delay, TimeUnit.MILLISECONDS);
assertTrue("Failover was expected to begin within " + delay + " ms.", complete);
}
- @Override
- public void failoverComplete()
- {
- _failoverCompletionLatch.countDown();
- }
-
- @Override
- public void bytesSent(long count)
- {
- }
-
- @Override
- public void bytesReceived(long count)
- {
- }
-
- public synchronized boolean isFailoverStarted()
+ synchronized boolean isFailoverStarted()
{
return _failoverStarted;
}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c09a9a31/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/TwoNodeTest.java
----------------------------------------------------------------------
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/TwoNodeTest.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/TwoNodeTest.java
index 31d88ca..385417f 100644
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/TwoNodeTest.java
+++ b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/TwoNodeTest.java
@@ -19,14 +19,16 @@
*/
package org.apache.qpid.server.store.berkeleydb.replication;
-import java.io.File;
import java.util.Collections;
import java.util.Map;
import javax.jms.Connection;
import javax.jms.JMSException;
+import javax.jms.Session;
+import org.apache.qpid.server.model.Protocol;
import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBHAVirtualHostNode;
+import org.apache.qpid.systests.ConnectionBuilder;
import org.apache.qpid.test.utils.QpidBrokerTestCase;
public class TwoNodeTest extends QpidBrokerTestCase
@@ -38,10 +40,10 @@ public class TwoNodeTest extends QpidBrokerTestCase
private GroupCreator _groupCreator;
/** Used when expectation is client will not (re)-connect */
- private String _positiveFailoverUrl;
+ private ConnectionBuilder _positiveFailoverBuilder;
/** Used when expectation is client will not (re)-connect */
- private String _negativeFailoverUrl;
+ private ConnectionBuilder _negativeFailoverBuilder;
@Override
protected void setUp() throws Exception
@@ -62,24 +64,28 @@ public class TwoNodeTest extends QpidBrokerTestCase
private void startCluster(boolean designedPrimary) throws Exception
{
- setSystemProperty("java.util.logging.config.file", "etc" + File.separator + "log.properties");
_groupCreator.configureClusterNodes();
_groupCreator.setDesignatedPrimaryOnFirstBroker(designedPrimary);
- _positiveFailoverUrl = _groupCreator.getConnectionUrlForAllClusterNodes();
- _negativeFailoverUrl = _groupCreator.getConnectionUrlForAllClusterNodes(200, 0, 2);
+ _positiveFailoverBuilder = _groupCreator.getConnectionBuilderForAllClusterNodes();
+ _negativeFailoverBuilder = _groupCreator.getConnectionBuilderForAllClusterNodes(200, 0, 2);
_groupCreator.startCluster();
}
public void testMasterDesignatedPrimaryCanBeRestartedWithoutReplica() throws Exception
{
startCluster(true);
- final Connection initialConnection = getConnection(_positiveFailoverUrl);
+
+ final Connection initialConnection = _positiveFailoverBuilder.build();
+ Session session = initialConnection.createSession(true, Session.SESSION_TRANSACTED);
+ getJmsProvider().createQueue(session, getTestQueueName());
+ session.close();
+
int masterPort = _groupCreator.getBrokerPortNumberFromConnection(initialConnection);
assertProducingConsuming(initialConnection);
initialConnection.close();
_groupCreator.stopCluster();
_groupCreator.startNode(masterPort);
- final Connection secondConnection = getConnection(_positiveFailoverUrl);
+ final Connection secondConnection = _positiveFailoverBuilder.build();
assertProducingConsuming(secondConnection);
secondConnection.close();
}
@@ -87,12 +93,17 @@ public class TwoNodeTest extends QpidBrokerTestCase
public void testClusterRestartWithoutDesignatedPrimary() throws Exception
{
startCluster(false);
- final Connection initialConnection = getConnection(_positiveFailoverUrl);
+
+ final Connection initialConnection = _positiveFailoverBuilder.build();
+ Session session = initialConnection.createSession(true, Session.SESSION_TRANSACTED);
+ getJmsProvider().createQueue(session, getTestQueueName());
+ session.close();
+
assertProducingConsuming(initialConnection);
initialConnection.close();
_groupCreator.stopCluster();
_groupCreator.startClusterParallel();
- final Connection secondConnection = getConnection(_positiveFailoverUrl);
+ final Connection secondConnection = _positiveFailoverBuilder.build();
assertProducingConsuming(secondConnection);
secondConnection.close();
}
@@ -101,19 +112,38 @@ public class TwoNodeTest extends QpidBrokerTestCase
{
startCluster(true);
_groupCreator.stopNode(_groupCreator.getBrokerPortNumberOfSecondaryNode());
- final Connection connection = getConnection(_positiveFailoverUrl);
+
+ final Connection connection = _positiveFailoverBuilder.build();
+ Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
+ getJmsProvider().createQueue(session, getTestQueueName());
+ session.close();
+
assertNotNull("Expected to get a valid connection to primary", connection);
assertProducingConsuming(connection);
}
public void testPersistentOperationsFailOnNonDesignatedPrimaryAfterSecondaryStopped() throws Exception
{
+ if (getBrokerProtocol().equals(Protocol.AMQP_1_0))
+ {
+ // TODO - there seems to be a client defect when a JMS operation is interrupted
+ // by a graceful connection close from the client side.
+ return;
+ }
+
startCluster(false);
+
+ final Connection initialConnection = _negativeFailoverBuilder.build();
+ Session session = initialConnection.createSession(true, Session.SESSION_TRANSACTED);
+ getJmsProvider().createQueue(session, getTestQueueName());
+ initialConnection.close();
+
_groupCreator.stopNode(_groupCreator.getBrokerPortNumberOfSecondaryNode());
try
{
- Connection connection = getConnection(_negativeFailoverUrl);
+
+ Connection connection = _negativeFailoverBuilder.build();
assertProducingConsuming(connection);
fail("Exception not thrown");
}
@@ -127,12 +157,19 @@ public class TwoNodeTest extends QpidBrokerTestCase
public void testSecondaryDoesNotBecomePrimaryWhenDesignatedPrimaryStopped() throws Exception
{
+ if (getBrokerProtocol().equals(Protocol.AMQP_1_0))
+ {
+ // TODO - there seems to be a client defect when a JMS operation is interrupted
+ // by a graceful connection close from the client side.
+ return;
+ }
+
startCluster(true);
_groupCreator.stopNode(_groupCreator.getBrokerPortNumberOfPrimary());
try
{
- getConnection(_negativeFailoverUrl);
+ _negativeFailoverBuilder.build();
fail("Connection not expected");
}
catch (JMSException e)
@@ -158,6 +195,12 @@ public class TwoNodeTest extends QpidBrokerTestCase
{
startCluster(true);
+ final Connection initialConnection = _positiveFailoverBuilder.build();
+ Session session = initialConnection.createSession(true, Session.SESSION_TRANSACTED);
+ getJmsProvider().createQueue(session, getTestQueueName());
+ initialConnection.close();
+
+
_groupCreator.stopNode(_groupCreator.getBrokerPortNumberOfPrimary());
Map<String, Object> secondaryNodeAttributes = _groupCreator.getNodeAttributes(_groupCreator.getBrokerPortNumberOfSecondaryNode());
@@ -174,7 +217,7 @@ public class TwoNodeTest extends QpidBrokerTestCase
}
assertTrue("Expected secondary to transition to primary within " + timeout, (Boolean) secondaryNodeAttributes.get(BDBHAVirtualHostNode.DESIGNATED_PRIMARY));
- final Connection connection = getConnection(_positiveFailoverUrl);
+ final Connection connection = _positiveFailoverBuilder.build();
assertNotNull("Expected to get a valid connection to new primary", connection);
assertProducingConsuming(connection);
}
@@ -183,6 +226,11 @@ public class TwoNodeTest extends QpidBrokerTestCase
{
startCluster(false);
+ final Connection initialConnection = _positiveFailoverBuilder.build();
+ Session session = initialConnection.createSession(true, Session.SESSION_TRANSACTED);
+ getJmsProvider().createQueue(session, getTestQueueName());
+ initialConnection.close();
+
_groupCreator.stopNode(_groupCreator.getBrokerPortNumberOfSecondaryNode());
Map<String, Object> secondaryNodeAttributes = _groupCreator.getNodeAttributes(_groupCreator.getBrokerPortNumberOfPrimary());
@@ -191,7 +239,7 @@ public class TwoNodeTest extends QpidBrokerTestCase
_groupCreator.setNodeAttributes(_groupCreator.getBrokerPortNumberOfPrimary(), Collections.<String, Object>singletonMap(BDBHAVirtualHostNode.DESIGNATED_PRIMARY, true));
_groupCreator.awaitNodeToAttainRole(_groupCreator.getBrokerPortNumberOfPrimary(), "MASTER" );
- final Connection connection = getConnection(_positiveFailoverUrl);
+ final Connection connection = _positiveFailoverBuilder.build();
assertNotNull("Expected to get a valid connection to primary", connection);
assertProducingConsuming(connection);
}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c09a9a31/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/ConnectionBuilder.java
----------------------------------------------------------------------
diff --git a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/ConnectionBuilder.java b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/ConnectionBuilder.java
index 6e64fd2..34a7f62 100644
--- a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/ConnectionBuilder.java
+++ b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/ConnectionBuilder.java
@@ -34,14 +34,19 @@ public interface ConnectionBuilder
ConnectionBuilder setHost(String host);
ConnectionBuilder setPort(int port);
+
+ @Deprecated
ConnectionBuilder setSslPort(int port);
+
ConnectionBuilder setPrefetch(int prefetch);
ConnectionBuilder setClientId(String clientId);
ConnectionBuilder setUsername(String username);
ConnectionBuilder setPassword(String password);
ConnectionBuilder setVirtualHost(String virtualHostName);
ConnectionBuilder setFailover(boolean enableFailover);
+ ConnectionBuilder addFailoverPort(int port);
ConnectionBuilder setFailoverReconnectAttempts(int reconnectAttempts);
+ ConnectionBuilder setFailoverReconnectDelay(int connectDelay);
ConnectionBuilder setTls(boolean enableTls);
ConnectionBuilder setSyncPublish(boolean syncPublish);
ConnectionBuilder setOptions(Map<String, String> options);
@@ -56,8 +61,9 @@ public interface ConnectionBuilder
ConnectionBuilder setVerifyHostName(boolean verifyHostName);
ConnectionBuilder setKeyAlias(String alias);
ConnectionBuilder setSaslMechanisms(String... mechanism);
- ConnectionBuilder setCompress(boolean compress);
+ ConnectionBuilder setCompress(boolean compress);
Connection build() throws NamingException, JMSException;
+
ConnectionFactory buildConnectionFactory() throws NamingException;
}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c09a9a31/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/GenericConnectionListener.java
----------------------------------------------------------------------
diff --git a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/GenericConnectionListener.java b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/GenericConnectionListener.java
new file mode 100644
index 0000000..0d55d8a
--- /dev/null
+++ b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/GenericConnectionListener.java
@@ -0,0 +1,29 @@
+/*
+ * 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.systests;
+
+import java.net.URI;
+
+public interface GenericConnectionListener
+{
+ void onConnectionRestored(URI uri);
+ void onConnectionInterrupted(URI uri);
+}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c09a9a31/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/JmsProvider.java
----------------------------------------------------------------------
diff --git a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/JmsProvider.java b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/JmsProvider.java
index beece11..7980d17 100644
--- a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/JmsProvider.java
+++ b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/JmsProvider.java
@@ -20,6 +20,7 @@
package org.apache.qpid.systests;
+import java.net.URI;
import java.net.URISyntaxException;
import javax.jms.Connection;
@@ -49,4 +50,8 @@ public interface JmsProvider
Topic createTopicOnFanout(Connection con, String topicName) throws JMSException, URISyntaxException;
ConnectionBuilder getConnectionBuilder();
+
+ void addGenericConnectionListener(Connection connection, GenericConnectionListener genericConnectionListener);
+
+ URI getConnectedURI(Connection connection);
}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c09a9a31/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClient0xConnectionBuilder.java
----------------------------------------------------------------------
diff --git a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClient0xConnectionBuilder.java b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClient0xConnectionBuilder.java
index 95e6134..262d20b 100644
--- a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClient0xConnectionBuilder.java
+++ b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClient0xConnectionBuilder.java
@@ -23,9 +23,12 @@ package org.apache.qpid.systests;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
import java.util.Hashtable;
+import java.util.List;
import java.util.Map;
import java.util.TreeMap;
+import java.util.stream.Collectors;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
@@ -36,6 +39,8 @@ import javax.naming.NamingException;
public class QpidJmsClient0xConnectionBuilder implements ConnectionBuilder
{
+ private final List<Integer> _failoverPorts = new ArrayList<>();
+
private String _clientId = "clientid";
private String _username = USERNAME;
private String _password = PASSWORD;
@@ -44,6 +49,7 @@ public class QpidJmsClient0xConnectionBuilder implements ConnectionBuilder
private boolean _enableFailover;
private final Map<String, Object> _options = new TreeMap<>();
private int _reconnectAttempts = 20;
+ private int _connectdelay;
private String _host = "localhost";
private int _port;
private int _sslPort;
@@ -70,6 +76,13 @@ public class QpidJmsClient0xConnectionBuilder implements ConnectionBuilder
}
@Override
+ public ConnectionBuilder addFailoverPort(final int port)
+ {
+ _failoverPorts.add(port);
+ return this;
+ }
+
+ @Override
public ConnectionBuilder setSslPort(final int port)
{
_sslPort = port;
@@ -126,6 +139,13 @@ public class QpidJmsClient0xConnectionBuilder implements ConnectionBuilder
}
@Override
+ public ConnectionBuilder setFailoverReconnectDelay(final int connectDelay)
+ {
+ _connectdelay = connectDelay;
+ return this;
+ }
+
+ @Override
public ConnectionBuilder setTls(final boolean enableTls)
{
_enableTls = enableTls;
@@ -285,73 +305,47 @@ public class QpidJmsClient0xConnectionBuilder implements ConnectionBuilder
{
cUrlBuilder.append(_virtualHost);
}
+ cUrlBuilder.append("?");
- cUrlBuilder.append("?brokerlist='tcp://").append(_host).append(":");
- if (_enableTls)
- {
- cUrlBuilder.append(_sslPort).append("?ssl='true'");
- if (_keyStoreLocation != null)
- {
- cUrlBuilder.append("&key_store='").append(encodeBrokerOption(_keyStoreLocation)).append('\'');
- }
- if (_keyStorePassword != null)
- {
- cUrlBuilder.append("&key_store_password='").append(_keyStorePassword).append('\'');
- }
- if (_trustStoreLocation != null)
- {
- cUrlBuilder.append("&trust_store='").append(encodeBrokerOption(_trustStoreLocation)).append('\'');
- }
- if (_trustStorePassword != null)
- {
- cUrlBuilder.append("&trust_store_password='").append(_trustStorePassword).append('\'');
- }
- if (_verifyHostName != null)
- {
- cUrlBuilder.append("&ssl_verify_hostname='").append(_verifyHostName).append('\'');
- }
- if (_keyAlias != null)
- {
- cUrlBuilder.append("&ssl_cert_alias='").append(_keyAlias).append('\'');
- }
- }
- else
- {
- cUrlBuilder.append(_port);
- }
+ final List<Integer> copy = new ArrayList<>(_failoverPorts.size() + 1);
+ copy.add(_enableTls ? _sslPort : _port);
- if (_saslMechanisms != null)
+ if (_enableFailover)
{
- if (_enableTls)
+ if (_failoverPorts.isEmpty())
{
- cUrlBuilder.append("&");
+ Integer testPortAlt;
+ if ((testPortAlt = Integer.getInteger("test.port.alt")) != null)
+ {
+ copy.add(testPortAlt);
+ }
+ else if (_enableTls && (testPortAlt = Integer.getInteger("test.port.alt.ssl")) != null)
+ {
+ copy.add(testPortAlt);
+ }
}
else
{
- cUrlBuilder.append("?");
+ copy.addAll(_failoverPorts);
}
- cUrlBuilder.append("sasl_mechs='").append(_saslMechanisms).append('\'');
}
+ final String transportQuery = buildTransportQuery();
+ final String brokerlist = copy.stream()
+ .map(port -> String.format("tcp://%s:%d%s", _host, port, transportQuery))
+ .collect(Collectors.joining(";", "brokerlist='", "'"));
+ cUrlBuilder.append(brokerlist);
+
if (_enableFailover)
{
- cUrlBuilder.append(";tcp://").append(_host).append(":");
- if (_enableTls)
- {
- cUrlBuilder.append(System.getProperty("test.port.alt.ssl")).append("?ssl='true'");
- }
- else
- {
- cUrlBuilder.append(System.getProperty("test.port.alt"));
- }
- cUrlBuilder.append("'")
- .append("&sync_ack='true'&sync_publish='all'&failover='roundrobin?cyclecount='")
- .append(_reconnectAttempts)
- .append("''");
+ cUrlBuilder.append("&sync_ack='true'&sync_publish='all'");
+ cUrlBuilder.append(String.format("&failover='roundrobin?cyclecount='%d''", _reconnectAttempts));
}
- else
+
+ if (_saslMechanisms != null)
{
- cUrlBuilder.append("'");
+ cUrlBuilder.append("&");
+ cUrlBuilder.append("sasl_mechs='").append(_saslMechanisms).append('\'');
}
for (Map.Entry<String, Object> entry : _options.entrySet())
@@ -375,6 +369,47 @@ public class QpidJmsClient0xConnectionBuilder implements ConnectionBuilder
}
}
+ private String buildTransportQuery()
+ {
+ final StringBuilder builder = new StringBuilder();
+
+ if (_enableTls)
+ {
+ builder.append("?ssl='true'");
+ if (_keyStoreLocation != null)
+ {
+ builder.append("&key_store='").append(encodeBrokerOption(_keyStoreLocation)).append('\'');
+ }
+ if (_keyStorePassword != null)
+ {
+ builder.append("&key_store_password='").append(_keyStorePassword).append('\'');
+ }
+ if (_trustStoreLocation != null)
+ {
+ builder.append("&trust_store='").append(encodeBrokerOption(_trustStoreLocation)).append('\'');
+ }
+ if (_trustStorePassword != null)
+ {
+ builder.append("&trust_store_password='").append(_trustStorePassword).append('\'');
+ }
+ if (_verifyHostName != null)
+ {
+ builder.append("&ssl_verify_hostname='").append(_verifyHostName).append('\'');
+ }
+ if (_keyAlias != null)
+ {
+ builder.append("&ssl_cert_alias='").append(_keyAlias).append('\'');
+ }
+ }
+ if (_connectdelay > 0)
+ {
+ final char initial = builder.length() == 0 ? '?' : '&';
+ builder.append(String.format("%cconnectdelay='%d'", initial, _connectdelay));
+ }
+
+ return builder.toString();
+ }
+
private String encodeBrokerOption(final String canonicalPath)
{
try
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c09a9a31/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClient0xProvider.java
----------------------------------------------------------------------
diff --git a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClient0xProvider.java b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClient0xProvider.java
index 89de60a..733b650 100644
--- a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClient0xProvider.java
+++ b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClient0xProvider.java
@@ -22,9 +22,13 @@ package org.apache.qpid.systests;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.net.URI;
import java.net.URISyntaxException;
import java.security.AccessControlException;
import java.util.Hashtable;
+import java.util.Objects;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
@@ -73,7 +77,7 @@ public class QpidJmsClient0xProvider implements JmsProvider
public Queue createQueue(Session session, String queueName) throws JMSException
{
- Queue amqQueue = null;
+ Queue amqQueue;
try
{
amqQueue = getTestQueue(queueName);
@@ -148,4 +152,73 @@ public class QpidJmsClient0xProvider implements JmsProvider
{
return new QpidJmsClient0xConnectionBuilder();
}
+
+ @Override
+ public void addGenericConnectionListener(final Connection connection,
+ final GenericConnectionListener listener)
+ {
+ try
+ {
+ final Class<?> iface = Class.forName("org.apache.qpid.jms.ConnectionListener");
+ final Object listenerProxy = Proxy.newProxyInstance(iface.getClassLoader(),
+ new Class[]{iface},
+ (proxy, method, args) -> {
+ final String methodName = method.getName();
+ switch (methodName)
+ {
+ case "preFailover":
+ {
+ URI uri = getConnectedURI(connection);
+ listener.onConnectionInterrupted(uri);
+ return true;
+ }
+ case "preResubscribe":
+ return true;
+ case "failoverComplete":
+ {
+ URI uri = getConnectedURI(connection);
+ listener.onConnectionRestored(uri);
+ break;
+ }
+ case "toString":
+ return String.format("[Proxy %s]",
+ listener.toString());
+ case "equals":
+ Object other = args[0];
+ return Objects.equals(this, other);
+ case "hashCode":
+ return Objects.hashCode(this);
+ }
+ return null;
+ });
+
+ final Method setConnectionListener = connection.getClass().getMethod("setConnectionListener", iface);
+ setConnectionListener.invoke(connection, listenerProxy);
+ }
+ catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e)
+ {
+ throw new RuntimeException("Unable to reflectively add listener", e);
+ }
+ }
+
+ @Override
+ public URI getConnectedURI(final Connection connection)
+ {
+ try
+ {
+ final Method brokerDetailsMethod = connection.getClass().getMethod("getActiveBrokerDetails");
+ Object abd = brokerDetailsMethod.invoke(connection);
+ final Method getHostMethod = abd.getClass().getMethod("getHost");
+ final Method getPortMethod = abd.getClass().getMethod("getPort");
+ final Method getTransportMethod = abd.getClass().getMethod("getTransport");
+ String host = (String) getHostMethod.invoke(abd);
+ int port = (Integer) getPortMethod.invoke(abd);
+ String transport = (String) getTransportMethod.invoke(abd);
+ return URI.create(String.format("%s://%s:%d", transport, host, port));
+ }
+ catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e)
+ {
+ throw new RuntimeException("Unable to reflectively get connected URI", e);
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c09a9a31/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClientConnectionBuilder.java
----------------------------------------------------------------------
diff --git a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClientConnectionBuilder.java b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClientConnectionBuilder.java
index 76e3a76..263ff9c 100644
--- a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClientConnectionBuilder.java
+++ b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClientConnectionBuilder.java
@@ -22,10 +22,15 @@ package org.apache.qpid.systests;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.HashMap;
import java.util.Hashtable;
+import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
@@ -43,6 +48,7 @@ public class QpidJmsClientConnectionBuilder implements ConnectionBuilder
private Map<String, Object> _options;
private boolean _enableTls;
private boolean _enableFailover;
+ private final List<Integer> _failoverPorts = new ArrayList<>();
QpidJmsClientConnectionBuilder()
{
@@ -68,6 +74,13 @@ public class QpidJmsClientConnectionBuilder implements ConnectionBuilder
}
@Override
+ public ConnectionBuilder addFailoverPort(final int port)
+ {
+ _failoverPorts.add(port);
+ return this;
+ }
+
+ @Override
public ConnectionBuilder setSslPort(final int port)
{
_sslPort = port;
@@ -145,6 +158,13 @@ public class QpidJmsClientConnectionBuilder implements ConnectionBuilder
}
@Override
+ public ConnectionBuilder setFailoverReconnectDelay(final int connectDelay)
+ {
+ _options.put("failover.reconnectDelay", connectDelay);
+ return this;
+ }
+
+ @Override
public ConnectionBuilder setTls(final boolean enableTls)
{
_enableTls = enableTls;
@@ -270,13 +290,43 @@ public class QpidJmsClientConnectionBuilder implements ConnectionBuilder
{
options.put("failover.maxReconnectAttempts", "2");
}
- connectionUrlBuilder.append("failover:(amqp://")
- .append(_host)
- .append(":")
- .append(_port)
- .append(",amqp://localhost:")
- .append(System.getProperty("test.port.alt"))
- .append(")");
+
+ final Set<String> transportKeys = options.keySet()
+ .stream()
+ .filter(key -> key.startsWith("amqp.") || key.startsWith(
+ "transport."))
+ .collect(Collectors.toSet());
+
+
+ final Map<String, Object> transportOptions = new HashMap<>(options);
+ transportOptions.keySet().retainAll(transportKeys);
+ options.keySet().removeAll(transportKeys);
+
+ final StringBuilder transportQueryBuilder = new StringBuilder();
+ appendOptions(transportOptions, transportQueryBuilder);
+ final String transportQuery = transportQueryBuilder.toString();
+
+ final List<Integer> copy = new ArrayList<>(_failoverPorts.size() + 1);
+ copy.add(_enableTls ? _sslPort : _port);
+
+ if (_failoverPorts.isEmpty())
+ {
+ Integer testPortAlt;
+ if ((testPortAlt = Integer.getInteger("test.port.alt")) != null)
+ {
+ copy.add(testPortAlt);
+ }
+ else if (_enableTls && (testPortAlt = Integer.getInteger("test.port.alt.ssl")) != null)
+ {
+ copy.add(testPortAlt);
+ }
+ }
+ copy.addAll(_failoverPorts);
+
+ final String failover = copy.stream()
+ .map(port -> String.format("amqp://%s:%d%s", _host, port, transportQuery))
+ .collect(Collectors.joining(",", "failover:(", ")"));
+ connectionUrlBuilder.append(failover);
appendOptions(options, connectionUrlBuilder);
}
else if (!_enableTls)
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c09a9a31/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClientProvider.java
----------------------------------------------------------------------
diff --git a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClientProvider.java b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClientProvider.java
index d8af7f6..d450e11 100644
--- a/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClientProvider.java
+++ b/systests/qpid-systests-jms-core/src/main/java/org/apache/qpid/systests/QpidJmsClientProvider.java
@@ -20,7 +20,12 @@
package org.apache.qpid.systests;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.net.URI;
import java.net.URISyntaxException;
+import java.util.Objects;
import java.util.Properties;
import javax.jms.Connection;
@@ -120,4 +125,63 @@ public class QpidJmsClientProvider implements JmsProvider
initialContext.close();
}
}
+
+ @Override
+ public void addGenericConnectionListener(final Connection connection, final GenericConnectionListener listener)
+ {
+ try
+ {
+ final Class<?> iface = Class.forName("org.apache.qpid.jms.JmsConnectionListener");
+ final Object listenerProxy = Proxy.newProxyInstance(iface.getClassLoader(),
+ new Class[]{iface},
+ (proxy, method, args) -> {
+ final String methodName = method.getName();
+ switch (methodName)
+ {
+ case "onConnectionRestored":
+ listener.onConnectionRestored(
+
+ ((URI) args[0]));
+ break;
+ case "onConnectionInterrupted":
+ listener.onConnectionInterrupted(
+
+ ((URI) args[0]));
+ break;
+ case "toString":
+ return String.format("[Proxy %s]",
+ listener.toString());
+ case "equals":
+ Object other = args[0];
+ return Objects.equals(this, other);
+ case "hashCode":
+ return Objects.hashCode(this);
+ }
+ return null;
+ });
+
+ final Method addConnectionListener = connection.getClass().getMethod("addConnectionListener", iface);
+ addConnectionListener.invoke(connection, listenerProxy);
+ }
+ catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e)
+ {
+ throw new RuntimeException("Unable to reflectively add listener", e);
+ }
+ }
+
+ @Override
+ public URI getConnectedURI(final Connection connection)
+ {
+ final Method connectedURI;
+ try
+ {
+ connectedURI = connection.getClass().getMethod("getConnectedURI", new Class[] {});
+ return (URI) connectedURI.invoke(connection, null);
+ }
+ catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e)
+ {
+ throw new RuntimeException("Unable to reflectively get connected URI", e);
+ }
+ }
+
}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c09a9a31/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java b/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java
index fe53a24..654c6a0 100755
--- a/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java
+++ b/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java
@@ -99,6 +99,7 @@ public class QpidBrokerTestCase extends QpidTestCase
private AmqpManagementFacade _managementFacade;
private BrokerHolder _defaultBroker;
private MessageType _messageType = MessageType.TEXT;
+
private JmsProvider _jmsProvider;
@Override
@@ -217,6 +218,11 @@ public class QpidBrokerTestCase extends QpidTestCase
getDefaultBroker().restart();
}
+ public JmsProvider getJmsProvider()
+ {
+ return _jmsProvider;
+ }
+
public ConnectionBuilder getConnectionBuilder()
{
final ConnectionBuilder connectionBuilder = _jmsProvider.getConnectionBuilder()
@@ -571,7 +577,7 @@ public class QpidBrokerTestCase extends QpidTestCase
sendMessage(session, destination, 1);
session.commit();
connection.start();
- Message m1 = consumer.receive(RECEIVE_TIMEOUT);
+ Message m1 = consumer.receive(getReceiveTimeout());
assertNotNull("Message 1 is not received", m1);
assertEquals("Unexpected first message received", 0, m1.getIntProperty(INDEX));
session.commit();
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c09a9a31/test-profiles/CPPExcludes
----------------------------------------------------------------------
diff --git a/test-profiles/CPPExcludes b/test-profiles/CPPExcludes
index d8ae4d7..ba9a39e 100755
--- a/test-profiles/CPPExcludes
+++ b/test-profiles/CPPExcludes
@@ -82,8 +82,6 @@ org.apache.qpid.systest.rest.acl.*
-org.apache.qpid.test.unit.client.AMQSessionTest#testQueueDepthForQueueThatDoesNotExistLegacyBehaviour_08_091
-
org.apache.qpid.server.protocol.v0_8.*
//Qpid Broker-J BDB System Tests
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org
[3/8] qpid-broker-j git commit: QPID-8123: [Broker-J] [BDB System
Tests] Remove Qpid JMS AMQP 0-x client dependencies from BDBUpgradeTest
Posted by kw...@apache.org.
QPID-8123: [Broker-J] [BDB System Tests] Remove Qpid JMS AMQP 0-x client dependencies from BDBUpgradeTest
Project: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/commit/6b31d0fd
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/6b31d0fd
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/6b31d0fd
Branch: refs/heads/master
Commit: 6b31d0fd7bb2f31f65e68227610a6a50c2d758fe
Parents: c09a9a3
Author: Keith Wall <kw...@apache.org>
Authored: Mon Mar 12 15:54:05 2018 +0000
Committer: Keith Wall <kw...@apache.org>
Committed: Mon Mar 12 16:24:17 2018 +0000
----------------------------------------------------------------------
.../berkeleydb/BDBStoreUpgradeTestPreparer.java | 83 +++++++-------------
.../server/store/berkeleydb/BDBUpgradeTest.java | 33 +++++---
2 files changed, 52 insertions(+), 64 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/6b31d0fd/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBStoreUpgradeTestPreparer.java
----------------------------------------------------------------------
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBStoreUpgradeTestPreparer.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBStoreUpgradeTestPreparer.java
index 1cff8f2..750cc07 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBStoreUpgradeTestPreparer.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBStoreUpgradeTestPreparer.java
@@ -22,31 +22,16 @@ package org.apache.qpid.server.store.berkeleydb;
import java.util.HashMap;
import java.util.Map;
+import java.util.stream.Collectors;
-import javax.jms.Connection;
-import javax.jms.DeliveryMode;
-import javax.jms.Destination;
-import javax.jms.ExceptionListener;
-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.Topic;
-import javax.jms.TopicConnection;
-import javax.jms.TopicPublisher;
-import javax.jms.TopicSession;
-import javax.jms.TopicSubscriber;
+import javax.jms.*;
+import javax.naming.Context;
+import javax.naming.InitialContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.apache.qpid.client.AMQConnectionFactory;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQSession;
import org.apache.qpid.server.queue.QueueArgumentsConverter;
-import org.apache.qpid.url.URLSyntaxException;
/**
* Prepares an older version brokers BDB store with the required
@@ -73,22 +58,26 @@ public class BDBStoreUpgradeTestPreparer
public static final String PRIORITY_QUEUE_NAME="myPriorityQueue";
public static final String QUEUE_WITH_DLQ_NAME="myQueueWithDLQ";
public static final String NONEXCLUSIVE_WITH_ERRONEOUS_OWNER = "nonexclusive-with-erroneous-owner";
- public static final String MISUSED_OWNER = "misused-owner-as-description";
- private static final String VIRTUAL_HOST_NAME = "test";
private static final String SORTED_QUEUE_NAME = "mySortedQueue";
private static final String SORT_KEY = "mySortKey";
private static final String TEST_EXCHANGE_NAME = "myCustomExchange";
private static final String TEST_QUEUE_NAME = "myCustomQueue";
- private static AMQConnectionFactory _connFac;
- private static final String CONN_URL = "amqp://guest:guest@clientid/" + VIRTUAL_HOST_NAME + "?brokerlist='tcp://localhost:5672'";
+ private static ConnectionFactory _connFac;
+ private static TopicConnectionFactory _topciConnFac;
/**
* Create a BDBStoreUpgradeTestPreparer instance
*/
- public BDBStoreUpgradeTestPreparer () throws URLSyntaxException
+ public BDBStoreUpgradeTestPreparer () throws Exception
{
- _connFac = new AMQConnectionFactory(CONN_URL);
+ // The configuration for the Qpid InitialContextFactory has been supplied in
+ // a jndi.properties file in the classpath, which results in it being picked
+ // up automatically by the InitialContext constructor.
+ Context context = new InitialContext();
+
+ _connFac = (ConnectionFactory) context.lookup("myConnFactory");
+ _topciConnFac = (TopicConnectionFactory) context.lookup("myTopicConnFactory");
}
private void prepareBroker() throws Exception
@@ -102,10 +91,9 @@ public class BDBStoreUpgradeTestPreparer
private void prepareNonDurableQueue() throws Exception
{
Connection connection = _connFac.createConnection();
- AMQSession<?, ?> session = (AMQSession<?,?>)connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- AMQDestination destination = (AMQDestination) session.createQueue(NON_DURABLE_QUEUE_NAME);
- session.sendCreateQueue(NON_DURABLE_QUEUE_NAME, false, false, false, null);
- session.bindQueue(NON_DURABLE_QUEUE_NAME, NON_DURABLE_QUEUE_NAME, null, "amq.direct", destination);
+ Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ Destination destination = session.createQueue(NON_DURABLE_QUEUE_NAME);
+ session.createConsumer(destination).close();
MessageProducer messageProducer = session.createProducer(destination);
sendMessages(session, messageProducer, destination, DeliveryMode.PERSISTENT, 1024, 3);
connection.close();
@@ -129,14 +117,7 @@ public class BDBStoreUpgradeTestPreparer
// Create a connection
Connection connection = _connFac.createConnection();
connection.start();
- connection.setExceptionListener(new ExceptionListener()
- {
- @Override
- public void onException(JMSException e)
- {
- LOGGER.error("Error setting exception listener for connection", e);
- }
- });
+ connection.setExceptionListener(e -> LOGGER.error("Error setting exception listener for connection", e));
// Create a session on the connection, transacted to confirm delivery
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
Queue queue = session.createQueue(QUEUE_NAME);
@@ -188,8 +169,6 @@ public class BDBStoreUpgradeTestPreparer
MessageProducer dlqMessageProducer = session.createProducer(dlq);
sendMessages(session, dlqMessageProducer, dlq, DeliveryMode.PERSISTENT, 1*1024, 1);
session.commit();
-
- ((AMQSession<?,?>) session).declareExchange(TEST_EXCHANGE_NAME, "direct", false);
Queue customQueue = createAndBindQueueOnBroker(session, TEST_QUEUE_NAME, null, TEST_EXCHANGE_NAME, "direct");
MessageProducer customQueueMessageProducer = session.createProducer(customQueue);
sendMessages(session, customQueueMessageProducer, customQueue, DeliveryMode.PERSISTENT, 1*1024, 1);
@@ -209,15 +188,19 @@ public class BDBStoreUpgradeTestPreparer
private Queue createAndBindQueueOnBroker(Session session, String queueName, final Map<String, Object> arguments, String exchangeName, String exchangeType) throws Exception
{
- ((AMQSession<?,?>) session).createQueue(queueName, false, true, false, arguments);
- Queue queue = session.createQueue("BURL:" + exchangeType + "://" + exchangeName + "/" + queueName + "/" + queueName + "?durable='true'");
- ((AMQSession<?,?>) session).declareAndBind((AMQDestination)queue);
+ final String declareArgs = arguments.entrySet()
+ .stream()
+ .map(entry -> String.format("'%s' : %s", entry.getKey(), entry.getValue()))
+ .collect(Collectors.joining("{", "}", ","));
+
+ Queue queue = session.createQueue(String.format(
+ "ADDR: %s; {create:always, node: {type: queue, x-bindings:[{exchange: '%s', key: %s}], x-declare: {arguments:%s}}", queueName, exchangeName, queueName, declareArgs));
return queue;
}
private void prepareSortedQueue(Session session, String queueName, String sortKey) throws Exception
{
- final Map<String, Object> arguments = new HashMap<String, Object>();
+ final Map<String, Object> arguments = new HashMap<>();
arguments.put("qpid.queue_sort_key", sortKey);
Queue sortedQueue = createAndBindQueueOnBroker(session, queueName, arguments);
@@ -249,7 +232,7 @@ public class BDBStoreUpgradeTestPreparer
{
// Create a connection
- TopicConnection connection = _connFac.createTopicConnection();
+ TopicConnection connection = _topciConnFac.createTopicConnection();
connection.start();
connection.setExceptionListener(new ExceptionListener()
{
@@ -295,16 +278,9 @@ public class BDBStoreUpgradeTestPreparer
private void prepareDurableSubscriptionWithoutSelector() throws Exception
{
// Create a connection
- TopicConnection connection = _connFac.createTopicConnection();
+ TopicConnection connection = _topciConnFac.createTopicConnection();
connection.start();
- connection.setExceptionListener(new ExceptionListener()
- {
- @Override
- public void onException(JMSException e)
- {
- LOGGER.error("Error setting exception listener for connection", e);
- }
- });
+ connection.setExceptionListener(e -> LOGGER.error("Error setting exception listener for connection", e));
// Create a session on the connection, transacted to confirm delivery
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
Topic topic = session.createTopic(TOPIC_NAME);
@@ -371,7 +347,6 @@ public class BDBStoreUpgradeTestPreparer
*/
public static void main(String[] args) throws Exception
{
- System.setProperty("qpid.dest_syntax", "BURL");
BDBStoreUpgradeTestPreparer producer = new BDBStoreUpgradeTestPreparer();
producer.prepareBroker();
}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/6b31d0fd/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBUpgradeTest.java
----------------------------------------------------------------------
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBUpgradeTest.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBUpgradeTest.java
index 7b5c345..7f4f92c 100644
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBUpgradeTest.java
+++ b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBUpgradeTest.java
@@ -46,12 +46,6 @@ import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.exchange.ExchangeDefaults;
import org.apache.qpid.server.model.AlternateBinding;
import org.apache.qpid.server.model.Exchange;
import org.apache.qpid.server.model.ExclusivityPolicy;
@@ -71,7 +65,6 @@ import org.apache.qpid.util.FileUtils;
*/
public class BDBUpgradeTest extends QpidBrokerTestCase
{
- private static final Logger LOGGER = LoggerFactory.getLogger(BDBUpgradeTest.class);
private static final String STRING_1024 = generateString(1024);
private static final String STRING_1024_256 = generateString(1024*256);
@@ -140,7 +133,18 @@ public class BDBUpgradeTest extends QpidBrokerTestCase
*/
public void testSelectorDurability() throws Exception
{
- AMQDestination queue = new AMQQueue(ExchangeDefaults.DEFAULT_EXCHANGE_NAME, "clientid" + ":" + SELECTOR_SUB_NAME);
+ Connection con = getConnection();
+ Queue queue;
+ try
+ {
+ Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ queue = session.createQueue("BURL:direct:////clientid" + ":" + SELECTOR_SUB_NAME);
+ }
+ finally
+ {
+ con.close();
+ }
+
// Create a connection and start it
TopicConnection connection = (TopicConnection) getConnection();
connection.start();
@@ -179,8 +183,17 @@ public class BDBUpgradeTest extends QpidBrokerTestCase
*/
public void testDurableSubscriptionWithoutSelector() throws Exception
{
- AMQDestination queue = new AMQQueue(ExchangeDefaults.DEFAULT_EXCHANGE_NAME, "clientid" + ":" + SUB_NAME);
-
+ Connection con = getConnection();
+ Queue queue;
+ try
+ {
+ Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ queue = session.createQueue("BURL:direct:////clientid" + ":" + SELECTOR_SUB_NAME);
+ }
+ finally
+ {
+ con.close();
+ }
// Create a connection and start it
TopicConnection connection = (TopicConnection) getConnection();
connection.start();
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org
[7/8] qpid-broker-j git commit: NO-JIRA: [Broker-J] [System Tests]
Remove Rest ACL Tests
Posted by kw...@apache.org.
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java b/systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java
deleted file mode 100644
index 4e85329..0000000
--- a/systests/src/test/java/org/apache/qpid/systest/rest/acl/BrokerACLTest.java
+++ /dev/null
@@ -1,1129 +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.systest.rest.acl;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.qpid.server.logging.logback.BrokerFileLogger;
-import org.apache.qpid.server.logging.logback.BrokerMemoryLogger;
-import org.apache.qpid.server.logging.logback.BrokerNameAndLevelLogInclusionRule;
-import org.apache.qpid.server.management.plugin.HttpManagement;
-import org.apache.qpid.server.management.plugin.servlet.rest.AbstractServlet;
-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.BrokerLogger;
-import org.apache.qpid.server.model.ConfiguredObject;
-import org.apache.qpid.server.model.ExternalFileBasedAuthenticationManager;
-import org.apache.qpid.server.model.GroupProvider;
-import org.apache.qpid.server.model.KeyStore;
-import org.apache.qpid.server.model.Port;
-import org.apache.qpid.server.model.Protocol;
-import org.apache.qpid.server.model.State;
-import org.apache.qpid.server.model.TrustStore;
-import org.apache.qpid.server.model.adapter.FileBasedGroupProvider;
-import org.apache.qpid.server.model.adapter.FileBasedGroupProviderImpl;
-import org.apache.qpid.server.security.AllowAllAccessControlProvider;
-import org.apache.qpid.server.security.FileKeyStore;
-import org.apache.qpid.server.security.FileTrustStore;
-import org.apache.qpid.server.security.access.plugins.AclFileAccessControlProvider;
-import org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManager;
-import org.apache.qpid.server.security.auth.manager.PlainPasswordDatabaseAuthenticationManager;
-import org.apache.qpid.systest.rest.QpidRestTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-import org.apache.qpid.test.utils.TestFileUtils;
-import org.apache.qpid.test.utils.TestSSLConstants;
-import org.apache.qpid.test.utils.TestUtils;
-
-public class BrokerACLTest extends QpidRestTestCase
-{
- private static final String ALLOWED_USER = "user1";
- private static final String DENIED_USER = "user2";
- private String _secondaryAclFileContent = "";
-
- @Override
- protected void customizeConfiguration() throws Exception
- {
- super.customizeConfiguration();
- final TestBrokerConfiguration defaultBrokerConfiguration = getDefaultBrokerConfiguration();
- defaultBrokerConfiguration.configureTemporaryPasswordFile(ALLOWED_USER, DENIED_USER);
-
- TestUtils.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT",
- "ACL ALLOW-LOG " + ALLOWED_USER + " CONFIGURE BROKER",
- "ACL DENY-LOG " + DENIED_USER + " CONFIGURE BROKER",
- "ACL ALLOW-LOG " + ALLOWED_USER + " ACCESS_LOGS BROKER",
- "ACL DENY-LOG " + DENIED_USER + " ACCESS_LOGS BROKER",
- "ACL DENY-LOG ALL ALL");
-
- _secondaryAclFileContent =
- "ACL ALLOW-LOG ALL ACCESS MANAGEMENT\n" +
- "ACL ALLOW-LOG " + ALLOWED_USER + " CONFIGURE BROKER\n" +
- "ACL DENY-LOG " + DENIED_USER + " CONFIGURE BROKER\n" +
- "ACL DENY-LOG ALL ALL";
- }
-
- /* === AuthenticationProvider === */
-
- public void testCreateAuthenticationProviderAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String authenticationProviderName = getTestName();
-
- int responseCode = createAuthenticationProvider(authenticationProviderName);
- assertEquals("Provider creation should be allowed", 201, responseCode);
-
- assertAuthenticationProviderExists(authenticationProviderName);
- }
-
- public void testCreateAuthenticationProviderDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- String authenticationProviderName = getTestName();
-
- int responseCode = createAuthenticationProvider(authenticationProviderName);
- assertEquals("Provider creation should be denied", 403, responseCode);
-
- assertAuthenticationProviderDoesNotExist(authenticationProviderName);
- }
-
- public void testDeleteAuthenticationProviderAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String providerName = getTestName();
-
- int responseCode = createAuthenticationProvider(providerName);
- assertEquals("Provider creation should be allowed", 201, responseCode);
-
- assertAuthenticationProviderExists(providerName);
-
- responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "DELETE");
- assertEquals("Provider deletion should be allowed", 200, responseCode);
-
- assertAuthenticationProviderDoesNotExist(TEST2_VIRTUALHOST);
- }
-
- public void testDeleteAuthenticationProviderDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String providerName = getTestName();
-
- int responseCode = createAuthenticationProvider(providerName);
- assertEquals("Provider creation should be allowed", 201, responseCode);
-
- assertAuthenticationProviderExists(providerName);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "DELETE");
- assertEquals("Provider deletion should be denied", 403, responseCode);
-
- assertAuthenticationProviderExists(providerName);
- }
-
- public void testSetAuthenticationProviderAttributesAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String providerName = TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER;
-
- assertAuthenticationProviderExists(providerName);
-
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(AuthenticationProvider.NAME, providerName);
- attributes.put(AuthenticationProvider.TYPE, PlainPasswordDatabaseAuthenticationManager.PROVIDER_TYPE);
- attributes.put(AuthenticationProvider.STATE, State.DELETED.name());
-
- int responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "PUT", attributes);
- assertEquals("Setting of provider attribites should be allowed", 200, responseCode);
- }
-
- public void testSetAuthenticationProviderAttributesDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String providerName = TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER;
- Map<String, Object> providerData = getRestTestHelper().getJsonAsMap("authenticationprovider/" + providerName);
-
- File file = TestFileUtils.createTempFile(this, ".users", "guest:guest\n" + ALLOWED_USER + ":" + ALLOWED_USER + "\n"
- + DENIED_USER + ":" + DENIED_USER);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(AuthenticationProvider.NAME, providerName);
- attributes.put(AuthenticationProvider.TYPE, AnonymousAuthenticationManager.PROVIDER_TYPE);
- attributes.put(ExternalFileBasedAuthenticationManager.PATH, file.getAbsolutePath());
-
- int responseCode = getRestTestHelper().submitRequest("authenticationprovider/" + providerName, "PUT", attributes);
- assertEquals("Setting of provider attribites should be allowed", 403, responseCode);
-
- Map<String, Object> provider = getRestTestHelper().getJsonAsMap("authenticationprovider/" + providerName);
- assertEquals("Unexpected STORE_URL attribute value",
- providerData.get(ExternalFileBasedAuthenticationManager.PATH),
- provider.get(ExternalFileBasedAuthenticationManager.PATH));
- }
-
- /* === Port === */
-
- public void testCreatePortAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String portName = getTestName();
-
- int responseCode = createPort(portName);
- assertEquals("Port creation should be allowed", 201, responseCode);
-
- assertPortExists(portName);
- }
-
- public void testCreatePortDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- String portName = getTestName();
-
- int responseCode = createPort(portName);
- assertEquals("Port creation should be denied", 403, responseCode);
-
- assertPortDoesNotExist(portName);
- }
-
- public void testDeletePortDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT;
- assertPortExists(portName);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- int responseCode = getRestTestHelper().submitRequest("port/" + portName, "DELETE");
- assertEquals("Port deletion should be denied", 403, responseCode);
-
- assertPortExists(portName);
- }
-
- public void testDeletePortAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT;
- assertPortExists(portName);
-
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- int responseCode = getRestTestHelper().submitRequest("port/" + portName, "DELETE");
- assertEquals("Port deletion should be allowed", 200, responseCode);
-
- assertPortDoesNotExist(portName);
- }
-
-
- public void testSetPortAttributesDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String portName = getTestName();
-
- int responseCode = createPort(portName);
- assertEquals("Port creation should be allowed", 201, responseCode);
-
- assertPortExists(portName);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(Port.NAME, portName);
- attributes.put(Port.PROTOCOLS, Arrays.asList(Protocol.AMQP_0_9));
- attributes.put(Port.AUTHENTICATION_PROVIDER, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER);
- responseCode = getRestTestHelper().submitRequest("port/" + portName, "PUT", attributes);
- assertEquals("Setting of port attribites should be denied", 403, responseCode);
-
- Map<String, Object> port = getRestTestHelper().getJsonAsMap("port/" + portName);
- assertEquals("Unexpected authentication provider attribute value",
- TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER, port.get(Port.AUTHENTICATION_PROVIDER));
- }
-
- /* === KeyStore === */
-
- public void testCreateKeyStoreAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String keyStoreName = getTestName();
-
- assertKeyStoreExistence(keyStoreName, false);
-
- int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1);
- assertEquals("keyStore creation should be allowed", 201, responseCode);
-
- assertKeyStoreExistence(keyStoreName, true);
- }
-
- public void testCreateKeyStoreDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- String keyStoreName = getTestName();
-
- assertKeyStoreExistence(keyStoreName, false);
-
- int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1);
- assertEquals("keyStore creation should be allowed", 403, responseCode);
-
- assertKeyStoreExistence(keyStoreName, false);
- }
-
- public void testDeleteKeyStoreDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String keyStoreName = getTestName();
-
- assertKeyStoreExistence(keyStoreName, false);
-
- int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1);
- assertEquals("keyStore creation should be allowed", 201, responseCode);
-
- assertKeyStoreExistence(keyStoreName, true);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "DELETE");
- assertEquals("keystore deletion should be denied", 403, responseCode);
-
- assertKeyStoreExistence(keyStoreName, true);
- }
-
- public void testDeleteKeyStoreAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String keyStoreName = getTestName();
-
- assertKeyStoreExistence(keyStoreName, false);
-
- int responseCode = createKeyStore(keyStoreName, TestSSLConstants.CERT_ALIAS_APP1);
- assertEquals("keyStore creation should be allowed", 201, responseCode);
-
- assertKeyStoreExistence(keyStoreName, true);
-
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "DELETE");
- assertEquals("keystore deletion should be allowed", 200, responseCode);
-
- assertKeyStoreExistence(keyStoreName, false);
- }
-
- public void testSetKeyStoreAttributesAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String keyStoreName = getTestName();
- String initialCertAlias = TestSSLConstants.CERT_ALIAS_APP1;
- String updatedCertAlias = TestSSLConstants.CERT_ALIAS_APP2;
-
- assertKeyStoreExistence(keyStoreName, false);
-
- int responseCode = createKeyStore(keyStoreName, initialCertAlias);
- assertEquals("keyStore creation should be allowed", 201, responseCode);
-
- assertKeyStoreExistence(keyStoreName, true);
- Map<String, Object> keyStore = getRestTestHelper().getJsonAsMap("keystore/" + keyStoreName);
- assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS));
-
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(KeyStore.NAME, keyStoreName);
- attributes.put(FileKeyStore.CERTIFICATE_ALIAS, updatedCertAlias);
- responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "PUT", attributes);
- assertEquals("Setting of keystore attributes should be allowed", 200, responseCode);
-
- keyStore = getRestTestHelper().getJsonAsMap("keystore/" + keyStoreName);
- assertEquals("Unexpected certificateAlias attribute value", updatedCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS));
- }
-
- public void testSetKeyStoreAttributesDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String keyStoreName = getTestName();
- String initialCertAlias = TestSSLConstants.CERT_ALIAS_APP1;
- String updatedCertAlias = TestSSLConstants.CERT_ALIAS_APP2;
-
- assertKeyStoreExistence(keyStoreName, false);
-
- int responseCode = createKeyStore(keyStoreName, initialCertAlias);
- assertEquals("keyStore creation should be allowed", 201, responseCode);
-
- assertKeyStoreExistence(keyStoreName, true);
- Map<String, Object> keyStore = getRestTestHelper().getJsonAsMap("keystore/" + keyStoreName);
- assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS));
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(KeyStore.NAME, keyStoreName);
- attributes.put(FileKeyStore.CERTIFICATE_ALIAS, updatedCertAlias);
- responseCode = getRestTestHelper().submitRequest("keystore/" + keyStoreName, "PUT", attributes);
- assertEquals("Setting of keystore attributes should be denied", 403, responseCode);
-
- keyStore = getRestTestHelper().getJsonAsMap("keystore/" + keyStoreName);
- assertEquals("Unexpected certificateAlias attribute value", initialCertAlias, keyStore.get(FileKeyStore.CERTIFICATE_ALIAS));
- }
-
- /* === TrustStore === */
-
- public void testCreateTrustStoreAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String trustStoreName = getTestName();
-
- assertTrustStoreExistence(trustStoreName, false);
-
- int responseCode = createTrustStore(trustStoreName, false);
- assertEquals("trustStore creation should be allowed", 201, responseCode);
-
- assertTrustStoreExistence(trustStoreName, true);
- }
-
- public void testCreateTrustStoreDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- String trustStoreName = getTestName();
-
- assertTrustStoreExistence(trustStoreName, false);
-
- int responseCode = createTrustStore(trustStoreName, false);
- assertEquals("trustStore creation should be allowed", 403, responseCode);
-
- assertTrustStoreExistence(trustStoreName, false);
- }
-
- public void testDeleteTrustStoreDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String trustStoreName = getTestName();
-
- assertTrustStoreExistence(trustStoreName, false);
-
- int responseCode = createTrustStore(trustStoreName, false);
- assertEquals("trustStore creation should be allowed", 201, responseCode);
-
- assertTrustStoreExistence(trustStoreName, true);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "DELETE");
- assertEquals("truststore deletion should be denied", 403, responseCode);
-
- assertTrustStoreExistence(trustStoreName, true);
- }
-
- public void testDeleteTrustStoreAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String trustStoreName = getTestName();
-
- assertTrustStoreExistence(trustStoreName, false);
-
- int responseCode = createTrustStore(trustStoreName, false);
- assertEquals("trustStore creation should be allowed", 201, responseCode);
-
- assertTrustStoreExistence(trustStoreName, true);
-
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "DELETE");
- assertEquals("truststore deletion should be allowed", 200, responseCode);
-
- assertTrustStoreExistence(trustStoreName, false);
- }
-
- public void testSetTrustStoreAttributesAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String trustStoreName = getTestName();
- boolean initialPeersOnly = false;
- boolean updatedPeersOnly = true;
-
- assertTrustStoreExistence(trustStoreName, false);
-
- int responseCode = createTrustStore(trustStoreName, initialPeersOnly);
- assertEquals("trustStore creation should be allowed", 201, responseCode);
-
- assertTrustStoreExistence(trustStoreName, true);
- Map<String, Object> trustStore = getRestTestHelper().getJsonAsMap("truststore/" + trustStoreName);
- assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY));
-
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(TrustStore.NAME, trustStoreName);
- attributes.put(FileTrustStore.PEERS_ONLY, updatedPeersOnly);
- responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "PUT", attributes);
- assertEquals("Setting of truststore attributes should be allowed", 200, responseCode);
-
- trustStore = getRestTestHelper().getJsonAsMap("truststore/" + trustStoreName);
- assertEquals("Unexpected peersOnly attribute value", updatedPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY));
- }
-
- public void testSetTrustStoreAttributesDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String trustStoreName = getTestName();
- boolean initialPeersOnly = false;
- boolean updatedPeersOnly = true;
-
- assertTrustStoreExistence(trustStoreName, false);
-
- int responseCode = createTrustStore(trustStoreName, initialPeersOnly);
- assertEquals("trustStore creation should be allowed", 201, responseCode);
-
- assertTrustStoreExistence(trustStoreName, true);
- Map<String, Object> trustStore = getRestTestHelper().getJsonAsMap("truststore/" + trustStoreName);
- assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY));
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(TrustStore.NAME, trustStoreName);
- attributes.put(FileTrustStore.PEERS_ONLY, updatedPeersOnly);
- responseCode = getRestTestHelper().submitRequest("truststore/" + trustStoreName, "PUT", attributes);
- assertEquals("Setting of truststore attributes should be denied", 403, responseCode);
-
- trustStore = getRestTestHelper().getJsonAsMap("truststore/" + trustStoreName);
- assertEquals("Unexpected peersOnly attribute value", initialPeersOnly, trustStore.get(FileTrustStore.PEERS_ONLY));
- }
-
- /* === Broker === */
-
- public void testSetBrokerAttributesAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- Map<String, Object> brokerAttributes = getRestTestHelper().getJsonAsMap("broker");
- assertEquals("Unexpected description", null,
- brokerAttributes.get(Broker.DESCRIPTION));
-
- String descriptionValue = "test description";
-
- getRestTestHelper().submitRequest("broker",
- "PUT",
- Collections.singletonMap(Broker.DESCRIPTION, descriptionValue),
- 200);
-
- brokerAttributes = getRestTestHelper().getJsonAsMap("broker");
- assertEquals("Unexpected description", descriptionValue,
- brokerAttributes.get(Broker.DESCRIPTION));
- }
-
- public void testSetBrokerAttributesDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- Map<String, Object> brokerAttributes = getRestTestHelper().getJsonAsMap("broker");
- assertEquals("Unexpected description", null, brokerAttributes.get(Broker.DESCRIPTION));
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- getRestTestHelper().submitRequest("broker",
- "PUT",
- Collections.singletonMap(Broker.DESCRIPTION, "test description"),
- 403);
-
- brokerAttributes = getRestTestHelper().getJsonAsMap("broker");
- assertEquals("Unexpected description", null, brokerAttributes.get(Broker.DESCRIPTION));
- }
-
- /* === GroupProvider === */
-
- public void testCreateGroupProviderAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String groupProviderName = getTestName();
-
- assertGroupProviderExistence(groupProviderName, false);
-
- int responseCode = createGroupProvider(groupProviderName);
- assertEquals("Group provider creation should be allowed", 201, responseCode);
-
- assertGroupProviderExistence(groupProviderName, true);
- }
-
- public void testCreateGroupProviderDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- String groupProviderName = getTestName();
-
- assertGroupProviderExistence(groupProviderName, false);
-
- int responseCode = createGroupProvider(groupProviderName);
- assertEquals("Group provider creation should be denied", 403, responseCode);
-
- assertGroupProviderExistence(groupProviderName, false);
- }
-
- public void testDeleteGroupProviderDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String groupProviderName = getTestName();
-
- assertGroupProviderExistence(groupProviderName, false);
-
- int responseCode = createGroupProvider(groupProviderName);
- assertEquals("Group provider creation should be allowed", 201, responseCode);
-
- assertGroupProviderExistence(groupProviderName, true);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "DELETE");
- assertEquals("Group provider deletion should be denied", 403, responseCode);
-
- assertGroupProviderExistence(groupProviderName, true);
- }
-
- public void testDeleteGroupProviderAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String groupProviderName = getTestName();
-
- assertGroupProviderExistence(groupProviderName, false);
-
- int responseCode = createGroupProvider(groupProviderName);
- assertEquals("Group provider creation should be allowed", 201, responseCode);
-
- assertGroupProviderExistence(groupProviderName, true);
-
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "DELETE");
- assertEquals("Group provider deletion should be allowed", 200, responseCode);
-
- assertGroupProviderExistence(groupProviderName, false);
- }
-
- public void testSetGroupProviderAttributesAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String groupProviderName = getTestName();
-
- assertGroupProviderExistence(groupProviderName, false);
-
- int responseCode = createGroupProvider(groupProviderName);
- assertEquals("Group provider creation should be allowed", 201, responseCode);
-
- assertGroupProviderExistence(groupProviderName, true);
-
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(GroupProvider.NAME, groupProviderName);
- attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE);
- attributes.put(FileBasedGroupProvider.PATH, "/path/to/file");
- responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes);
- assertEquals("Setting of group provider attributes should be allowed but not supported", AbstractServlet.SC_UNPROCESSABLE_ENTITY, responseCode);
- }
-
- public void testSetGroupProviderAttributesDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String groupProviderName = getTestName();
-
- assertGroupProviderExistence(groupProviderName, false);
-
- int responseCode = createGroupProvider(groupProviderName);
- assertEquals("Group provider creation should be allowed", 201, responseCode);
-
- assertGroupProviderExistence(groupProviderName, true);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(GroupProvider.NAME, groupProviderName);
- attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE);
- attributes.put(FileBasedGroupProvider.PATH, "/path/to/file");
- responseCode = getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes);
- assertEquals("Setting of group provider attributes should be denied", 403, responseCode);
- }
-
- /* === AccessControlProvider === */
-
-
- public void testCreateAccessControlProviderDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- String accessControlProviderName = getTestName();
-
- assertAccessControlProviderExistence(accessControlProviderName, false);
-
- int responseCode = createAccessControlProvider(accessControlProviderName);
- assertEquals("Access control provider creation should be denied", 403, responseCode);
-
- assertAccessControlProviderExistence(accessControlProviderName, false);
- }
-
- public void testDeleteAccessControlProviderDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE;
-
- assertAccessControlProviderExistence(accessControlProviderName, true);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE");
- assertEquals("Access control provider deletion should be denied", 403, responseCode);
-
- assertAccessControlProviderExistence(accessControlProviderName, true);
- }
-
- public void testDeleteAccessControlProviderAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE;
-
-
- assertAccessControlProviderExistence(accessControlProviderName, true);
- // add a second, low priority AllowAll provider
- Map<String,Object> attributes = new HashMap<>();
- final String secondProviderName = "AllowAll";
- attributes.put(ConfiguredObject.NAME, secondProviderName);
- attributes.put(ConfiguredObject.TYPE, AllowAllAccessControlProvider.ALLOW_ALL);
- attributes.put(AccessControlProvider.PRIORITY, 9999);
- int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + secondProviderName, "PUT", attributes);
- assertEquals("Access control provider creation should be allowed", 201, responseCode);
-
- responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE");
- assertEquals("Access control provider deletion should be allowed", 200, responseCode);
-
- assertAccessControlProviderExistence(accessControlProviderName, false);
- }
-
- public void testSetAccessControlProviderAttributesAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE;
-
- assertAccessControlProviderExistence(accessControlProviderName, true);
-
- File aclFile = TestFileUtils.createTempFile(this, ".acl", "ACL ALLOW all all");
-
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(AccessControlProvider.NAME, accessControlProviderName);
- attributes.put(FileBasedGroupProvider.PATH, aclFile.getAbsolutePath());
- int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes);
- assertEquals("Setting of access control provider attributes should be allowed", 200, responseCode);
- }
-
- public void testSetAccessControlProviderAttributesDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String accessControlProviderName = TestBrokerConfiguration.ENTRY_NAME_ACL_FILE;
-
- assertAccessControlProviderExistence(accessControlProviderName, true);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(GroupProvider.NAME, accessControlProviderName);
- attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE);
- attributes.put(FileBasedGroupProvider.PATH, "/path/to/file");
- int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes);
- assertEquals("Setting of access control provider attributes should be denied", 403, responseCode);
- }
-
- /* === HTTP management === */
-
- public void testSetHttpManagementAttributesAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(HttpManagement.NAME, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT);
- attributes.put(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED, false);
- attributes.put(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED, false);
- attributes.put(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED, false);
- attributes.put(HttpManagement.TIME_OUT, 10000);
-
- int responseCode = getRestTestHelper().submitRequest(
- "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, "PUT", attributes);
- assertEquals("Setting of http management should be allowed", 200, responseCode);
-
- Map<String, Object> details =
- getRestTestHelper().getJsonAsMap("plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT);
-
- assertEquals("Unexpected session timeout", 10000, details.get(HttpManagement.TIME_OUT));
- assertEquals("Unexpected http basic auth enabled", true, details.get(HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED));
- assertEquals("Unexpected https basic auth enabled", false, details.get(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED));
- assertEquals("Unexpected http sasl auth enabled", false, details.get(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED));
- assertEquals("Unexpected https sasl auth enabled", false, details.get(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED));
- }
-
- public void testSetHttpManagementAttributesDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(HttpManagement.NAME, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT);
- attributes.put(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED, false);
- attributes.put(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED, false);
- attributes.put(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED, false);
- attributes.put(HttpManagement.TIME_OUT, 10000);
-
- int responseCode = getRestTestHelper().submitRequest(
- "plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, "PUT", attributes);
- assertEquals("Setting of http management should be denied", 403, responseCode);
-
- Map<String, Object> details =
- getRestTestHelper().getJsonAsMap("plugin/" + TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT);
-
- assertEquals("Unexpected session timeout", HttpManagement.DEFAULT_TIMEOUT_IN_SECONDS,
- details.get(HttpManagement.TIME_OUT));
- assertEquals("Unexpected http basic auth enabled", true,
- details.get(HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED));
- assertEquals("Unexpected https basic auth enabled", true,
- details.get(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED));
- assertEquals("Unexpected http sasl auth enabled", true,
- details.get(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED));
- assertEquals("Unexpected https sasl auth enabled", true,
- details.get(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED));
- }
-
- /* === Broker Logger === */
-
- public void testCreateBrokerLoggerAllowedDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(BrokerLogger.NAME, "testLogger1");
- attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE);
-
- getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED);
- getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "testLogger2");
- getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN);
- getRestTestHelper().submitRequest("brokerlogger/testLogger2", "GET", HttpServletResponse.SC_NOT_FOUND);
- }
-
- public void testDeleteBrokerLoggerAllowedDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(BrokerLogger.NAME, "testLogger1");
- attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE);
-
- getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED);
- getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- getRestTestHelper().submitRequest("brokerlogger/testLogger1", "DELETE", null, HttpServletResponse.SC_FORBIDDEN);
- getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_OK);
-
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
- getRestTestHelper().submitRequest("brokerlogger/testLogger1", "DELETE", null, HttpServletResponse.SC_OK);
- getRestTestHelper().submitRequest("brokerlogger/testLogger1", "GET", HttpServletResponse.SC_NOT_FOUND);
- }
-
- public void testDownloadBrokerLoggerFileAllowedDenied() throws Exception
- {
- final String loggerName = "testFileLogger";
- final String loggerPath = "brokerlogger/" + loggerName;
-
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(BrokerLogger.NAME, loggerName);
- attributes.put(ConfiguredObject.TYPE, BrokerFileLogger.TYPE);
- getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED);
-
- getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_OK);
- getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_OK);
- getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_OK);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- getRestTestHelper().submitRequest(loggerPath + "/getFile?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN);
- getRestTestHelper().submitRequest(loggerPath + "/getFiles?fileName=qpid.log", "GET", HttpServletResponse.SC_FORBIDDEN);
- getRestTestHelper().submitRequest(loggerPath + "/getAllFiles", "GET", HttpServletResponse.SC_FORBIDDEN);
- }
-
- public void testViewMemoryLoggerEntriesAllowedDenied() throws Exception
- {
- final String loggerName = "testMemoryLogger";
- final String loggerPath = "brokerlogger/" + loggerName;
-
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(BrokerLogger.NAME, loggerName);
- attributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE);
- getRestTestHelper().submitRequest("brokerlogger", "PUT", attributes, HttpServletResponse.SC_CREATED);
-
- getRestTestHelper().submitRequest(loggerPath + "/getLogEntries?lastLogId=0", "GET", HttpServletResponse.SC_OK);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- getRestTestHelper().submitRequest(loggerPath + "/getLogEntries?lastLogId=0", "GET", HttpServletResponse.SC_FORBIDDEN);
- }
-
- /* === Broker Log Inclusion Rules === */
-
- public void testCreateBrokerLoggerRuleAllowedDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- Map<String, Object> loggerAttributes = new HashMap<>();
- loggerAttributes.put(BrokerLogger.NAME, "testLogger1");
- loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE);
- getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED);
-
-
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1");
- attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE);
- attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG");
-
- getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_CREATED);
- getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule2");
- getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN);
- getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule2", "GET", HttpServletResponse.SC_NOT_FOUND);
- }
-
- public void testUpdateBrokerLoggerRuleAllowedDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- Map<String, Object> loggerAttributes = new HashMap<>();
- loggerAttributes.put(BrokerLogger.NAME, "testLogger1");
- loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE);
- getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED);
-
- Map<String, Object> ruleAttributes = new HashMap<>();
- ruleAttributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1");
- ruleAttributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE);
- ruleAttributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "INFO");
- getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", ruleAttributes, HttpServletResponse.SC_CREATED);
-
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1");
- attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE);
- attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG");
-
- getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "PUT", attributes, HttpServletResponse.SC_OK);
- Map<String,Object> resultAfterUpdate =
- getRestTestHelper().getJsonAsMap("brokerloginclusionrule/testLogger1/rule1");
- assertEquals("Log level was not changed", "DEBUG", resultAfterUpdate.get(BrokerNameAndLevelLogInclusionRule.LEVEL));
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "INFO");
- getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "PUT", attributes, HttpServletResponse.SC_FORBIDDEN);
-
- Map<String,Object> resultAfterDeniedUpdate =
- getRestTestHelper().getJsonAsMap("brokerloginclusionrule/testLogger1/rule1");
- assertEquals("Log level was changed by not allowed user", "DEBUG", resultAfterDeniedUpdate.get(BrokerNameAndLevelLogInclusionRule.LEVEL));
- }
-
- public void testDeleteBrokerLoggerRuleAllowedDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- Map<String, Object> loggerAttributes = new HashMap<>();
- loggerAttributes.put(BrokerLogger.NAME, "testLogger1");
- loggerAttributes.put(ConfiguredObject.TYPE, BrokerMemoryLogger.TYPE);
- getRestTestHelper().submitRequest("brokerlogger", "PUT", loggerAttributes, HttpServletResponse.SC_CREATED);
-
-
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(BrokerNameAndLevelLogInclusionRule.NAME, "rule1");
- attributes.put(ConfiguredObject.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE);
- attributes.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG");
-
- getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1", "PUT", attributes, HttpServletResponse.SC_CREATED);
- getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "DELETE", null, HttpServletResponse.SC_FORBIDDEN);
- getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_OK);
-
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
- getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "DELETE", null, HttpServletResponse.SC_OK);
- getRestTestHelper().submitRequest("brokerloginclusionrule/testLogger1/rule1", "GET", HttpServletResponse.SC_NOT_FOUND);
- }
-
- /* === Utility Methods === */
-
- private int createPort(String portName) throws Exception
- {
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(Port.NAME, portName);
- attributes.put(Port.PORT, 0);
- attributes.put(Port.AUTHENTICATION_PROVIDER, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER);
-
- return getRestTestHelper().submitRequest("port/" + portName, "PUT", attributes);
- }
-
- private void assertPortExists(String portName) throws Exception
- {
- assertPortExistence(portName, true);
- }
-
- private void assertPortDoesNotExist(String portName) throws Exception
- {
- assertPortExistence(portName, false);
- }
-
- private void assertPortExistence(String portName, boolean exists) throws Exception
- {
- String path = "port/" + portName;
- int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND;
- getRestTestHelper().submitRequest(path, "GET", expectedResponseCode);
-
- }
-
- private void assertKeyStoreExistence(String keyStoreName, boolean exists) throws Exception
- {
- String path = "keystore/" + keyStoreName;
- int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND;
- getRestTestHelper().submitRequest(path, "GET", expectedResponseCode);
- }
-
- private void assertTrustStoreExistence(String trustStoreName, boolean exists) throws Exception
- {
- String path = "truststore/" + trustStoreName;
- int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND;
- getRestTestHelper().submitRequest(path, "GET", expectedResponseCode);
- }
-
- private int createAuthenticationProvider(String authenticationProviderName) throws Exception
- {
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(AuthenticationProvider.NAME, authenticationProviderName);
- attributes.put(AuthenticationProvider.TYPE, AnonymousAuthenticationManager.PROVIDER_TYPE);
-
- return getRestTestHelper().submitRequest("authenticationprovider/" + authenticationProviderName, "PUT", attributes);
- }
-
- private void assertAuthenticationProviderDoesNotExist(String authenticationProviderName) throws Exception
- {
- assertAuthenticationProviderExistence(authenticationProviderName, false);
- }
-
- private void assertAuthenticationProviderExists(String authenticationProviderName) throws Exception
- {
- assertAuthenticationProviderExistence(authenticationProviderName, true);
- }
-
- private void assertAuthenticationProviderExistence(String authenticationProviderName, boolean exists) throws Exception
- {
- String path = "authenticationprovider/" + authenticationProviderName;
- int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND;
- getRestTestHelper().submitRequest(path, "GET", expectedResponseCode);
- }
-
- private int createKeyStore(String name, String certAlias) throws IOException
- {
- Map<String, Object> keyStoreAttributes = new HashMap<String, Object>();
- keyStoreAttributes.put(KeyStore.NAME, name);
- keyStoreAttributes.put(FileKeyStore.STORE_URL, TestSSLConstants.KEYSTORE);
- keyStoreAttributes.put(FileKeyStore.PASSWORD, TestSSLConstants.KEYSTORE_PASSWORD);
- keyStoreAttributes.put(FileKeyStore.CERTIFICATE_ALIAS, certAlias);
-
- return getRestTestHelper().submitRequest("keystore/" + name, "PUT", keyStoreAttributes);
- }
-
- private int createTrustStore(String name, boolean peersOnly) throws IOException
- {
- Map<String, Object> trustStoreAttributes = new HashMap<String, Object>();
- trustStoreAttributes.put(TrustStore.NAME, name);
- trustStoreAttributes.put(FileTrustStore.STORE_URL, TestSSLConstants.KEYSTORE);
- trustStoreAttributes.put(FileTrustStore.PASSWORD, TestSSLConstants.KEYSTORE_PASSWORD);
- trustStoreAttributes.put(FileTrustStore.PEERS_ONLY, peersOnly);
-
- return getRestTestHelper().submitRequest("truststore/" + name, "PUT", trustStoreAttributes);
- }
-
- private void assertGroupProviderExistence(String groupProviderName, boolean exists) throws Exception
- {
- String path = "groupprovider/" + groupProviderName;
- int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND;
- getRestTestHelper().submitRequest(path, "GET", expectedResponseCode);
- }
-
- private int createGroupProvider(String groupProviderName) throws Exception
- {
- File file = TestFileUtils.createTempFile(this, ".groups");
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(GroupProvider.NAME, groupProviderName);
- attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE);
- attributes.put(FileBasedGroupProvider.PATH, file.getAbsoluteFile());
-
- return getRestTestHelper().submitRequest("groupprovider/" + groupProviderName, "PUT", attributes);
- }
-
- private void assertAccessControlProviderExistence(String accessControlProviderName, boolean exists) throws Exception
- {
- String path = "accesscontrolprovider/" + accessControlProviderName;
- int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND;
- getRestTestHelper().submitRequest(path, "GET", expectedResponseCode);
- }
-
- private int createAccessControlProvider(String accessControlProviderName) throws Exception
- {
- File file = TestFileUtils.createTempFile(this, ".acl", _secondaryAclFileContent);
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(AccessControlProvider.NAME, accessControlProviderName);
- attributes.put(AccessControlProvider.TYPE, AclFileAccessControlProvider.ACL_FILE_PROVIDER_TYPE);
- attributes.put(AclFileAccessControlProvider.PATH, file.getAbsoluteFile());
-
- return getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes);
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/test/java/org/apache/qpid/systest/rest/acl/ExchangeRestACLTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/systest/rest/acl/ExchangeRestACLTest.java b/systests/src/test/java/org/apache/qpid/systest/rest/acl/ExchangeRestACLTest.java
deleted file mode 100644
index 41fdba2..0000000
--- a/systests/src/test/java/org/apache/qpid/systest/rest/acl/ExchangeRestACLTest.java
+++ /dev/null
@@ -1,317 +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.systest.rest.acl;
-
-import static org.apache.qpid.test.utils.TestUtils.writeACLFileUtil;
-import static org.apache.qpid.test.utils.TestBrokerConfiguration.ENTRY_NAME_ACL_FILE;
-
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.qpid.server.management.plugin.servlet.rest.AbstractServlet;
-import org.apache.qpid.server.model.AccessControlProvider;
-import org.apache.qpid.server.model.AlternateBinding;
-import org.apache.qpid.server.model.Exchange;
-import org.apache.qpid.server.model.Queue;
-import org.apache.qpid.systest.rest.QpidRestTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-
-public class ExchangeRestACLTest extends QpidRestTestCase
-{
- private static final String ALLOWED_USER = "user1";
- private static final String DENIED_USER = "user2";
- private static final String ADMIN = "ADMIN";
-
- private String _queueName;
- private String _exchangeName;
- private String _exchangeUrl;
- private String _aclFilePath;
-
- @Override
- protected void customizeConfiguration() throws Exception
- {
- super.customizeConfiguration();
- final TestBrokerConfiguration defaultBrokerConfiguration = getDefaultBrokerConfiguration();
- defaultBrokerConfiguration.configureTemporaryPasswordFile(ALLOWED_USER, DENIED_USER, ADMIN);
-
- _aclFilePath = writeACLFileUtil(this,
- "ACL ALLOW-LOG ALL ACCESS MANAGEMENT",
- "ACL ALLOW-LOG " + ALLOWED_USER + " CREATE QUEUE",
- "ACL ALLOW-LOG " + ALLOWED_USER + " CREATE EXCHANGE",
- "ACL DENY-LOG " + DENIED_USER + " CREATE EXCHANGE",
- "ACL ALLOW-LOG " + ALLOWED_USER + " UPDATE EXCHANGE",
- "ACL DENY-LOG " + DENIED_USER + " UPDATE EXCHANGE",
- "ACL ALLOW-LOG " + ALLOWED_USER + " DELETE EXCHANGE",
- "ACL DENY-LOG " + DENIED_USER + " DELETE EXCHANGE",
- "ACL ALLOW-LOG " + ALLOWED_USER + " BIND EXCHANGE",
- "ACL DENY-LOG " + DENIED_USER + " BIND EXCHANGE",
- "ACL ALLOW-LOG " + ALLOWED_USER + " UNBIND EXCHANGE",
- "ACL DENY-LOG " + DENIED_USER + " UNBIND EXCHANGE",
- "ACL ALLOW-LOG " + ADMIN + " ALL ALL",
- "ACL DENY-LOG ALL ALL");
- }
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- _queueName = getTestQueueName();
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
- Map<String, Object> queueData = new HashMap<String, Object>();
- queueData.put(Queue.NAME, _queueName);
- queueData.put(Queue.DURABLE, Boolean.TRUE);
- int status = getRestTestHelper().submitRequest("queue/test/test/" + _queueName, "PUT", queueData);
- assertEquals("Unexpected status", 201, status);
-
- _exchangeName = getTestName();
- _exchangeUrl = "exchange/test/test/" + _exchangeName;
- }
-
- public void testCreateExchangeAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- int responseCode = createExchange();
- assertEquals("Exchange creation should be allowed", 201, responseCode);
-
- assertExchangeExists();
- }
-
- public void testCreateExchangeDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- int responseCode = createExchange();
- assertEquals("Exchange creation should be denied", 403, responseCode);
-
- assertExchangeDoesNotExist();
- }
-
-
- public void testCreateExchangeAllowedAfterReload() throws Exception
- {
-
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- int responseCode = createExchange();
- assertEquals("Exchange creation should be denied", 403, responseCode);
-
- assertExchangeDoesNotExist();
-
- overwriteAclFile("ACL ALLOW-LOG ALL ACCESS MANAGEMENT",
- "ACL ALLOW-LOG " + ALLOWED_USER + " CREATE QUEUE",
- "ACL ALLOW-LOG " + ALLOWED_USER + " CREATE EXCHANGE",
- "ACL ALLOW-LOG " + DENIED_USER + " CREATE EXCHANGE",
- "ACL ALLOW-LOG " + ALLOWED_USER + " UPDATE EXCHANGE",
- "ACL DENY-LOG " + DENIED_USER + " UPDATE EXCHANGE",
- "ACL ALLOW-LOG " + ALLOWED_USER + " DELETE EXCHANGE",
- "ACL DENY-LOG " + DENIED_USER + " DELETE EXCHANGE",
- "ACL ALLOW-LOG " + ALLOWED_USER + " BIND EXCHANGE",
- "ACL DENY-LOG " + DENIED_USER + " BIND EXCHANGE",
- "ACL ALLOW-LOG " + ALLOWED_USER + " UNBIND EXCHANGE",
- "ACL DENY-LOG " + DENIED_USER + " UNBIND EXCHANGE",
- "ACL ALLOW-LOG " + ADMIN + " ALL ALL",
- "ACL DENY-LOG ALL ALL");
- getRestTestHelper().setUsernameAndPassword(ADMIN, ADMIN);
- getRestTestHelper().submitRequest("/api/latest/"
- + AccessControlProvider.class.getSimpleName().toLowerCase()
- + "/" + ENTRY_NAME_ACL_FILE + "/reload", "POST", Collections.emptyMap(), 200);
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- responseCode = createExchange();
- assertEquals("Exchange creation should be allowed", 201, responseCode);
-
- assertExchangeExists();
-
- }
-
- private void overwriteAclFile(final String... rules) throws IOException
- {
- try(FileWriter fw = new FileWriter(_aclFilePath); PrintWriter out = new PrintWriter(fw))
- {
- for(String line :rules)
- {
- out.println(line);
- }
- }
- }
-
- public void testDeleteExchangeAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- int responseCode = createExchange();
- assertEquals("Exchange creation should be allowed", 201, responseCode);
-
- assertExchangeExists();
-
-
- responseCode = getRestTestHelper().submitRequest(_exchangeUrl, "DELETE");
- assertEquals("Exchange deletion should be allowed", 200, responseCode);
-
- assertExchangeDoesNotExist();
- }
-
- public void testDeleteExchangeDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- int responseCode = createExchange();
- assertEquals("Exchange creation should be allowed", 201, responseCode);
-
- assertExchangeExists();
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- responseCode = getRestTestHelper().submitRequest(_exchangeUrl, "DELETE");
- assertEquals("Exchange deletion should be denied", 403, responseCode);
-
- assertExchangeExists();
- }
-
- public void testSetExchangeAttributesAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- createExchange();
-
- assertExchangeExists();
-
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(Exchange.NAME, _exchangeName);
- attributes.put(Exchange.ALTERNATE_BINDING,
- Collections.singletonMap(AlternateBinding.DESTINATION, "my-alternate-exchange"));
-
- getRestTestHelper().submitRequest(_exchangeUrl, "PUT", attributes, AbstractServlet.SC_UNPROCESSABLE_ENTITY);
- }
-
- public void testSetExchangeAttributesDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- createExchange();
- assertExchangeExists();
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(Exchange.NAME, _exchangeName);
- attributes.put(Exchange.ALTERNATE_BINDING,
- Collections.singletonMap(AlternateBinding.DESTINATION, "my-alternate-exchange"));
-
- getRestTestHelper().submitRequest(_exchangeUrl, "PUT", attributes, 403);
- }
-
- public void testBindToExchangeAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- String bindingName = getTestName();
- int responseCode = createBinding(bindingName);
- assertEquals("Binding creation should be allowed", 200, responseCode);
-
- assertBindingExists(bindingName);
- }
-
- public void testBindToExchangeDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- String bindingName = getTestName();
- int responseCode = createBinding(bindingName);
- assertEquals("Binding creation should be denied", 403, responseCode);
-
- assertBindingDoesNotExist(bindingName);
- }
-
- private int createExchange() throws Exception
- {
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(Exchange.NAME, _exchangeName);
- attributes.put(Exchange.TYPE, "direct");
- return getRestTestHelper().submitRequest(_exchangeUrl, "PUT", attributes);
- }
-
- private void assertExchangeDoesNotExist() throws Exception
- {
- assertExchangeExistence(false);
- }
-
- private void assertExchangeExists() throws Exception
- {
- assertExchangeExistence(true);
- }
-
- private void assertExchangeExistence(boolean exists) throws Exception
- {
- int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND;
- getRestTestHelper().submitRequest(_exchangeUrl, "GET", expectedResponseCode);
- }
-
- private int createBinding(String bindingName) throws IOException
- {
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put("bindingKey", bindingName);
- attributes.put("destination", _queueName);
-
- int responseCode = getRestTestHelper().submitRequest("exchange/test/test/amq.direct/bind", "POST", attributes);
- return responseCode;
- }
-
- private void assertBindingDoesNotExist(String bindingName) throws Exception
- {
- assertBindingExistence(bindingName, false);
- }
-
- private void assertBindingExists(String bindingName) throws Exception
- {
- assertBindingExistence(bindingName, true);
- }
-
- private void assertBindingExistence(String bindingName, boolean exists) throws Exception
- {
- String path = "exchange/test/test/amq.direct";
-
- final Map<String, Object> exch = getRestTestHelper().getJsonAsMap(path);
- final Collection<Map<String, Object>> bindings = (Collection<Map<String, Object>>) exch.get("bindings");
- boolean found = false;
- if (bindings != null)
- {
- for(Map<String, Object> binding : bindings)
- {
- if (bindingName.equals(binding.get("bindingKey")))
- {
- found = true;
- break;
- }
- }
- }
-
- assertEquals(exists, found);
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/test/java/org/apache/qpid/systest/rest/acl/GroupRestACLTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/systest/rest/acl/GroupRestACLTest.java b/systests/src/test/java/org/apache/qpid/systest/rest/acl/GroupRestACLTest.java
deleted file mode 100644
index 70954c5..0000000
--- a/systests/src/test/java/org/apache/qpid/systest/rest/acl/GroupRestACLTest.java
+++ /dev/null
@@ -1,201 +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.systest.rest.acl;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.Map;
-import java.util.Properties;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.qpid.server.management.plugin.HttpManagement;
-import org.apache.qpid.server.model.Plugin;
-import org.apache.qpid.systest.rest.QpidRestTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-import org.apache.qpid.test.utils.TestUtils;
-
-public class GroupRestACLTest extends QpidRestTestCase
-{
- private static final String FILE_GROUP_MANAGER = TestBrokerConfiguration.ENTRY_NAME_GROUP_FILE;
-
- private static final String ALLOWED_GROUP = "allowedGroup";
- private static final String DENIED_GROUP = "deniedGroup";
- private static final String OTHER_GROUP = "otherGroup";
-
- private static final String ALLOWED_USER = "webadmin";
- private static final String DENIED_USER = "admin";
- private static final String OTHER_USER = "admin";
-
- private File _groupFile;
-
- @Override
- public void startDefaultBroker() throws Exception
- {
- // tests will start the broker after configuring it
- }
-
- @Override
- protected void customizeConfiguration() throws Exception
- {
- super.customizeConfiguration();
- getDefaultBrokerConfiguration().setObjectAttribute(Plugin.class, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED, true);
- _groupFile = createTemporaryGroupFile();
- getDefaultBrokerConfiguration().addGroupFileConfiguration(_groupFile.getAbsolutePath());
- }
-
- @Override
- public void tearDown() throws Exception
- {
- super.tearDown();
-
- if (_groupFile != null)
- {
- if (_groupFile.exists())
- {
- _groupFile.delete();
- }
- }
- }
-
- private File createTemporaryGroupFile() throws Exception
- {
- File groupFile = File.createTempFile("group", "grp");
- groupFile.deleteOnExit();
-
- Properties props = new Properties();
- props.put(ALLOWED_GROUP + ".users", ALLOWED_USER);
- props.put(DENIED_GROUP + ".users", DENIED_USER);
- props.put(OTHER_GROUP + ".users", OTHER_USER);
-
- try(final FileOutputStream out = new FileOutputStream(groupFile))
- {
- props.store(out, "test group file");
- }
-
- return groupFile;
- }
-
- public void testCreateGroup() throws Exception
- {
- TestUtils.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT",
- "ACL ALLOW-LOG " + ALLOWED_GROUP + " CREATE GROUP",
- "ACL DENY-LOG " + DENIED_GROUP + " CREATE GROUP");
-
- //Start the broker with the custom config
- super.startDefaultBroker();
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- Map<String, Object> data =
- getRestTestHelper().getJsonAsMap("groupprovider/" + FILE_GROUP_MANAGER + "?depth=1");
- getRestTestHelper().assertNumberOfGroups(data, 3);
-
- getRestTestHelper().createGroup("newGroup", FILE_GROUP_MANAGER);
-
- data = getRestTestHelper().getJsonAsMap("groupprovider/" + FILE_GROUP_MANAGER + "?depth=1");
- getRestTestHelper().assertNumberOfGroups(data, 4);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- getRestTestHelper().createGroup("anotherNewGroup", FILE_GROUP_MANAGER, HttpServletResponse.SC_FORBIDDEN);
-
- data = getRestTestHelper().getJsonAsMap("groupprovider/" + FILE_GROUP_MANAGER + "?depth=1");
- getRestTestHelper().assertNumberOfGroups(data, 4);
- }
-
- public void testDeleteGroup() throws Exception
- {
- TestUtils.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT",
- "ACL ALLOW-LOG " + ALLOWED_GROUP + " DELETE GROUP",
- "ACL DENY-LOG " + DENIED_GROUP + " DELETE GROUP");
-
- //Start the broker with the custom config
- super.startDefaultBroker();
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- Map<String, Object> data =
- getRestTestHelper().getJsonAsMap("groupprovider/" + FILE_GROUP_MANAGER + "?depth=1");
- getRestTestHelper().assertNumberOfGroups(data, 3);
-
- getRestTestHelper().removeGroup(OTHER_GROUP, FILE_GROUP_MANAGER, HttpServletResponse.SC_FORBIDDEN);
-
- data = getRestTestHelper().getJsonAsMap("groupprovider/" + FILE_GROUP_MANAGER + "?depth=1");
- getRestTestHelper().assertNumberOfGroups(data, 3);
-
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- getRestTestHelper().removeGroup(OTHER_GROUP, FILE_GROUP_MANAGER);
-
- data = getRestTestHelper().getJsonAsMap("groupprovider/" + FILE_GROUP_MANAGER + "?depth=1");
- getRestTestHelper().assertNumberOfGroups(data, 2);
- }
-
- public void testUpdateGroupAddMember() throws Exception
- {
- TestUtils.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT",
- "ACL ALLOW-LOG " + ALLOWED_GROUP + " UPDATE GROUP",
- "ACL DENY-LOG " + DENIED_GROUP + " UPDATE GROUP");
-
- //Start the broker with the custom config
- super.startDefaultBroker();
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- assertNumberOfGroupMembers(OTHER_GROUP, 1);
-
- getRestTestHelper().createNewGroupMember(FILE_GROUP_MANAGER, OTHER_GROUP, "newGroupMember", HttpServletResponse.SC_FORBIDDEN);
- assertNumberOfGroupMembers(OTHER_GROUP, 1);
-
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
- getRestTestHelper().createNewGroupMember(FILE_GROUP_MANAGER, OTHER_GROUP, "newGroupMember");
- assertNumberOfGroupMembers(OTHER_GROUP, 2);
- }
-
- public void testUpdateGroupDeleteMember() throws Exception
- {
- TestUtils.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT",
- "ACL ALLOW-LOG " + ALLOWED_GROUP + " UPDATE GROUP",
- "ACL DENY-LOG " + DENIED_GROUP + " UPDATE GROUP");
-
- //Start the broker with the custom config
- super.startDefaultBroker();
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- assertNumberOfGroupMembers(OTHER_GROUP, 1);
-
- getRestTestHelper().removeMemberFromGroup(FILE_GROUP_MANAGER, OTHER_GROUP, OTHER_USER, HttpServletResponse.SC_FORBIDDEN);
- assertNumberOfGroupMembers(OTHER_GROUP, 1);
-
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
- getRestTestHelper().removeMemberFromGroup(FILE_GROUP_MANAGER, OTHER_GROUP, OTHER_USER);
- assertNumberOfGroupMembers(OTHER_GROUP, 0);
- }
-
- private void assertNumberOfGroupMembers(String groupName, int expectedNumberOfMembers) throws IOException
- {
- Map<String, Object> group = getRestTestHelper().getJsonAsMap("group/"
- + FILE_GROUP_MANAGER
- + "/"
- + groupName
- + "?depth=1");
- getRestTestHelper().assertNumberOfGroupMembers(group, expectedNumberOfMembers);
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/test/java/org/apache/qpid/systest/rest/acl/QueueRestACLTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/systest/rest/acl/QueueRestACLTest.java b/systests/src/test/java/org/apache/qpid/systest/rest/acl/QueueRestACLTest.java
deleted file mode 100644
index e23b7d3..0000000
--- a/systests/src/test/java/org/apache/qpid/systest/rest/acl/QueueRestACLTest.java
+++ /dev/null
@@ -1,192 +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.systest.rest.acl;
-
-import static javax.servlet.http.HttpServletResponse.SC_CREATED;
-import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
-import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
-import static javax.servlet.http.HttpServletResponse.SC_OK;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.qpid.server.model.Queue;
-import org.apache.qpid.systest.rest.QpidRestTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-import org.apache.qpid.test.utils.TestUtils;
-
-public class QueueRestACLTest extends QpidRestTestCase
-{
- private static final String ALLOWED_USER = "user1";
- private static final String DENIED_USER = "user2";
- private String _queueUrl;
- private String _queueName;
-
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- _queueName = getTestName();
- _queueUrl = "queue/test/test/" + _queueName;
- }
-
- @Override
- protected void customizeConfiguration() throws Exception
- {
- super.customizeConfiguration();
- final TestBrokerConfiguration defaultBrokerConfiguration = getDefaultBrokerConfiguration();
- defaultBrokerConfiguration.configureTemporaryPasswordFile(ALLOWED_USER, DENIED_USER);
-
- TestUtils.writeACLFileUtil(this, "ACL ALLOW-LOG ALL ACCESS MANAGEMENT",
- "ACL ALLOW-LOG " + ALLOWED_USER + " CREATE QUEUE",
- "ACL DENY-LOG " + DENIED_USER + " CREATE QUEUE",
- "ACL ALLOW-LOG " + ALLOWED_USER + " UPDATE QUEUE",
- "ACL DENY-LOG " + DENIED_USER + " UPDATE QUEUE",
- "ACL ALLOW-LOG " + ALLOWED_USER + " DELETE QUEUE",
- "ACL DENY-LOG " + DENIED_USER + " DELETE QUEUE",
- "ACL ALLOW-LOG " + ALLOWED_USER + " INVOKE QUEUE method_name=\"clearQueue\"",
- "ACL ALLOW-LOG " + ALLOWED_USER + " INVOKE QUEUE method_name=\"get*\"",
- "ACL DENY-LOG ALL ALL");
-
- }
-
- public void testCreateQueueAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- createQueue(SC_CREATED);
-
- assertQueueExists();
- }
-
- public void testCreateQueueDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- createQueue(SC_FORBIDDEN);
-
- assertQueueDoesNotExist();
- }
-
- public void testDeleteQueueAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- createQueue(SC_CREATED);
-
- assertQueueExists();
-
- getRestTestHelper().submitRequest(_queueUrl, "DELETE", SC_OK);
-
- assertQueueDoesNotExist();
- }
-
- public void testDeleteQueueDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- createQueue(SC_CREATED);
-
- assertQueueExists();
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- getRestTestHelper().submitRequest(_queueUrl, "DELETE", SC_FORBIDDEN);
-
- assertQueueExists();
- }
-
-
-
- public void testSetQueueAttributesAllowed() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- createQueue(SC_CREATED);
-
- assertQueueExists();
-
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(Queue.NAME, _queueName);
- attributes.put(Queue.MAXIMUM_QUEUE_DEPTH_MESSAGES, 100000);
-
- getRestTestHelper().submitRequest(_queueUrl, "PUT", attributes, SC_OK);
-
- Map<String, Object> queueData = getRestTestHelper().getJsonAsMap(_queueUrl);
- assertEquals("Unexpected " + Queue.MAXIMUM_QUEUE_DEPTH_MESSAGES, 100000, queueData.get(Queue.MAXIMUM_QUEUE_DEPTH_MESSAGES));
- }
-
- public void testSetQueueAttributesDenied() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- createQueue(SC_CREATED);
- assertQueueExists();
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(Queue.NAME, _queueName);
- attributes.put(Queue.MAXIMUM_QUEUE_DEPTH_MESSAGES, 100000);
-
- getRestTestHelper().submitRequest(_queueUrl, "PUT", attributes, SC_FORBIDDEN);
-
- Map<String, Object> queueData = getRestTestHelper().getJsonAsMap(_queueUrl);
- assertEquals("Unexpected " + Queue.MAXIMUM_QUEUE_DEPTH_MESSAGES, -1, queueData.get(Queue.MAXIMUM_QUEUE_DEPTH_MESSAGES));
- }
-
- public void testInvokeQueueOperation() throws Exception
- {
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- createQueue(SC_CREATED);
-
- getRestTestHelper().submitRequest(_queueUrl + "/clearQueue", "POST", Collections.emptyMap(), SC_OK);
- getRestTestHelper().submitRequest(_queueUrl + "/getStatistics", "POST", Collections.emptyMap(), SC_OK);
-
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
-
- getRestTestHelper().submitRequest(_queueUrl + "/clearQueue", "POST", Collections.emptyMap(), SC_FORBIDDEN);
- }
-
- private void createQueue(final int expectedResponseCode) throws Exception
- {
- Map<String, Object> attributes = Collections.singletonMap(Queue.NAME, _queueName);
-
- getRestTestHelper().submitRequest(_queueUrl, "PUT", attributes, expectedResponseCode);
- }
-
- private void assertQueueDoesNotExist() throws Exception
- {
- assertQueueExistence(false);
- }
-
- private void assertQueueExists() throws Exception
- {
- assertQueueExistence(true);
- }
-
- private void assertQueueExistence(boolean exists) throws Exception
- {
- int expectedResponseCode = exists ? SC_OK : SC_NOT_FOUND;
- getRestTestHelper().submitRequest(_queueUrl, "GET", expectedResponseCode);
- }
-}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org
[8/8] qpid-broker-j git commit: NO-JIRA: [Broker-J] [System Tests]
Remove Rest ACL Tests
Posted by kw...@apache.org.
NO-JIRA: [Broker-J] [System Tests] Remove Rest ACL Tests
Project: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/commit/cec889db
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/cec889db
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/cec889db
Branch: refs/heads/master
Commit: cec889db6d0df6624d45a84fe5e23721a33c83f5
Parents: b21a8f5
Author: Keith Wall <kw...@apache.org>
Authored: Mon Mar 12 15:45:15 2018 +0000
Committer: Keith Wall <kw...@apache.org>
Committed: Mon Mar 12 16:24:18 2018 +0000
----------------------------------------------------------------------
.../org/apache/qpid/systest/rest/Asserts.java | 334 ------
.../org/apache/qpid/test/utils/TestUtils.java | 22 -
.../server/SupportedProtocolVersionsTest.java | 196 ---
.../server/queue/LiveQueueOperationsTest.java | 135 ---
.../rest/AccessControlProviderRestTest.java | 234 ----
.../qpid/systest/rest/ConnectionRestTest.java | 255 ----
.../qpid/systest/rest/SessionRestTest.java | 159 ---
.../qpid/systest/rest/acl/BrokerACLTest.java | 1129 ------------------
.../systest/rest/acl/ExchangeRestACLTest.java | 317 -----
.../qpid/systest/rest/acl/GroupRestACLTest.java | 201 ----
.../qpid/systest/rest/acl/QueueRestACLTest.java | 192 ---
.../qpid/systest/rest/acl/UserRestACLTest.java | 183 ---
.../systest/rest/acl/VirtualHostACLTest.java | 188 ---
...irtualHostAccessControlProviderRestTest.java | 287 -----
.../rest/acl/VirtualHostNodeACLTest.java | 125 --
.../test/utils/BrokerCommandHelperTest.java | 57 -
.../test/utils/SpawnedBrokerHolderTest.java | 38 -
17 files changed, 4052 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.java b/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.java
index c0cc77e..be0dd54 100644
--- a/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.java
+++ b/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.java
@@ -20,350 +20,16 @@
*/
package org.apache.qpid.systest.rest;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
import java.util.Map;
-import javax.jms.JMSException;
-
import junit.framework.TestCase;
-import org.apache.qpid.server.model.Broker;
-import org.apache.qpid.server.model.BrokerModel;
import org.apache.qpid.server.model.ConfiguredObject;
-import org.apache.qpid.server.model.Connection;
-import org.apache.qpid.server.model.Exchange;
-import org.apache.qpid.server.model.ExclusivityPolicy;
-import org.apache.qpid.server.model.LifetimePolicy;
-import org.apache.qpid.server.model.Port;
-import org.apache.qpid.server.model.Queue;
-import org.apache.qpid.server.model.State;
-import org.apache.qpid.server.model.VirtualHost;
-import org.apache.qpid.server.model.VirtualHostNode;
-import org.apache.qpid.server.queue.LastValueQueue;
-import org.apache.qpid.server.queue.PriorityQueue;
-import org.apache.qpid.server.queue.SortedQueue;
-import org.apache.qpid.server.virtualhost.QueueManagingVirtualHost;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
public class Asserts
{
public static final String STATISTICS_ATTRIBUTE = "statistics";
- public static void assertVirtualHostNode(final String nodeName, final Map<String, Object> node)
- {
- assertNotNull("Virtualhostnode " + nodeName + " data is not found", node);
- assertEquals("Unexpected value of attribute " + VirtualHostNode.NAME,
- nodeName,
- node.get(VirtualHostNode.NAME));
- }
-
- public static void assertVirtualHost(String virtualHostName, Map<String, Object> virtualHost)
- {
- assertNotNull("Virtualhost " + virtualHostName + " data are not found", virtualHost);
- assertAttributesPresent(virtualHost,
- BrokerModel.getInstance().getTypeRegistry().getAttributeNames(VirtualHost.class),
- ConfiguredObject.CREATED_BY,
- ConfiguredObject.CREATED_TIME,
- ConfiguredObject.LAST_UPDATED_BY,
- ConfiguredObject.LAST_UPDATED_TIME,
- ConfiguredObject.DESCRIPTION,
- ConfiguredObject.CONTEXT,
- ConfiguredObject.DESIRED_STATE,
- QueueManagingVirtualHost.ENABLED_CONNECTION_VALIDATORS,
- QueueManagingVirtualHost.DISABLED_CONNECTION_VALIDATORS,
- QueueManagingVirtualHost.GLOBAL_ADDRESS_DOMAINS,
- VirtualHost.TYPE,
- VirtualHost.PREFERENCE_STORE_ATTRIBUTES);
-
- assertEquals("Unexpected value of attribute " + VirtualHost.NAME,
- virtualHostName,
- virtualHost.get(VirtualHost.NAME));
- assertNotNull("Unexpected value of attribute " + VirtualHost.ID, virtualHost.get(VirtualHost.ID));
- assertEquals("Unexpected value of attribute " + VirtualHost.STATE, State.ACTIVE.name(),
- virtualHost.get(VirtualHost.STATE));
- assertEquals("Unexpected value of attribute " + VirtualHost.DURABLE, Boolean.TRUE,
- virtualHost.get(VirtualHost.DURABLE));
- assertEquals("Unexpected value of attribute " + VirtualHost.LIFETIME_POLICY, LifetimePolicy.PERMANENT.name(),
- virtualHost.get(VirtualHost.LIFETIME_POLICY));
-
- @SuppressWarnings("unchecked")
- Map<String, Object> statistics = (Map<String, Object>) virtualHost.get(STATISTICS_ATTRIBUTE);
- Asserts.assertAttributesPresent(statistics,
- "queueCount","exchangeCount","bytesIn","bytesOut","messagesIn", "messagesOut");
-
- }
-
- public static void assertQueue(String queueName, String queueType, Map<String, Object> queueData)
- {
- assertQueue(queueName, queueType, queueData, null);
- }
-
- public static void assertQueue(String queueName,
- String queueType,
- Map<String, Object> queueData,
- Map<String, Object> expectedAttributes)
- {
- assertNotNull("Queue " + queueName + " is not found!", queueData);
- Asserts.assertAttributesPresent(queueData,
- BrokerModel.getInstance().getTypeRegistry().getAttributeNames(Queue.class),
- Queue.CREATED_BY,
- Queue.CREATED_TIME,
- Queue.LAST_UPDATED_BY,
- Queue.LAST_UPDATED_TIME,
- Queue.TYPE,
- Queue.DESCRIPTION,
- Queue.ALTERNATE_BINDING,
- Queue.OWNER,
- Queue.NO_LOCAL,
- LastValueQueue.LVQ_KEY,
- SortedQueue.SORT_KEY,
- Queue.MESSAGE_GROUP_KEY_OVERRIDE,
- Queue.MESSAGE_GROUP_TYPE,
- PriorityQueue.PRIORITIES,
- ConfiguredObject.CONTEXT,
- ConfiguredObject.DESIRED_STATE,
- Queue.DEFAULT_FILTERS,
- Queue.ENSURE_NONDESTRUCTIVE_CONSUMERS,
- Queue.CREATING_LINK_INFO);
-
- assertEquals("Unexpected value of queue attribute " + Queue.NAME, queueName, queueData.get(Queue.NAME));
- assertNotNull("Unexpected value of queue attribute " + Queue.ID, queueData.get(Queue.ID));
- assertEquals("Unexpected value of queue attribute " + Queue.STATE,
- State.ACTIVE.name(),
- queueData.get(Queue.STATE));
- assertEquals("Unexpected value of queue attribute " + Queue.LIFETIME_POLICY, LifetimePolicy.PERMANENT.name(),
- queueData.get(Queue.LIFETIME_POLICY));
- assertEquals("Unexpected value of queue attribute " + Queue.TYPE,
- queueType,
- queueData.get(Queue.TYPE));
- if (expectedAttributes == null)
- {
- assertEquals("Unexpected value of queue attribute " + Queue.EXCLUSIVE,
- ExclusivityPolicy.NONE.name(), queueData.get(Queue.EXCLUSIVE));
- assertEquals("Unexpected value of queue attribute " + Queue.MAXIMUM_DELIVERY_ATTEMPTS, 0,
- queueData.get(Queue.MAXIMUM_DELIVERY_ATTEMPTS));
- assertEquals("Unexpected value of queue attribute " + Queue.MAXIMUM_QUEUE_DEPTH_MESSAGES, -1,
- queueData.get(Queue.MAXIMUM_QUEUE_DEPTH_MESSAGES));
- assertEquals("Unexpected value of queue attribute " + Queue.QUEUE_FLOW_STOPPED, Boolean.FALSE,
- queueData.get(Queue.QUEUE_FLOW_STOPPED));
- }
- else
- {
- for (Map.Entry<String, Object> attribute : expectedAttributes.entrySet())
- {
- assertEquals("Unexpected value of " + queueName + " queue attribute " + attribute.getKey(),
- attribute.getValue(), queueData.get(attribute.getKey()));
- }
- }
-
- assertNotNull("Unexpected value of queue attribute statistics", queueData.get(Asserts.STATISTICS_ATTRIBUTE));
- @SuppressWarnings("unchecked")
- Map<String, Object> statistics = (Map<String, Object>) queueData.get(Asserts.STATISTICS_ATTRIBUTE);
-
- Asserts.assertAttributesPresent(statistics,
- "bindingCount",
- "consumerCount",
- "consumerCountWithCredit",
- "persistentDequeuedBytes",
- "persistentDequeuedMessages",
- "persistentEnqueuedBytes",
- "persistentEnqueuedMessages",
- "queueDepthBytes",
- "queueDepthMessages",
- "totalDequeuedBytes",
- "totalDequeuedMessages",
- "totalEnqueuedBytes",
- "totalEnqueuedMessages",
- "unacknowledgedBytes",
- "unacknowledgedMessages");
- }
-
- public static void assertAttributesPresent(Map<String, Object> data, String... attributes)
- {
- for (String name : attributes)
- {
- assertNotNull("Attribute " + name + " is not present", data.get(name));
- }
- }
-
- public static void assertAttributesPresent(Map<String, Object> data, Collection<String> attributes,
- String... unsupportedAttributes)
- {
- for (String name : attributes)
- {
- boolean unsupported = false;
- for (String unsupportedAttribute : unsupportedAttributes)
- {
- if (unsupportedAttribute.equals(name))
- {
- unsupported = true;
- break;
- }
- }
- if (unsupported)
- {
- continue;
- }
- assertNotNull("Attribute " + name + " is not present", data.get(name));
- }
- }
-
- public static void assertConnection(Map<String, Object> connectionData, final int sessions)
- throws JMSException
- {
- assertNotNull("Unexpected connection data", connectionData);
- assertAttributesPresent(connectionData,
- BrokerModel.getInstance().getTypeRegistry().getAttributeNames(Connection.class),
- Connection.STATE,
- Connection.DURABLE,
- Connection.LIFETIME_POLICY,
- Connection.INCOMING,
- Connection.REMOTE_PROCESS_NAME,
- Connection.REMOTE_PROCESS_PID,
- Connection.LOCAL_ADDRESS,
- Connection.PROPERTIES,
- ConfiguredObject.TYPE,
- ConfiguredObject.CREATED_BY,
- ConfiguredObject.CREATED_TIME,
- ConfiguredObject.LAST_UPDATED_BY,
- ConfiguredObject.LAST_UPDATED_TIME,
- ConfiguredObject.DESCRIPTION,
- ConfiguredObject.CONTEXT,
- ConfiguredObject.DESIRED_STATE);
-
- assertEquals("Unexpected value for connection attribute " + Connection.PORT,
- TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT, connectionData.get(Connection.PORT));
- assertEquals("Unexpected value of connection attribute " + Connection.PRINCIPAL, "guest",
- connectionData.get(Connection.PRINCIPAL));
-
- @SuppressWarnings("unchecked")
- Map<String, Object> statistics = (Map<String, Object>) connectionData.get(STATISTICS_ATTRIBUTE);
-
-
- assertAttributesPresent(statistics,
- "bytesIn",
- "bytesOut",
- "lastIoTime",
- "messagesIn",
- "messagesOut",
- "sessionCount");
- assertEquals("Unexpected value of connection statistics attribute sessionCount ", sessions,
- statistics.get("sessionCount"));
- }
-
- public static void assertPortAttributes(Map<String, Object> port)
- {
- assertPortAttributes(port, State.ACTIVE);
- }
-
- public static void assertPortAttributes(Map<String, Object> port, State state)
- {
- assertNotNull("Unexpected value of attribute " + Port.ID, port.get(Port.ID));
- assertEquals("Unexpected value of attribute " + Port.DURABLE, Boolean.TRUE, port.get(Port.DURABLE));
- assertEquals("Unexpected value of attribute " + Port.LIFETIME_POLICY, LifetimePolicy.PERMANENT.name(),
- port.get(Broker.LIFETIME_POLICY));
- assertEquals("Unexpected value of attribute " + Port.STATE, state.name(), port.get(Port.STATE));
-
- @SuppressWarnings("unchecked")
- Collection<String> protocols = (Collection<String>) port.get(Port.PROTOCOLS);
-
- if ("AMQP".equals(port.get(ConfiguredObject.TYPE)))
- {
- assertAttributesPresent(port,
- BrokerModel.getInstance().getTypeRegistry().getAttributeNames(Port.class),
- ConfiguredObject.TYPE,
- ConfiguredObject.CREATED_BY,
- ConfiguredObject.CREATED_TIME,
- ConfiguredObject.LAST_UPDATED_BY,
- ConfiguredObject.LAST_UPDATED_TIME,
- ConfiguredObject.DESCRIPTION,
- ConfiguredObject.CONTEXT,
- ConfiguredObject.DESIRED_STATE,
- Port.AUTHENTICATION_PROVIDER,
- Port.KEY_STORE,
- Port.TRUST_STORES,
- Port.PROTOCOLS,
- Port.CLIENT_CERT_RECORDER);
- assertNotNull("Unexpected value of attribute " + Port.BINDING_ADDRESS, port.get(Port.BINDING_ADDRESS));
- }
- else
- {
- assertAttributesPresent(port,
- BrokerModel.getInstance().getTypeRegistry().getAttributeNames(Port.class),
- ConfiguredObject.TYPE,
- ConfiguredObject.CREATED_BY,
- ConfiguredObject.CREATED_TIME,
- ConfiguredObject.LAST_UPDATED_BY,
- ConfiguredObject.LAST_UPDATED_TIME,
- ConfiguredObject.DESCRIPTION,
- ConfiguredObject.CONTEXT,
- ConfiguredObject.DESIRED_STATE,
- Port.AUTHENTICATION_PROVIDER,
- Port.BINDING_ADDRESS,
- Port.TCP_NO_DELAY,
- Port.NEED_CLIENT_AUTH,
- Port.WANT_CLIENT_AUTH,
- Port.KEY_STORE,
- Port.TRUST_STORES,
- Port.PROTOCOLS,
- Port.CLIENT_CERT_RECORDER);
- }
-
- @SuppressWarnings("unchecked")
- Collection<String> transports = (Collection<String>) port.get(Port.TRANSPORTS);
- assertEquals("Unexpected value of attribute " + Port.TRANSPORTS, new HashSet<String>(Arrays.asList("TCP")),
- new HashSet<String>(transports));
- }
-
- public static void assertDurableExchange(String exchangeName, String type, Map<String, Object> exchangeData)
- {
- assertExchange(exchangeName, type, exchangeData);
-
- assertEquals("Unexpected value of exchange attribute " + Exchange.DURABLE, Boolean.TRUE,
- exchangeData.get(Exchange.DURABLE));
- }
-
- public static void assertExchange(String exchangeName, String type, Map<String, Object> exchangeData)
- {
- assertNotNull("Exchange " + exchangeName + " is not found!", exchangeData);
- assertAttributesPresent(exchangeData, BrokerModel.getInstance().getTypeRegistry().getAttributeNames(Exchange.class),
- Exchange.ALTERNATE_BINDING,
- ConfiguredObject.CREATED_BY,
- ConfiguredObject.CREATED_TIME,
- ConfiguredObject.LAST_UPDATED_BY,
- ConfiguredObject.LAST_UPDATED_TIME,
- ConfiguredObject.DESCRIPTION,
- ConfiguredObject.CONTEXT,
- ConfiguredObject.DESIRED_STATE,
- Exchange.CREATING_LINK_INFO);
-
- assertEquals("Unexpected value of exchange attribute " + Exchange.NAME, exchangeName,
- exchangeData.get(Exchange.NAME));
- assertNotNull("Unexpected value of exchange attribute " + Exchange.ID, exchangeData.get(VirtualHost.ID));
- assertEquals("Unexpected value of exchange attribute " + Exchange.STATE, State.ACTIVE.name(),
- exchangeData.get(Exchange.STATE));
-
- assertEquals("Unexpected value of exchange attribute " + Exchange.LIFETIME_POLICY,
- LifetimePolicy.PERMANENT.name(),
- exchangeData.get(Exchange.LIFETIME_POLICY));
- assertEquals("Unexpected value of exchange attribute " + Exchange.TYPE, type, exchangeData.get(Exchange.TYPE));
- assertNotNull("Unexpected value of exchange attribute statistics", exchangeData.get(STATISTICS_ATTRIBUTE));
-
- @SuppressWarnings("unchecked")
- Map<String, Object> statistics = (Map<String, Object>) exchangeData.get(STATISTICS_ATTRIBUTE);
-
- assertAttributesPresent(statistics,"bindingCount",
- "bytesDropped",
- "bytesIn",
- "messagesDropped",
- "messagesIn");
- }
-
public static void assertActualAndDesiredState(final String expectedDesiredState,
final String expectedActualState,
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/main/java/org/apache/qpid/test/utils/TestUtils.java
----------------------------------------------------------------------
diff --git a/systests/src/main/java/org/apache/qpid/test/utils/TestUtils.java b/systests/src/main/java/org/apache/qpid/test/utils/TestUtils.java
index b112601..5069e20 100644
--- a/systests/src/main/java/org/apache/qpid/test/utils/TestUtils.java
+++ b/systests/src/main/java/org/apache/qpid/test/utils/TestUtils.java
@@ -21,10 +21,6 @@
package org.apache.qpid.test.utils;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
@@ -56,22 +52,4 @@ public class TestUtils
}
return dump.toString();
}
-
- public static String writeACLFileUtil(QpidBrokerTestCase testcase, String...rules) throws IOException
- {
- File aclFile = File.createTempFile(testcase.getClass().getSimpleName(), testcase.getName());
- aclFile.deleteOnExit();
-
- testcase.getDefaultBrokerConfiguration().addAclFileConfiguration(aclFile.getAbsolutePath());
-
- try (PrintWriter out = new PrintWriter(new FileWriter(aclFile)))
- {
- out.println(String.format("# %s", testcase.getName()));
- for (String line : rules)
- {
- out.println(line);
- }
- }
- return aclFile.getCanonicalPath();
- }
}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/test/java/org/apache/qpid/server/SupportedProtocolVersionsTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/server/SupportedProtocolVersionsTest.java b/systests/src/test/java/org/apache/qpid/server/SupportedProtocolVersionsTest.java
deleted file mode 100644
index 00a95d9..0000000
--- a/systests/src/test/java/org/apache/qpid/server/SupportedProtocolVersionsTest.java
+++ /dev/null
@@ -1,196 +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.server;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Set;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.configuration.ClientProperties;
-import org.apache.qpid.framing.ProtocolVersion;
-import org.apache.qpid.server.model.Protocol;
-import org.apache.qpid.server.model.port.AmqpPort;
-import org.apache.qpid.server.plugin.AMQPProtocolVersionWrapper;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-
-/**
- * Tests to validate it is possible to disable support for particular protocol
- * versions entirely, rather than selectively excluding them on particular ports,
- * and it is possible to configure the reply to an unsupported protocol initiation.
- *<p>
- */
-public class SupportedProtocolVersionsTest extends QpidBrokerTestCase
-{
- @Override
- public void startDefaultBroker() throws Exception
- {
- // No-op, we call super.startDefaultBroker() from test methods after appropriate config overrides
- }
-
- private void clearProtocolSupportManipulations() throws Exception
- {
- //Remove the QBTC provided protocol manipulations, giving only the protocols which default to enabled
-
- setSystemProperty(QpidBrokerTestCase.TEST_AMQP_PORT_PROTOCOLS_PROPERTY, getProtocolsAsString(getAllAmqpProtocols()));
- }
-
- private Collection<Protocol> getAllAmqpProtocols() throws Exception
- {
- Collection<Protocol> protocols = new HashSet<>();
- for(Protocol p : Protocol.values())
- {
- if(p.getProtocolType() == Protocol.ProtocolType.AMQP)
- {
- protocols.add(p);
- }
- }
-
- return protocols;
- }
-
- private String getProtocolsWithExclusions(Protocol... excludes) throws Exception
- {
- Set<Protocol> protocols = new HashSet<>(getAllAmqpProtocols());
- protocols.removeAll(Arrays.asList(excludes));
- return getProtocolsAsString(protocols);
- }
-
- private String getProtocolsAsString(final Collection<Protocol> protocols) throws IOException
- {
- ObjectMapper mapper = new ObjectMapper();
- StringWriter stringWriter = new StringWriter();
- mapper.writeValue(stringWriter, protocols);
- return stringWriter.toString();
- }
-
- /**
- * Test that 0-10, 0-9-1, 0-9, and 0-8 support is present when no
- * attempt has yet been made to disable them, and forcing the client
- * to negotiate from a particular protocol version returns a connection
- * using the expected protocol version.
- */
- public void testDefaultProtocolSupport() throws Exception
- {
- clearProtocolSupportManipulations();
-
- super.startDefaultBroker();
-
- //Verify requesting a 0-10 connection works
- setTestClientSystemProperty(ClientProperties.AMQP_VERSION, "0-10");
- AMQConnection connection = (AMQConnection) getConnection();
- assertEquals("Unexpected protocol version in use", ProtocolVersion.v0_10, connection.getProtocolVersion());
- connection.close();
-
- //Verify requesting a 0-91 connection works
- setTestClientSystemProperty(ClientProperties.AMQP_VERSION, "0-9-1");
- connection = (AMQConnection) getConnection();
- assertEquals("Unexpected protocol version in use", ProtocolVersion.v0_91, connection.getProtocolVersion());
- connection.close();
-
- //Verify requesting a 0-9 connection works
- setTestClientSystemProperty(ClientProperties.AMQP_VERSION, "0-9");
- connection = (AMQConnection) getConnection();
- assertEquals("Unexpected protocol version in use", ProtocolVersion.v0_9, connection.getProtocolVersion());
- connection.close();
-
- //Verify requesting a 0-8 connection works
- setTestClientSystemProperty(ClientProperties.AMQP_VERSION, "0-8");
- connection = (AMQConnection) getConnection();
- assertEquals("Unexpected protocol version in use", ProtocolVersion.v0_8, connection.getProtocolVersion());
- connection.close();
- }
-
- public void testDisabling010and10() throws Exception
- {
- setSystemProperty(QpidBrokerTestCase.TEST_AMQP_PORT_PROTOCOLS_PROPERTY, getProtocolsWithExclusions(Protocol.AMQP_1_0, Protocol.AMQP_0_10));
-
- super.startDefaultBroker();
-
- //Verify initially requesting a 0-10 connection now negotiates a 0-91
- //connection as the broker should reply with its highest supported protocol
- setTestClientSystemProperty(ClientProperties.AMQP_VERSION, "0-10");
- AMQConnection connection = (AMQConnection) getConnection();
- assertEquals("Unexpected protocol version in use", ProtocolVersion.v0_91, connection.getProtocolVersion());
- connection.close();
- }
-
- public void testConfiguringReplyingToUnsupported010ProtocolInitiationWith09insteadOf091() throws Exception
- {
- clearProtocolSupportManipulations();
-
- //disable 0-10 support, and set the default unsupported protocol initiation reply to 0-9
- setSystemProperty(QpidBrokerTestCase.TEST_AMQP_PORT_PROTOCOLS_PROPERTY, getProtocolsWithExclusions(Protocol.AMQP_1_0, Protocol.AMQP_0_10));
-
- setSystemProperty(AmqpPort.PROPERTY_DEFAULT_SUPPORTED_PROTOCOL_REPLY, "v0_9");
-
- super.startDefaultBroker();
-
- //Verify initially requesting a 0-10 connection now negotiates a 0-9 connection as the
- //broker should reply with its 'default unsupported protocol initiation reply' as opposed
- //to the previous behaviour of the highest supported protocol version.
- setTestClientSystemProperty(ClientProperties.AMQP_VERSION, "0-10");
- AMQConnection connection = (AMQConnection) getConnection();
- assertEquals("Unexpected protocol version in use", ProtocolVersion.v0_9, connection.getProtocolVersion());
- connection.close();
-
- //Verify requesting a 0-91 connection directly still works, as its support is still enabled
- setTestClientSystemProperty(ClientProperties.AMQP_VERSION, "0-9-1");
- connection = (AMQConnection) getConnection();
- assertEquals("Unexpected protocol version in use", ProtocolVersion.v0_91, connection.getProtocolVersion());
- connection.close();
- }
-
- public void testProtocolIsExpectedBasedOnTestProfile() throws Exception
- {
- super.startDefaultBroker();
- final AMQConnection connection = (AMQConnection) getConnection();
- final Protocol expectedBrokerProtocol = getBrokerProtocol();
- final AMQPProtocolVersionWrapper amqpProtocolVersionWrapper = new AMQPProtocolVersionWrapper(expectedBrokerProtocol);
- final ProtocolVersion protocolVersion = connection.getProtocolVersion();
- assertTrue("Connection AMQP protocol " + expectedBrokerProtocol + "is not the same as the test specified protocol " + protocolVersion,
- areEquivalent(amqpProtocolVersionWrapper, protocolVersion));
- connection.close();
- }
-
- private boolean areEquivalent(AMQPProtocolVersionWrapper amqpProtocolVersionWrapper, ProtocolVersion protocolVersion)
- {
- byte byteMajor = (byte)amqpProtocolVersionWrapper.getMajor();
- byte byteMinor;
- if (amqpProtocolVersionWrapper.getPatch() == 0)
- {
- byteMinor = (byte)amqpProtocolVersionWrapper.getMinor();
- }
- else
- {
- final StringBuilder sb = new StringBuilder();
- sb.append(amqpProtocolVersionWrapper.getMinor());
- sb.append(amqpProtocolVersionWrapper.getPatch());
- byteMinor = Byte.valueOf(sb.toString()).byteValue();
- }
- return (protocolVersion.getMajorVersion() == byteMajor && protocolVersion.getMinorVersion() == byteMinor);
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/test/java/org/apache/qpid/server/queue/LiveQueueOperationsTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/server/queue/LiveQueueOperationsTest.java b/systests/src/test/java/org/apache/qpid/server/queue/LiveQueueOperationsTest.java
deleted file mode 100644
index f59a723..0000000
--- a/systests/src/test/java/org/apache/qpid/server/queue/LiveQueueOperationsTest.java
+++ /dev/null
@@ -1,135 +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.server.queue;
-
-import java.util.Collections;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
-
-import javax.jms.Connection;
-import javax.jms.MessageConsumer;
-import javax.jms.Queue;
-import javax.jms.Session;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.qpid.client.RejectBehaviour;
-import org.apache.qpid.configuration.ClientProperties;
-import org.apache.qpid.systest.rest.RestTestHelper;
-import org.apache.qpid.test.utils.QpidBrokerTestCase;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-
-public class LiveQueueOperationsTest extends QpidBrokerTestCase
-{
- private static final Logger LOGGER = LoggerFactory.getLogger(LiveQueueOperationsTest.class);
-
- private static final int MAX_DELIVERY_COUNT = 2;
-
- @Override
- protected void setUp() throws Exception
- {
- getDefaultBrokerConfiguration().addHttpManagementConfiguration();
- setTestSystemProperty("queue.deadLetterQueueEnabled","true");
- setTestSystemProperty("queue.maximumDeliveryAttempts", String.valueOf(MAX_DELIVERY_COUNT));
-
- // Set client-side flag to allow the server to determine if messages
- // dead-lettered or requeued.
- if (!isBroker010())
- {
- setTestClientSystemProperty(ClientProperties.REJECT_BEHAVIOUR_PROP_NAME, RejectBehaviour.SERVER.toString());
- }
-
- super.setUp();
- }
-
- public void testClearQueueOperationWithActiveConsumerDlqAll() throws Exception
- {
- final String virtualHostName = TestBrokerConfiguration.ENTRY_NAME_VIRTUAL_HOST;
- RestTestHelper restTestHelper = new RestTestHelper(getDefaultBroker().getHttpPort());
-
- Connection conn = getConnection();
- conn.start();
- final Session session = conn.createSession(true, Session.SESSION_TRANSACTED);
- final Queue queue = createTestQueue(session);
- session.createConsumer(queue).close();
-
- sendMessage(session, queue, 250);
-
- MessageConsumer consumer = session.createConsumer(queue);
-
- final CountDownLatch clearQueueLatch = new CountDownLatch(10);
- final AtomicReference<Throwable> throwableAtomicReference = new AtomicReference<>();
- consumer.setMessageListener(message ->
- {
- try
- {
- clearQueueLatch.countDown();
- session.rollback();
- }
- catch (Throwable t)
- {
- LOGGER.error("Unexpected exception from rollback", t);
- throwableAtomicReference.set(t);
- }
- });
-
-
- boolean ready = clearQueueLatch.await(30, TimeUnit.SECONDS);
- assertTrue("Consumer did not reach expected point within timeout", ready);
-
- final String queueUrl = "queue/" + virtualHostName + "/" + virtualHostName + "/" + queue.getQueueName();
-
- String clearOperationUrl = queueUrl + "/clearQueue";
- restTestHelper.submitRequest(clearOperationUrl, "POST", Collections.<String,Object>emptyMap(), 200);
-
- int queueDepthMessages = 0;
- for (int i = 0; i < 20; ++i)
- {
- Map<String, Object> statistics = getStatistics(restTestHelper, queueUrl);
- queueDepthMessages = (int) statistics.get("queueDepthMessages");
- if (queueDepthMessages == 0)
- {
- break;
- }
- Thread.sleep(250);
- }
- assertEquals("Queue depth did not reach 0 within expected time", 0, queueDepthMessages);
-
- consumer.close();
-
- Map<String, Object> statistics = getStatistics(restTestHelper, queueUrl);
- queueDepthMessages = (int) statistics.get("queueDepthMessages");
- assertEquals("Unexpected queue depth after consumer close", 0, queueDepthMessages);
-
- assertEquals("Unexpected exception thrown", null, throwableAtomicReference.get());
- }
-
- private Map<String, Object> getStatistics(final RestTestHelper restTestHelper, final String objectUrl) throws Exception
- {
- Map<String, Object> object = restTestHelper.getJsonAsMap(objectUrl);
- @SuppressWarnings("unchecked")
- Map<String, Object> statistics = (Map<String, Object>) object.get("statistics");
- return statistics;
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/test/java/org/apache/qpid/systest/rest/AccessControlProviderRestTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/systest/rest/AccessControlProviderRestTest.java b/systests/src/test/java/org/apache/qpid/systest/rest/AccessControlProviderRestTest.java
deleted file mode 100644
index 8ca674d..0000000
--- a/systests/src/test/java/org/apache/qpid/systest/rest/AccessControlProviderRestTest.java
+++ /dev/null
@@ -1,234 +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.systest.rest;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.qpid.server.management.plugin.servlet.rest.RestServlet;
-import org.apache.qpid.server.model.AccessControlProvider;
-import org.apache.qpid.server.model.ConfiguredObject;
-import org.apache.qpid.server.model.State;
-import org.apache.qpid.server.model.SystemConfig;
-import org.apache.qpid.server.security.AllowAllAccessControlProvider;
-import org.apache.qpid.server.security.access.plugins.AclFileAccessControlProvider;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-import org.apache.qpid.test.utils.TestFileUtils;
-
-public class AccessControlProviderRestTest extends QpidRestTestCase
-{
- private static final String ALLOWED_USER = "allowed";
- private static final String DENIED_USER = "denied";
- private static final String OTHER_USER = "other";
-
- private String _aclFileContent1 =
- "ACL ALLOW-LOG " + ALLOWED_USER + " ACCESS MANAGEMENT\n" +
- "ACL ALLOW-LOG " + ALLOWED_USER + " CONFIGURE BROKER\n" +
- "ACL DENY-LOG ALL ALL";
-
- private String _aclFileContent2 =
- "ACL ALLOW-LOG " + ALLOWED_USER + " ACCESS MANAGEMENT\n" +
- "ACL ALLOW-LOG " + OTHER_USER + " ACCESS MANAGEMENT\n" +
- "ACL ALLOW-LOG " + ALLOWED_USER + " CONFIGURE BROKER\n" +
- "ACL DENY-LOG ALL ALL";
-
- @Override
- protected void customizeConfiguration() throws Exception
- {
- super.customizeConfiguration();
- final TestBrokerConfiguration defaultBrokerConfiguration = getDefaultBrokerConfiguration();
- defaultBrokerConfiguration.configureTemporaryPasswordFile(ALLOWED_USER, DENIED_USER, OTHER_USER);
- }
-
- public void testCreateAccessControlProvider() throws Exception
- {
- String accessControlProviderName = getTestName();
-
- //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(accessControlProviderName, false);
-
- //create the access control provider using the 'allowed' user
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
- int responseCode = createAccessControlProvider(accessControlProviderName, _aclFileContent1);
- assertEquals("Access control provider creation should be allowed", 201, responseCode);
-
- //verify it exists with the 'allowed' user
- assertAccessControlProviderExistence(accessControlProviderName, true);
-
- //verify the 'denied' user can no longer access the management interface
- //due to the just-created ACL file now preventing it
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- assertCanAccessManagementInterface(accessControlProviderName, false);
- }
-
- public void testRemoveAccessControlProvider() throws Exception
- {
- String accessControlProviderName = getTestName();
-
- //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(accessControlProviderName, false);
-
- //create the access control provider using the 'allowed' user
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
- int responseCode = createAccessControlProvider(accessControlProviderName, _aclFileContent1);
- assertEquals("Access control provider creation should be allowed", 201, responseCode);
-
- //verify it exists with the 'allowed' user
- assertAccessControlProviderExistence(accessControlProviderName, true);
-
- // add a second, low priority AllowAll provider
- Map<String,Object> attributes = new HashMap<>();
- final String secondProviderName = "AllowAll";
- attributes.put(ConfiguredObject.NAME, secondProviderName);
- attributes.put(ConfiguredObject.TYPE, AllowAllAccessControlProvider.ALLOW_ALL);
- attributes.put(AccessControlProvider.PRIORITY, 9999);
- responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + secondProviderName, "PUT", attributes);
- assertEquals("Access control provider creation should be allowed", 201, responseCode);
-
-
- //verify the 'denied' user can no longer access the management interface
- //due to the just-created ACL file now preventing it
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- assertCanAccessManagementInterface(accessControlProviderName, false);
-
- //remove the access control provider using the 'allowed' user
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
-
- responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "DELETE");
- assertEquals("Access control provider deletion should be allowed", 200, responseCode);
- assertAccessControlProviderExistence(accessControlProviderName, false);
-
- //verify it is gone again, using the 'denied' user to implicitly confirm it is
- //now able to connect to the management interface again because the ACL was removed.
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- assertAccessControlProviderExistence(accessControlProviderName, false);
- }
-
- public void testReplaceAccessControlProvider() throws Exception
- {
-
-
- //create the access control provider using the 'allowed' user
- getRestTestHelper().setUsernameAndPassword(ALLOWED_USER, ALLOWED_USER);
- int responseCode = createAccessControlProvider(getTestName(), _aclFileContent1);
- assertEquals("Access control provider creation should be allowed", 201, responseCode);
-
- //verify it exists with the 'allowed' user
- 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(getTestName(), false);
- getRestTestHelper().setUsernameAndPassword(OTHER_USER, OTHER_USER);
- 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);
-
- //Verify that first access control provider is used
-
- //verify the 'denied' user still can't access the management interface
- getRestTestHelper().setUsernameAndPassword(DENIED_USER, DENIED_USER);
- assertCanAccessManagementInterface(accessControlProviderName2, false);
- getRestTestHelper().setUsernameAndPassword(OTHER_USER, OTHER_USER);
- assertCanAccessManagementInterface(accessControlProviderName2, false);
- }
-
-
-
- public void testRemovalOfAccessControlProviderInErrorStateUsingManagementMode() throws Exception
- {
- stopDefaultBroker();
-
- File file = new File(TMP_FOLDER, getTestName());
- if (file.exists())
- {
- file.delete();
- }
- assertFalse("ACL file should not exist", file.exists());
- TestBrokerConfiguration configuration = getDefaultBrokerConfiguration();
- UUID id = configuration.addAclFileConfiguration(file.getAbsolutePath());
-
- Map<String,Object> attributes = new HashMap<>();
- final String secondProviderName = "AllowAll";
- attributes.put(ConfiguredObject.NAME, secondProviderName);
- attributes.put(ConfiguredObject.TYPE, AllowAllAccessControlProvider.ALLOW_ALL);
- attributes.put(AccessControlProvider.PRIORITY, 9999);
- configuration.addObjectConfiguration(AccessControlProvider.class, attributes);
- configuration.setSaved(false);
- startDefaultBroker(true);
-
- getRestTestHelper().setUsernameAndPassword(SystemConfig.MANAGEMENT_MODE_USER_NAME, MANAGEMENT_MODE_PASSWORD);
- Map<String, Object> acl = getRestTestHelper().getJsonAsMap("accesscontrolprovider/"
- + TestBrokerConfiguration.ENTRY_NAME_ACL_FILE
- + "?"
- + RestServlet.OVERSIZE_PARAM
- + "="
- + (file.getAbsolutePath().length() + 10));
- assertEquals("Unexpected id", id.toString(), acl.get(AccessControlProvider.ID));
- assertEquals("Unexpected path", file.getAbsolutePath() , acl.get(AclFileAccessControlProvider.PATH));
- assertEquals("Unexpected state", State.ERRORED.name(), acl.get(AccessControlProvider.STATE));
-
- int status = getRestTestHelper().submitRequest("accesscontrolprovider/" + TestBrokerConfiguration.ENTRY_NAME_ACL_FILE, "DELETE");
- assertEquals("ACL was not deleted", 200, status);
-
- getRestTestHelper().submitRequest("accesscontrolprovider/" + TestBrokerConfiguration.ENTRY_NAME_ACL_FILE, "GET", HttpServletResponse.SC_NOT_FOUND);
- }
-
- private void assertCanAccessManagementInterface(String accessControlProviderName, boolean canAccess) throws Exception
- {
- int expected = canAccess ? 200 : 403;
- int responseCode = getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "GET");
- assertEquals("Unexpected response code", expected, responseCode);
- }
-
- private void assertAccessControlProviderExistence(String accessControlProviderName, boolean exists) throws Exception
- {
- String path = "accesscontrolprovider/" + accessControlProviderName;
- int expectedResponseCode = exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_NOT_FOUND;
- getRestTestHelper().submitRequest(path, "GET", expectedResponseCode);
- }
-
- private int createAccessControlProvider(String accessControlProviderName, String content) throws Exception
- {
- File file = TestFileUtils.createTempFile(this, ".acl", content);
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(AccessControlProvider.NAME, accessControlProviderName);
- attributes.put(AccessControlProvider.TYPE, AclFileAccessControlProvider.ACL_FILE_PROVIDER_TYPE);
- attributes.put(AclFileAccessControlProvider.PATH, file.getAbsoluteFile());
-
- return getRestTestHelper().submitRequest("accesscontrolprovider/" + accessControlProviderName, "PUT", attributes);
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/test/java/org/apache/qpid/systest/rest/ConnectionRestTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/systest/rest/ConnectionRestTest.java b/systests/src/test/java/org/apache/qpid/systest/rest/ConnectionRestTest.java
deleted file mode 100644
index 31ef47f..0000000
--- a/systests/src/test/java/org/apache/qpid/systest/rest/ConnectionRestTest.java
+++ /dev/null
@@ -1,255 +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.systest.rest;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.qpid.server.model.Connection;
-import org.apache.qpid.server.virtualhost.VirtualHostPropertiesNodeCreator;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-
-public class ConnectionRestTest extends QpidRestTestCase
-{
- private javax.jms.Connection _connection;
- private javax.jms.Session _session;
- private MessageProducer _producer;
- private long _startTime;
- private Destination _queue;
-
- @Override
- public void setUp() throws Exception
- {
- // disable the virtualhostPropertiesNode as it messes with the statistics counts since causes the client to
- // create a session and then it sends a message
- setTestSystemProperty("qpid.plugin.disabled:systemnodecreator." + VirtualHostPropertiesNodeCreator.TYPE,
- "true");
-
- super.setUp();
-
- javax.jms.Connection managementConnection = getConnection();
- managementConnection.start();
- _queue = createTestQueue(managementConnection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE));
- managementConnection.close();
-
- _startTime = System.currentTimeMillis();
- _connection = getConnectionBuilder().setSyncPublish(true).build();
- _session = _connection.createSession(true, javax.jms.Session.SESSION_TRANSACTED);
- _producer = _session.createProducer(_queue);
- _connection.start();
- }
-
- public void testGetAllConnections() throws Exception
- {
- List<Map<String, Object>> connections = getRestTestHelper().getJsonAsList("connection");
- assertEquals("Unexpected number of connections", 1, connections.size());
- Asserts.assertConnection(connections.get(0), isBroker10() ? 2 : 1);
- }
-
- public void testGetVirtualHostConnections() throws Exception
- {
- List<Map<String, Object>> connections =
- getRestTestHelper().getJsonAsList("virtualhost/test/test/getConnections");
- assertEquals("Unexpected number of connections", 1, connections.size());
- Asserts.assertConnection(connections.get(0), isBroker10() ? 2 : 1);
- }
-
- public void testDeleteConnection() throws Exception
- {
- String connectionName = getConnectionName();
- String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT;
-
- List<Map<String, Object>> connections = getRestTestHelper().getJsonAsList("connection/" + portName);
- assertEquals("Unexpected number of connections before deletion", 1, connections.size());
-
- String connectionUrl = "connection/" + portName + "/" + getRestTestHelper().encodeAsUTF(connectionName);
- getRestTestHelper().submitRequest(connectionUrl, "DELETE", HttpServletResponse.SC_OK);
-
- connections = getRestTestHelper().getJsonAsList("connection/" + portName);
- assertEquals("Unexpected number of connections after deletion", 0, connections.size());
-
- try
- {
- _connection.createSession(true, javax.jms.Session.SESSION_TRANSACTED);
- fail("Exception not thrown");
- }
- catch (JMSException je)
- {
- // PASS
- }
- finally
- {
- try
- {
- _connection.close();
- }
- catch (JMSException e)
- {
- // PASS
- }
- _connection = null;
- }
- }
-
- public void testConnectionTransactionCountStatistics() throws Exception
- {
- String connectionUrl = getVirtualHostConnectionUrl();
-
- _producer.send(_session.createTextMessage("Test-0"));
- _session.commit();
-
- MessageConsumer consumer = _session.createConsumer(_queue);
- Message m = consumer.receive(getReceiveTimeout());
- assertNotNull("Subsequent messages were not received", m);
-
- Map<String, Object> statistics = getConnectionStatistics(connectionUrl);
-
- assertEquals("Unexpected value of statistic attribute localTransactionBegins", 2,
- statistics.get("localTransactionBegins"));
- assertEquals("Unexpected value of statistic attribute localTransactionRollbacks", 0,
- statistics.get("localTransactionRollbacks"));
- assertEquals("Unexpected value of statistic attribute localTransactionOpen", 1,
- statistics.get("localTransactionOpen"));
-
- _session.rollback();
- m = consumer.receive(getReceiveTimeout());
- assertNotNull("Subsequent messages were not received", m);
-
- final Map<String, Object> statistics2 = getConnectionStatistics(connectionUrl);
-
- assertEquals("Unexpected value of statistic attribute localTransactionBegins", 3,
- statistics2.get("localTransactionBegins"));
- assertEquals("Unexpected value of statistic attribute localTransactionRollbacks", 1,
- statistics2.get("localTransactionRollbacks"));
- assertEquals("Unexpected value of statistic attribute localTransactionOpen", 1,
- statistics2.get("localTransactionOpen"));
-
- _producer.send(_session.createMessage());
- consumer.close();
- _session.close();
-
- final Map<String, Object> statistics3 = getConnectionStatistics(connectionUrl);
-
- assertEquals("Unexpected value of statistic attribute localTransactionBegins", 3,
- statistics3.get("localTransactionBegins"));
- assertEquals("Unexpected value of statistic attribute localTransactionRollbacks", 2,
- statistics3.get("localTransactionRollbacks"));
- assertEquals("Unexpected value of statistic attribute localTransactionOpen", 0,
- statistics3.get("localTransactionOpen"));
- }
-
- public void testConnectionMessageCountStatistics() throws Exception
- {
- _producer.send(_session.createTextMessage("Test-0"));
- _session.commit();
-
- MessageConsumer consumer = _session.createConsumer(_queue);
- Message m = consumer.receive(getReceiveTimeout());
- assertNotNull("First message was not received", m);
- _session.commit();
-
- _session.close();
-
- _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- _producer = _session.createProducer(_queue);
- _producer.send(_session.createTextMessage("Test-1"));
- consumer = _session.createConsumer(_queue);
- m = consumer.receive(getReceiveTimeout());
- assertNotNull("First message was not received", m);
-
- // close session to make sure message ack/disposition reaches the broker before rest request is made
- _session.close();
-
- String connectionUrl = getVirtualHostConnectionUrl();
-
- Map<String, Object> statistics = getConnectionStatistics(connectionUrl);
- assertTrue("Unexpected value of connection statistics attribute bytesIn",
- Long.parseLong(String.valueOf(statistics.get("bytesIn"))) > 0);
- assertTrue("Unexpected value of connection statistics attribute bytesOut",
- Long.parseLong(String.valueOf(statistics.get("bytesOut"))) > 0);
- assertEquals("Unexpected value of connection statistics attribute messagesIn", 2,
- statistics.get("messagesIn"));
- assertEquals("Unexpected value of connection statistics attribute messagesOut",
- 2, statistics.get("messagesOut"));
-
- assertEquals("Unexpected value of statistic attribute transactedMessagesIn", 1,
- statistics.get("transactedMessagesIn"));
-
- assertEquals("Unexpected value of statistic attribute transactedMessagesOut", 1,
- statistics.get("transactedMessagesOut"));
- }
-
- public void testOldestTransactionStartTime() throws Exception
- {
- String connectionUrl = getVirtualHostConnectionUrl();
-
- _producer.send(_session.createTextMessage("Test"));
-
- Map<String, Object> statistics = getConnectionStatistics(connectionUrl);
- long oldestTransactionStartTime = ((Number) statistics.get("oldestTransactionStartTime")).longValue();
- assertTrue("Unexpected transaction oldestTransactionStartTime for connection with work "
- + oldestTransactionStartTime, oldestTransactionStartTime >= _startTime);
-
- _session.commit();
- statistics = getConnectionStatistics(connectionUrl);
- assertNull(String.format(
- "Unexpected transaction oldestTransactionStartTime %s for connection with no work",
- statistics.get("oldestTransactionStartTime")), statistics.get("oldestTransactionStartTime"));
-
- _producer.send(_session.createTextMessage("Test"));
- _session.close();
-
- statistics = getConnectionStatistics(connectionUrl);
- assertNull("Unexpected transaction oldestTransactionStartTime for connection with no session",
- statistics.get("oldestTransactionStartTime"));
- }
-
- private String getConnectionName() throws IOException
- {
- List<Map<String, Object>> connections =
- getRestTestHelper().getJsonAsList("virtualhost/test/test/getConnections");
- assertEquals("Unexpected number of connections", 1, connections.size());
- Map<String, Object> connection = connections.get(0);
- String connectionName = (String) connection.get(Connection.NAME);
- return connectionName;
- }
-
- private String getVirtualHostConnectionUrl() throws IOException
- {
- String connectionName = getConnectionName();
- return "virtualhost/test/test/getConnection?name=" + getRestTestHelper().encodeAsUTF(connectionName);
- }
-
- private Map<String, Object> getConnectionStatistics(final String connectionUrl) throws IOException
- {
- Map<String, Object> connection = getRestTestHelper().getJsonAsMap(connectionUrl);
- return (Map<String, Object>) connection.get(Asserts.STATISTICS_ATTRIBUTE);
- }
-}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cec889db/systests/src/test/java/org/apache/qpid/systest/rest/SessionRestTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/systest/rest/SessionRestTest.java b/systests/src/test/java/org/apache/qpid/systest/rest/SessionRestTest.java
deleted file mode 100644
index 1265ae2..0000000
--- a/systests/src/test/java/org/apache/qpid/systest/rest/SessionRestTest.java
+++ /dev/null
@@ -1,159 +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.systest.rest;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-
-import javax.jms.Destination;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-
-import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.server.model.BrokerModel;
-import org.apache.qpid.server.model.ConfiguredObject;
-import org.apache.qpid.server.model.Connection;
-import org.apache.qpid.server.model.Session;
-import org.apache.qpid.server.virtualhost.VirtualHostPropertiesNodeCreator;
-import org.apache.qpid.test.utils.TestBrokerConfiguration;
-
-public class SessionRestTest extends QpidRestTestCase
-{
-
- private javax.jms.Connection _connection;
- private javax.jms.Session _session;
- private Destination _queue;
- private MessageProducer _producer;
-
- @Override
- public void setUp() throws Exception
- {
- // disable the virtualhostPropertiesNode as it messes with the statistics counts since causes the client to
- // create a session and then it sends a message
- setTestSystemProperty("qpid.plugin.disabled:systemnodecreator."+ VirtualHostPropertiesNodeCreator.TYPE, "true");
-
- super.setUp();
-
- javax.jms.Connection managementConnection = getConnection();
- try
- {
- managementConnection.start();
- _queue = createTestQueue(managementConnection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE));
- }
- finally
- {
- managementConnection.close();
- }
- _connection = getConnection();
- _session = _connection.createSession(true, javax.jms.Session.SESSION_TRANSACTED);
- MessageConsumer consumer = _session.createConsumer(_queue);
- _producer = _session.createProducer(_queue);
- _connection.start();
-
- _producer.send(_session.createTextMessage("Test"));
- _session.commit();
-
- Message m = consumer.receive(getReceiveTimeout());
- assertNotNull("First message was not received", m);
- // Session left open with uncommitted transaction
- }
-
- public void testGetAllSessions() throws Exception
- {
- List<Map<String, Object>> sessions = getRestTestHelper().getJsonAsList("session");
- assertEquals("Unexpected number of sessions", 1, sessions.size());
- assertSession(sessions.get(0));
- }
-
- public void testGetPortSessions() throws Exception
- {
- String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT;
-
- List<Map<String, Object>> sessions = getRestTestHelper().getJsonAsList("session/" + portName);
- assertEquals("Unexpected number of sessions", 1, sessions.size());
- assertSession(sessions.get(0));
- }
-
- public void testGetConnectionSessions() throws Exception
- {
- String connectionName = getConnectionName();
- String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT;
-
- List<Map<String, Object>> sessions = getRestTestHelper().getJsonAsList("session/" + portName + "/"
- + getRestTestHelper().encodeAsUTF(connectionName));
- assertEquals("Unexpected number of sessions", 1, sessions.size());
- assertSession(sessions.get(0));
- }
-
- public void testGetSessionByName() throws Exception
- {
- String connectionName = getConnectionName();
- String portName = TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT;
-
- Map<String, Object> sessionDetails = getRestTestHelper().getJsonAsMap("session/" + portName + "/"
- + getRestTestHelper().encodeAsUTF(connectionName) + "/" + ((AMQSession<?, ?>) _session).getChannelId());
- assertSession(sessionDetails);
- }
-
- private void assertSession(Map<String, Object> sessionData)
- {
- assertNotNull("Session map cannot be null", sessionData);
- Asserts.assertAttributesPresent(sessionData, BrokerModel.getInstance().getTypeRegistry().getAttributeNames(
- Session.class),
- ConfiguredObject.TYPE,
- ConfiguredObject.CREATED_BY,
- ConfiguredObject.CREATED_TIME,
- ConfiguredObject.LAST_UPDATED_BY,
- ConfiguredObject.LAST_UPDATED_TIME,
- ConfiguredObject.DESCRIPTION,
- ConfiguredObject.CONTEXT,
- ConfiguredObject.DESIRED_STATE,
- Session.STATE,
- Session.DURABLE,
- Session.LIFETIME_POLICY);
- assertEquals("Unexpected value of attribute " + Session.PRODUCER_FLOW_BLOCKED, Boolean.FALSE,
- sessionData.get(Session.PRODUCER_FLOW_BLOCKED));
- assertNotNull("Unexpected value of attribute " + Session.NAME, sessionData.get(Session.NAME));
- assertNotNull("Unexpected value of attribute " + Session.CHANNEL_ID , sessionData.get(Session.CHANNEL_ID));
-
- @SuppressWarnings("unchecked")
- Map<String, Object> statistics = (Map<String, Object>) sessionData.get(Asserts.STATISTICS_ATTRIBUTE);
- Asserts.assertAttributesPresent(statistics, "consumerCount",
- "unacknowledgedMessages");
-
- assertEquals("Unexpected value of statistic attribute " + "unacknowledgedMessages", 1,
- statistics.get("unacknowledgedMessages"));
-
- assertEquals("Unexpected value of statistic attribute " + "consumerCount", 1,
- statistics.get("consumerCount"));
- }
-
- private String getConnectionName() throws IOException
- {
- List<Map<String, Object>> connections = getRestTestHelper().getJsonAsList("virtualhost/test/test/getConnections");
- assertEquals("Unexpected number of connections", 1, connections.size());
- Map<String, Object> connection = connections.get(0);
- String connectionName = (String) connection.get(Connection.NAME);
- return connectionName;
- }
-}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org
[4/8] qpid-broker-j git commit: QPID-8123: [Broker-J] [BDB System
Tests] Refactor MultiNodeTest and TwoNodeTest to remove knowledge of Qpid JMS
AMQP 0-x client (code dependency and format of failover url).
Posted by kw...@apache.org.
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c09a9a31/test-profiles/Java010Excludes
----------------------------------------------------------------------
diff --git a/test-profiles/Java010Excludes b/test-profiles/Java010Excludes
index 3557644..e72790c 100755
--- a/test-profiles/Java010Excludes
+++ b/test-profiles/Java010Excludes
@@ -25,8 +25,6 @@ org.apache.qpid.server.logging.ChannelLoggingTest#testChannelStartConsumerFlowSt
org.apache.qpid.test.client.timeouts.SyncWaitTimeoutDelayTest#*
org.apache.qpid.test.client.timeouts.SyncWaitDelayTest#*
-org.apache.qpid.test.unit.client.AMQSessionTest#testQueueDepthForQueueThatDoesNotExistLegacyBehaviour_08_091
-
# Exclude the JMS 2.0 test suite
org.apache.qpid.systests.jms_2_0.*
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c09a9a31/test-profiles/Java10Excludes
----------------------------------------------------------------------
diff --git a/test-profiles/Java10Excludes b/test-profiles/Java10Excludes
index 611c6b9..3265d94 100644
--- a/test-profiles/Java10Excludes
+++ b/test-profiles/Java10Excludes
@@ -17,9 +17,6 @@
// under the License.
//
-// Exclude client test of initial context factory, as the 1.0 profile uses the 1.0 context factory
-org.apache.qpid.jndi.PropertiesFileInitialContextFactoryTest#*
-
// The binding logging tests focus on the behaviour of the old client with regard to creating (and binding) queues on
// the creation of consumers.
org.apache.qpid.server.logging.BindingLoggingTest#*
@@ -30,9 +27,6 @@ org.apache.qpid.server.logging.ChannelLoggingTest#testChannelStartConsumerFlowSt
// This test is testing AMQP 0-x specific behaviour
org.apache.qpid.server.logging.ChannelLoggingTest#testChannelClosedOnExclusiveQueueDeclaredOnDifferentSession
-// This test is checking features of the 0-x client specific implementation of Session
-org.apache.qpid.test.unit.client.AMQSessionTest#*
-
// Tests the interaction between the Broker's supported protocols and what the 0-x client agrees to
org.apache.qpid.server.SupportedProtocolVersionsTest#*
@@ -40,10 +34,6 @@ org.apache.qpid.server.SupportedProtocolVersionsTest#*
org.apache.qpid.server.logging.ConsumerLoggingTest#testSubscriptionCreateDurable
org.apache.qpid.server.logging.ConsumerLoggingTest#testSubscriptionCreateDurableWithArguments
-// Tests assume BURL and/or Connection URL formats
-org.apache.qpid.server.store.berkeleydb.replication.MultiNodeTest#*
-org.apache.qpid.server.store.berkeleydb.replication.TwoNodeTest#*
-
// These tests assume names of queues backing durable subscriptions
org.apache.qpid.server.store.berkeleydb.BDBUpgradeTest#testConsumptionOfUpgradedMessages
org.apache.qpid.server.store.berkeleydb.BDBUpgradeTest#testDurableSubscriptionWithoutSelector
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org