diff options
| author | Alex Rudyy <orudyy@apache.org> | 2015-04-15 09:47:28 +0000 |
|---|---|---|
| committer | Alex Rudyy <orudyy@apache.org> | 2015-04-15 09:47:28 +0000 |
| commit | 0a0baee45ebcff44635907d457c4ff6810b09c87 (patch) | |
| tree | 8bfb0f9eddbc23cff88af69be80ab3ce7d47011c /qpid/java/systests/src/main | |
| parent | 54aa3d7070da16ce55c28ccad3f7d0871479e461 (diff) | |
| download | qpid-python-0a0baee45ebcff44635907d457c4ff6810b09c87.tar.gz | |
QPID-6481: Move java source tree to top level
git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1673693 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'qpid/java/systests/src/main')
14 files changed, 0 insertions, 4579 deletions
diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.java b/qpid/java/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.java deleted file mode 100644 index 19708353aa..0000000000 --- a/qpid/java/systests/src/main/java/org/apache/qpid/systest/rest/Asserts.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.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.client.AMQConnection; -import org.apache.qpid.server.model.Binding; -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.model.port.AmqpPort; -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.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, - VirtualHost.ENABLED_CONNECTION_VALIDATORS, - VirtualHost.DISABLED_CONNECTION_VALIDATORS, - VirtualHost.GLOBAL_ADDRESS_DOMAINS, - VirtualHost.TYPE); - - 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)); - assertEquals("Unexpected value of attribute " + VirtualHost.QUEUE_DEAD_LETTER_QUEUE_ENABLED, Boolean.FALSE, - virtualHost.get(VirtualHost.QUEUE_DEAD_LETTER_QUEUE_ENABLED)); - - @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_EXCHANGE, - Queue.OWNER, - Queue.NO_LOCAL, - LastValueQueue.LVQ_KEY, - SortedQueue.SORT_KEY, - Queue.MESSAGE_GROUP_KEY, - Queue.MESSAGE_GROUP_SHARED_GROUPS, - PriorityQueue.PRIORITIES, - ConfiguredObject.CONTEXT, - ConfiguredObject.DESIRED_STATE, - Queue.DEFAULT_FILTERS, - Queue.ENSURE_NONDESTRUCTIVE_CONSUMERS); - - 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.QUEUE_FLOW_CONTROL_SIZE_BYTES, 0, - queueData.get(Queue.QUEUE_FLOW_CONTROL_SIZE_BYTES)); - assertEquals("Unexpected value of queue attribute " + Queue.QUEUE_FLOW_RESUME_SIZE_BYTES, 0, - queueData.get(Queue.QUEUE_FLOW_RESUME_SIZE_BYTES)); - 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, AMQConnection connection) - 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.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.SESSION_COUNT_LIMIT, - (int) connection.getMaximumChannelCount(), connectionData.get(Connection.SESSION_COUNT_LIMIT)); - assertEquals("Unexpected value of connection attribute " + Connection.CLIENT_ID, "clientid", - connectionData.get(Connection.CLIENT_ID)); - 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 ", 1, - 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); - 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, - AmqpPort.SEND_BUFFER_SIZE, - AmqpPort.RECEIVE_BUFFER_SIZE, - Port.NEED_CLIENT_AUTH, - Port.WANT_CLIENT_AUTH, - Port.KEY_STORE, - Port.TRUST_STORES, - Port.PROTOCOLS); - } - - @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_EXCHANGE, - ConfiguredObject.CREATED_BY, - ConfiguredObject.CREATED_TIME, - ConfiguredObject.LAST_UPDATED_BY, - ConfiguredObject.LAST_UPDATED_TIME, - ConfiguredObject.DESCRIPTION, - ConfiguredObject.CONTEXT, - ConfiguredObject.DESIRED_STATE); - - 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 assertBinding(String bindingName, String queueName, String exchange, Map<String, Object> binding) - { - assertNotNull("Binding map should not be null", binding); - assertAttributesPresent(binding, - BrokerModel.getInstance().getTypeRegistry().getAttributeNames(Binding.class), - Binding.STATE, - Binding.ARGUMENTS, - 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 binding attribute " + Binding.NAME, bindingName, binding.get(Binding.NAME)); - assertEquals("Unexpected binding attribute " + Binding.QUEUE, queueName, binding.get(Binding.QUEUE)); - assertEquals("Unexpected binding attribute " + Binding.EXCHANGE, exchange, binding.get(Binding.EXCHANGE)); - assertEquals("Unexpected binding attribute " + Binding.LIFETIME_POLICY, LifetimePolicy.PERMANENT.name(), - binding.get(Binding.LIFETIME_POLICY)); - } - - public static void assertBinding(String queueName, String exchange, Map<String, Object> binding) - { - assertBinding(queueName, queueName, exchange, binding); - } - - public static void assertActualAndDesiredState(final String expectedDesiredState, - final String expectedActualState, - final Map<String, Object> data) - { - String name = (String) data.get(ConfiguredObject.NAME); - TestCase.assertEquals("Object with name " + name + " has unexpected desired state", - expectedDesiredState, - data.get(ConfiguredObject.DESIRED_STATE)); - TestCase.assertEquals("Object with name " + name + " has unexpected actual state", - expectedActualState, data.get(ConfiguredObject.STATE)); - } -} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/systest/rest/QpidRestTestCase.java b/qpid/java/systests/src/main/java/org/apache/qpid/systest/rest/QpidRestTestCase.java deleted file mode 100644 index 91447677a5..0000000000 --- a/qpid/java/systests/src/main/java/org/apache/qpid/systest/rest/QpidRestTestCase.java +++ /dev/null @@ -1,120 +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.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.server.management.plugin.HttpManagement; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Plugin; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManager; -import org.apache.qpid.test.utils.QpidBrokerTestCase; -import org.apache.qpid.test.utils.TestBrokerConfiguration; - -public class QpidRestTestCase extends QpidBrokerTestCase -{ - public static final String EXTERNAL_AUTHENTICATION_PROVIDER = "testExternal"; - - public static final String TEST1_VIRTUALHOST = "test"; - public static final String TEST2_VIRTUALHOST = "test2"; - public static final String TEST3_VIRTUALHOST = "test3"; - - public static final String[] EXPECTED_VIRTUALHOSTS = { TEST1_VIRTUALHOST, TEST2_VIRTUALHOST, TEST3_VIRTUALHOST}; - public static final String[] EXPECTED_EXCHANGES = { "amq.fanout", "amq.match", "amq.direct","amq.topic" }; - - private RestTestHelper _restTestHelper = new RestTestHelper(findFreePort()); - - @Override - public void setUp() throws Exception - { - // use webadmin account to perform tests - getRestTestHelper().setUsernameAndPassword("webadmin", "webadmin"); - - //remove the normal 'test' vhost, we will configure the vhosts below - getBrokerConfiguration(0).removeObjectConfiguration(VirtualHostNode.class, TestBrokerConfiguration.ENTRY_NAME_VIRTUAL_HOST); - - // Set up virtualhost config with queues and bindings to the amq.direct - for (String virtualhost : EXPECTED_VIRTUALHOSTS) - { - createTestVirtualHostNode(0, virtualhost); - } - - customizeConfiguration(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception - { - try - { - super.tearDown(); - } - finally - { - getRestTestHelper().tearDown(); - } - } - - protected void customizeConfiguration() throws IOException - { - TestBrokerConfiguration config = getBrokerConfiguration(); - config.addHttpManagementConfiguration(); - config.setObjectAttribute(Port.class, TestBrokerConfiguration.ENTRY_NAME_HTTP_PORT, Port.PORT, _restTestHelper.getHttpPort()); - config.removeObjectConfiguration(Port.class, TestBrokerConfiguration.ENTRY_NAME_JMX_PORT); - config.removeObjectConfiguration(Port.class, TestBrokerConfiguration.ENTRY_NAME_RMI_PORT); - - config.setObjectAttribute(AuthenticationProvider.class, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER, - "secureOnlyMechanisms", - "{}"); - - - // set password authentication provider on http port for the tests - config.setObjectAttribute(Port.class, TestBrokerConfiguration.ENTRY_NAME_HTTP_PORT, Port.AUTHENTICATION_PROVIDER, - TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER); - config.setObjectAttribute(Plugin.class, TestBrokerConfiguration.ENTRY_NAME_HTTP_MANAGEMENT, HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED, true); - } - - public RestTestHelper getRestTestHelper() - { - return _restTestHelper; - } - - public Map<String, Object> waitForAttributeChanged(String url, String attributeName, Object newValue) throws Exception - { - List<Map<String, Object>> nodeAttributes = getRestTestHelper().getJsonAsList(url); - int timeout = 5000; - long limit = System.currentTimeMillis() + timeout; - while(System.currentTimeMillis() < limit && (nodeAttributes.size() == 0 || !newValue.equals(nodeAttributes.get(0).get(attributeName)))) - { - Thread.sleep(100l); - nodeAttributes = getRestTestHelper().getJsonAsList(url); - } - Map<String, Object> nodeData = nodeAttributes.get(0); - assertEquals("Attribute " + attributeName + " did not reach expected value within permitted timeout " + timeout + "ms.", newValue, nodeData.get(attributeName)); - return nodeData; - } -} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/systest/rest/RestTestHelper.java b/qpid/java/systests/src/main/java/org/apache/qpid/systest/rest/RestTestHelper.java deleted file mode 100644 index 6e2d3b901b..0000000000 --- a/qpid/java/systests/src/main/java/org/apache/qpid/systest/rest/RestTestHelper.java +++ /dev/null @@ -1,611 +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 static org.apache.qpid.test.utils.TestSSLConstants.KEYSTORE; -import static org.apache.qpid.test.utils.TestSSLConstants.KEYSTORE_PASSWORD; -import static org.apache.qpid.test.utils.TestSSLConstants.TRUSTSTORE; -import static org.apache.qpid.test.utils.TestSSLConstants.TRUSTSTORE_PASSWORD; - -import java.io.BufferedWriter; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLEncoder; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManagerFactory; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.codec.binary.Base64; -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.JsonParseException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.type.TypeReference; -import org.junit.Assert; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Binding; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.ssl.SSLContextFactory; -import org.apache.qpid.test.utils.QpidBrokerTestCase; -import org.apache.qpid.test.utils.TestBrokerConfiguration; - -public class RestTestHelper -{ - - private static final TypeReference<List<LinkedHashMap<String, Object>>> TYPE_LIST_OF_LINKED_HASH_MAPS = new TypeReference<List<LinkedHashMap<String, Object>>>() - { - }; - public static final String API_BASE = "/api/latest/"; - - private static final Logger LOGGER = LoggerFactory.getLogger(RestTestHelper.class); - private static final String CERT_ALIAS_APP1 = "app1"; - - private int _httpPort; - - private boolean _useSsl; - - - private String _username; - - private String _password; - - private File _passwdFile; - private boolean _useSslAuth; - static final String[] EXPECTED_QUEUES = { "queue", "ping" }; - private final int _connectTimeout = Integer.getInteger("qpid.resttest_connection_timeout", 30000); - - public RestTestHelper(int httpPort) - { - _httpPort = httpPort; - } - - public int getHttpPort() - { - return _httpPort; - } - - private String getHostName() - { - return "localhost"; - } - - private String getProtocol() - { - return _useSsl ? "https" : "http"; - } - - public String getManagementURL() - { - return getProtocol() + "://" + getHostName() + ":" + getHttpPort(); - } - - public URL getManagementURL(String path) throws MalformedURLException - { - return new URL(getManagementURL() + path); - } - - public HttpURLConnection openManagementConnection(String path, String method) throws IOException - { - if (!path.startsWith("/")) - { - path = API_BASE + path; - } - URL url = getManagementURL(path); - HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); - httpCon.setConnectTimeout(_connectTimeout); - - if(_useSslAuth) - { - try - { - // We have to use a SSLSocketFactory from a new SSLContext so that we don't re-use - // the JVM's defaults that may have been initialised in previous tests. - - SSLContext sslContext = SSLContextFactory.buildClientContext( - TRUSTSTORE, TRUSTSTORE_PASSWORD, - KeyStore.getDefaultType(), - TrustManagerFactory.getDefaultAlgorithm(), - KEYSTORE, KEYSTORE_PASSWORD, KeyStore.getDefaultType(), KeyManagerFactory.getDefaultAlgorithm(), CERT_ALIAS_APP1); - - SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); - - ((HttpsURLConnection) httpCon).setSSLSocketFactory(sslSocketFactory); - } - catch (GeneralSecurityException e) - { - throw new RuntimeException(e); - } - } - else if(_useSsl) - { - try - { - // We have to use a SSLSocketFactory from a new SSLContext so that we don't re-use - // the JVM's defaults that may have been initialised in previous tests. - - SSLContext sslContext = SSLContextFactory.buildClientContext( - TRUSTSTORE, TRUSTSTORE_PASSWORD, - KeyStore.getDefaultType(), - TrustManagerFactory.getDefaultAlgorithm(), - null, null, null, null, null); - - SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); - - ((HttpsURLConnection) httpCon).setSSLSocketFactory(sslSocketFactory); - } - catch (GeneralSecurityException e) - { - throw new RuntimeException(e); - } - } - - if(_username != null) - { - String encoded = new String(new Base64().encode((_username + ":" + _password).getBytes())); - httpCon.setRequestProperty("Authorization", "Basic " + encoded); - } - - httpCon.setDoOutput(true); - httpCon.setRequestMethod(method); - return httpCon; - } - - public List<Map<String, Object>> readJsonResponseAsList(HttpURLConnection connection) throws IOException, - JsonParseException, JsonMappingException - { - byte[] data = readConnectionInputStream(connection); - ObjectMapper mapper = new ObjectMapper(); - List<Map<String, Object>> providedObject = mapper.readValue(new ByteArrayInputStream(data), TYPE_LIST_OF_LINKED_HASH_MAPS); - return providedObject; - } - - public Map<String, Object> readJsonResponseAsMap(HttpURLConnection connection) throws IOException, - JsonParseException, JsonMappingException - { - byte[] data = readConnectionInputStream(connection); - - ObjectMapper mapper = new ObjectMapper(); - - TypeReference<LinkedHashMap<String, Object>> typeReference = new TypeReference<LinkedHashMap<String, Object>>() - { - }; - Map<String, Object> providedObject = mapper.readValue(new ByteArrayInputStream(data), typeReference); - return providedObject; - } - - private byte[] readConnectionInputStream(HttpURLConnection connection) throws IOException - { - InputStream is = connection.getInputStream(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - int len = -1; - while ((len = is.read(buffer)) != -1) - { - baos.write(buffer, 0, len); - } - if (LOGGER.isTraceEnabled()) - { - LOGGER.trace("RESPONSE:" + new String(baos.toByteArray())); - } - return baos.toByteArray(); - } - - private void writeJsonRequest(HttpURLConnection connection, Map<String, Object> data) throws JsonGenerationException, - JsonMappingException, IOException - { - ObjectMapper mapper = new ObjectMapper(); - mapper.writeValue(connection.getOutputStream(), data); - } - - public Map<String, Object> find(String name, Object value, List<Map<String, Object>> data) - { - if (data == null) - { - return null; - } - - for (Map<String, Object> map : data) - { - Object mapValue = map.get(name); - if (value.equals(mapValue)) - { - return map; - } - } - return null; - } - - public Map<String, Object> find(Map<String, Object> searchAttributes, List<Map<String, Object>> data) - { - for (Map<String, Object> map : data) - { - boolean equals = true; - for (Map.Entry<String, Object> entry : searchAttributes.entrySet()) - { - Object mapValue = map.get(entry.getKey()); - if (!entry.getValue().equals(mapValue)) - { - equals = false; - break; - } - } - if (equals) - { - return map; - } - } - return null; - } - - public Map<String, Object> getJsonAsSingletonList(String path) throws IOException - { - List<Map<String, Object>> response = getJsonAsList(path); - - Assert.assertNotNull("Response cannot be null", response); - Assert.assertEquals("Unexpected response from " + path, 1, response.size()); - return response.get(0); - } - - public List<Map<String, Object>> getJsonAsList(String path) throws IOException, JsonParseException, - JsonMappingException - { - HttpURLConnection connection = openManagementConnection(path, "GET"); - connection.connect(); - List<Map<String, Object>> response = readJsonResponseAsList(connection); - return response; - } - - public Map<String, Object> getJsonAsMap(String path) throws IOException - { - HttpURLConnection connection = openManagementConnection(path, "GET"); - connection.connect(); - Map<String, Object> response = readJsonResponseAsMap(connection); - return response; - } - - public void createNewGroupMember(String groupProviderName, String groupName, String memberName, int responseCode) throws IOException - { - HttpURLConnection connection = openManagementConnection( - "groupmember/" + encodeAsUTF(groupProviderName) + "/"+ encodeAsUTF(groupName) + "/" + encodeAsUTF(memberName), - "PUT"); - - Map<String, Object> groupMemberData = new HashMap<String, Object>(); - // TODO add type - writeJsonRequest(connection, groupMemberData); - - Assert.assertEquals("Unexpected response code", responseCode, connection.getResponseCode()); - - connection.disconnect(); - } - - public void createNewGroupMember(String groupProviderName, String groupName, String memberName) throws IOException - { - createNewGroupMember(groupProviderName, groupName, memberName, HttpServletResponse.SC_CREATED); - } - - public void removeMemberFromGroup(String groupProviderName, String groupName, String memberName, int responseCode) throws IOException - { - HttpURLConnection connection = openManagementConnection( - "groupmember/" + encodeAsUTF(groupProviderName) + "/"+ encodeAsUTF(groupName) + "/" + encodeAsUTF(memberName), - "DELETE"); - - Assert.assertEquals("Unexpected response code", responseCode, connection.getResponseCode()); - - connection.disconnect(); - } - - public void removeMemberFromGroup(String groupProviderName, String groupName, String memberName) throws IOException - { - removeMemberFromGroup(groupProviderName, groupName, memberName, HttpServletResponse.SC_OK); - } - - public void assertNumberOfGroupMembers(Map<String, Object> data, int expectedNumberOfGroupMembers) - { - @SuppressWarnings("unchecked") - List<Map<String, Object>> groups = (List<Map<String, Object>>) data.get("groupmembers"); - if (groups == null) - { - groups = Collections.emptyList(); - } - - Assert.assertEquals("Unexpected number of group members", expectedNumberOfGroupMembers, groups.size()); - } - - public void createGroup(String groupName, String groupProviderName) throws IOException - { - createGroup(groupName, groupProviderName, HttpServletResponse.SC_CREATED); - } - - public void createGroup(String groupName, String groupProviderName, int responseCode) throws IOException - { - HttpURLConnection connection = openManagementConnection( - "group/" + encodeAsUTF(groupProviderName) + "/"+ encodeAsUTF(groupName), - "PUT"); - - Map<String, Object> groupData = new HashMap<String, Object>(); - writeJsonRequest(connection, groupData); - - Assert.assertEquals("Unexpected response code", responseCode, connection.getResponseCode()); - - connection.disconnect(); - } - - public void createOrUpdateUser(String username, String password) throws IOException - { - createOrUpdateUser(username, password, HttpServletResponse.SC_CREATED); - } - - public void createOrUpdateUser(String username, String password, int responseCode) throws IOException - { - HttpURLConnection connection = openManagementConnection("user/" - + TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER + "/" + username, "PUT"); - - Map<String, Object> data = new HashMap<String, Object>(); - data.put("password", password); - writeJsonRequest(connection, data); - - Assert.assertEquals("Unexpected response code", responseCode, connection.getResponseCode()); - - connection.disconnect(); - } - - public void removeGroup(String groupName, String groupProviderName, int responseCode) throws IOException - { - HttpURLConnection connection = openManagementConnection( - "group/" + encodeAsUTF(groupProviderName) + "/"+ encodeAsUTF(groupName), - "DELETE"); - - Assert.assertEquals("Unexpected response code", responseCode, connection.getResponseCode()); - connection.disconnect(); - } - - public void removeGroup(String groupName, String groupProviderName) throws IOException - { - removeGroup(groupName, groupProviderName, HttpServletResponse.SC_OK); - } - - public void removeUserById(String id) throws IOException - { - HttpURLConnection connection = openManagementConnection("user/" - + TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER + "?id=" + id, "DELETE"); - Assert.assertEquals("Unexpected response code", HttpServletResponse.SC_OK, connection.getResponseCode()); - connection.disconnect(); - } - - public void removeUser(String username, int responseCode) throws IOException - { - HttpURLConnection connection = openManagementConnection("user/" - + TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER + "/" + username, "DELETE"); - Assert.assertEquals("Unexpected response code", responseCode, connection.getResponseCode()); - connection.disconnect(); - } - - public void removeUser(String username) throws IOException - { - removeUser(username, HttpServletResponse.SC_OK); - } - - public void assertNumberOfGroups(Map<String, Object> data, int expectedNumberOfGroups) - { - @SuppressWarnings("unchecked") - List<Map<String, Object>> groups = (List<Map<String, Object>>) data.get("groups"); - if (groups == null) - { - groups = Collections.emptyList(); - } - Assert.assertEquals("Unexpected number of groups", expectedNumberOfGroups, groups.size()); - } - - public void setUseSsl(boolean useSsl) - { - _useSsl = useSsl; - } - - public void setUsernameAndPassword(String username, String password) - { - _username = username; - _password = password; - } - - public void setManagementModeCredentials() - { - setUsernameAndPassword(BrokerOptions.MANAGEMENT_MODE_USER_NAME, QpidBrokerTestCase.MANAGEMENT_MODE_PASSWORD); - } - - /** - * Create password file that follows the convention username=password, which is deleted by {@link #tearDown()} - */ - public void configureTemporaryPasswordFile(QpidBrokerTestCase testCase, String... users) throws IOException - { - _passwdFile = createTemporaryPasswdFile(users); - - testCase.getBrokerConfiguration().setObjectAttribute(AuthenticationProvider.class, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER, - "path", _passwdFile.getAbsolutePath()); - } - - public void tearDown() - { - if (_passwdFile != null) - { - if (_passwdFile.exists()) - { - _passwdFile.delete(); - } - } - } - - File createTemporaryPasswdFile(String[] users) throws IOException - { - BufferedWriter writer = null; - try - { - File testFile = File.createTempFile(this.getClass().getName(),"tmp"); - testFile.deleteOnExit(); - - writer = new BufferedWriter(new FileWriter(testFile)); - for (int i = 0; i < users.length; i++) - { - String username = users[i]; - writer.write(username + ":" + username); - writer.newLine(); - } - - return testFile; - - } - finally - { - if (writer != null) - { - writer.close(); - } - } - } - - public int submitRequest(String url, String method, Map<String, Object> attributes) throws IOException - { - return submitRequest(url, method, attributes, null); - } - - public int submitRequest(String url, String method, Map<String, Object> attributes, Map<String, List<String>> responseHeadersToCapture) throws IOException - { - HttpURLConnection connection = openManagementConnection(url, method); - if (attributes != null) - { - writeJsonRequest(connection, attributes); - } - int responseCode = connection.getResponseCode(); - if (responseHeadersToCapture!= null) - { - responseHeadersToCapture.putAll(connection.getHeaderFields()); - } - connection.disconnect(); - return responseCode; - } - - public int submitRequest(String url, String method) throws IOException - { - return submitRequest(url, method, (byte[])null); - } - - public void submitRequest(String url, String method, Map<String, Object> attributes, int expectedResponseCode) throws IOException - { - Map<String, List<String>> headers = new HashMap<>(); - int responseCode = submitRequest(url, method, attributes, headers); - Assert.assertEquals("Unexpected response code from " + method + " " + url , expectedResponseCode, responseCode); - if (expectedResponseCode == 201) - { - List<String> location = headers.get("Location"); - Assert.assertTrue("Location is not returned by REST create request", location != null && location.size() == 1); - } - } - - public void submitRequest(String url, String method, int expectedResponseCode) throws IOException - { - submitRequest(url, method, null, expectedResponseCode); - } - - public int submitRequest(String url, String method, byte[] parameters) throws IOException - { - HttpURLConnection connection = openManagementConnection(url, method); - if (parameters != null) - { - OutputStream os = connection.getOutputStream(); - os.write(parameters); - os.flush(); - } - int responseCode = connection.getResponseCode(); - connection.disconnect(); - return responseCode; - } - - public byte[] getBytes(String path) throws IOException - { - HttpURLConnection connection = openManagementConnection(path, "GET"); - connection.connect(); - return readConnectionInputStream(connection); - } - - public void setUseSslAuth(final boolean useSslAuth) - { - _useSslAuth = useSslAuth; - _useSsl = true; - } - - public void createTestQueues() throws IOException, JsonGenerationException, JsonMappingException - { - for (int i = 0; i < EXPECTED_QUEUES.length; i++) - { - String queueName = EXPECTED_QUEUES[i]; - Map<String, Object> queueData = new HashMap<String, Object>(); - queueData.put(Queue.NAME, queueName); - queueData.put(Queue.DURABLE, Boolean.FALSE); - int responseCode = submitRequest("queue/test/test/" + queueName, "PUT", queueData); - Assert.assertEquals("Unexpected response code creating queue" + queueName, 201, responseCode); - - Map<String, Object> bindingData = new HashMap<String, Object>(); - bindingData.put(Binding.NAME, queueName); - bindingData.put(Binding.QUEUE, queueName); - bindingData.put(Binding.EXCHANGE, "amq.direct"); - responseCode = submitRequest("binding/test/test/amq.direct/" + queueName + "/" + queueName, "PUT", queueData); - Assert.assertEquals("Unexpected response code binding queue " + queueName, 201, responseCode); - } - } - - public String encode(String value, String encoding) throws UnsupportedEncodingException - { - return URLEncoder.encode(value, encoding).replace("+", "%20"); - } - - public String encodeAsUTF(String value) - { - try - { - return encode(value, "UTF8"); - } - catch(UnsupportedEncodingException e) - { - throw new RuntimeException("Unsupported encoding UTF8", e); - } - } -} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/BrokerCommandHelper.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/BrokerCommandHelper.java deleted file mode 100644 index 7eba3f8e71..0000000000 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/BrokerCommandHelper.java +++ /dev/null @@ -1,111 +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; -import java.util.LinkedList; -import java.util.List; - -/** - * Generates the command to start a broker by substituting the tokens - * in the provided broker command. - * - * The command is returned as a list so that it can be easily used by a - * {@link java.lang.ProcessBuilder}. - */ -public class BrokerCommandHelper -{ - private final List<String> _brokerCommandTemplateAsList; - - public BrokerCommandHelper(String brokerCommandTemplate) - { - _brokerCommandTemplateAsList = split(brokerCommandTemplate); - } - - public String[] getBrokerCommand( int port, String storePath, String storeType, File logConfigFile) - { - String[] command = new String[_brokerCommandTemplateAsList.size()]; - int i=0; - for (String commandPart : _brokerCommandTemplateAsList) - { - command[i] = commandPart - .replace("@PORT", "" + port) - .replace("@STORE_PATH", storePath) - .replace("@STORE_TYPE", storeType) - .replace("@LOG_CONFIG_FILE", '"' + logConfigFile.getAbsolutePath() + '"'); - i++; - } - return command; - } - - private int getBrokerCommandLogOptionIndex(String logOption) - { - int logOptionIndex = _brokerCommandTemplateAsList.indexOf(logOption); - if(logOptionIndex == -1) - { - throw new RuntimeException("Could not find option " + logOption + " in " + _brokerCommandTemplateAsList); - } - return logOptionIndex; - } - - - public void removeBrokerCommandLog4JFile() - { - String logOption = "-l"; - int logOptionIndex = getBrokerCommandLogOptionIndex(logOption); - if (logOptionIndex + 1 >= _brokerCommandTemplateAsList.size()) - { - throw new RuntimeException("Could not find log config location"); - } - _brokerCommandTemplateAsList.remove(logOptionIndex); - _brokerCommandTemplateAsList.remove(logOptionIndex); - } - - private static List<String> split(String str) - { - List<String> tokens = new LinkedList<String>(); - boolean inQuote = false; - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < str.length(); i++) - { - char c = str.charAt(i); - - if (c == '\"' || c == '\'') - { - inQuote = !inQuote; - } - else if (c == ' ' && !inQuote) - { - if (sb.length() > 0) - { - tokens.add(sb.toString()); - sb.delete(0, sb.length()); - } - } - else - { - sb.append(c); - } - } - if (sb.length() > 0) - { - tokens.add(sb.toString()); - } - return tokens; - } -} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/BrokerHolder.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/BrokerHolder.java deleted file mode 100644 index 4537d1a678..0000000000 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/BrokerHolder.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; - -import org.apache.qpid.server.BrokerOptions; - -public interface BrokerHolder -{ - public void start(BrokerOptions options) throws Exception; - void shutdown(); - void kill(); - String dumpThreads(); - - enum BrokerType - { - EXTERNAL /** Test case relies on a Broker started independently of the test-suite */, - INTERNAL /** Test case starts an embedded broker within this JVM */, - SPAWNED /** Test case spawns a new broker as a separate process */ - } -} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/InternalBrokerHolder.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/InternalBrokerHolder.java deleted file mode 100644 index ee2c4be3ff..0000000000 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/InternalBrokerHolder.java +++ /dev/null @@ -1,127 +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.security.PrivilegedAction; -import java.util.Set; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.Broker; -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.util.Action; - -public class InternalBrokerHolder implements BrokerHolder -{ - private static final Logger LOGGER = LoggerFactory.getLogger(InternalBrokerHolder.class); - - private Broker _broker; - - private Set<Integer> _portsUsedByBroker; - - public InternalBrokerHolder(Set<Integer> portsUsedByBroker) - { - _portsUsedByBroker = portsUsedByBroker; - } - - @Override - public void start(BrokerOptions options) throws Exception - { - if (Thread.getDefaultUncaughtExceptionHandler() == null) - { - Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() - { - @Override - public void uncaughtException(final Thread t, final Throwable e) - { - System.err.print("Thread terminated due to uncaught exception"); - e.printStackTrace(); - - LOGGER.error("Uncaught exception from thread " + t.getName(), e); - } - }); - } - - LOGGER.info("Starting internal broker (same JVM)"); - - _broker = new Broker(new Action<Integer>() - { - @Override - public void performAction(final Integer object) - { - _broker = null; - } - }); - _broker.startup(options); - } - - public void shutdown() - { - LOGGER.info("Shutting down Broker instance"); - - Subject.doAs(SecurityManager.getSystemTaskSubject("Shutdown"), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - if(_broker != null) - { - _broker.shutdown(); - } - return null; - } - - - }); - waitUntilPortsAreFree(); - - LOGGER.info("Broker instance shutdown"); - } - - @Override - public void kill() - { - // Can't kill a internal broker as we would also kill ourselves as we share the same JVM. - shutdown(); - } - - private void waitUntilPortsAreFree() - { - new PortHelper().waitUntilPortsAreFree(_portsUsedByBroker); - } - - @Override - public String dumpThreads() - { - return TestUtils.dumpThreads(); - } - - @Override - public String toString() - { - return "InternalBrokerHolder [_portsUsedByBroker=" + _portsUsedByBroker + "]"; - } - -} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/JMXTestUtils.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/JMXTestUtils.java deleted file mode 100644 index 4e5c4ca034..0000000000 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/JMXTestUtils.java +++ /dev/null @@ -1,452 +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 junit.framework.TestCase; - -import org.apache.qpid.management.common.JMXConnnectionFactory; -import org.apache.qpid.management.common.mbeans.LoggingManagement; -import org.apache.qpid.management.common.mbeans.ManagedBroker; -import org.apache.qpid.management.common.mbeans.ManagedConnection; -import org.apache.qpid.management.common.mbeans.ManagedExchange; -import org.apache.qpid.management.common.mbeans.ManagedQueue; -import org.apache.qpid.management.common.mbeans.ServerInformation; -import org.apache.qpid.management.common.mbeans.UserManagement; - -import javax.management.InstanceNotFoundException; -import javax.management.JMException; -import javax.management.ListenerNotFoundException; -import javax.management.MBeanException; -import javax.management.MBeanServerConnection; -import javax.management.MBeanServerInvocationHandler; -import javax.management.MalformedObjectNameException; -import javax.management.NotificationFilter; -import javax.management.NotificationListener; -import javax.management.ObjectName; -import javax.management.remote.JMXConnector; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -/** - * JMX access for tests. - */ -public class JMXTestUtils -{ - public static final String DEFAULT_PASSWORD = "admin"; - public static final String DEFAULT_USERID = "admin"; - - private MBeanServerConnection _mbsc; - private JMXConnector _jmxc; - - private final String _user; - private final String _password; - private final QpidBrokerTestCase _test; - - public JMXTestUtils(QpidBrokerTestCase test, String user, String password) - { - _test = test; - _user = user; - _password = password; - } - - public JMXTestUtils(QpidBrokerTestCase test) - { - this(test, DEFAULT_USERID, DEFAULT_PASSWORD); - } - - public void open() throws Exception - { - open(0); // Zero signifies default broker to QBTC. - } - - public void open(final int brokerPort) throws Exception - { - int actualBrokerPort = _test.getPort(brokerPort); - int managementPort = _test.getManagementPort(actualBrokerPort); - - _jmxc = JMXConnnectionFactory.getJMXConnection(5000, "127.0.0.1", - managementPort, _user, _password); - - _mbsc = _jmxc.getMBeanServerConnection(); - } - - public void close() throws IOException - { - if(_jmxc != null) - { - _jmxc.close(); - } - } - - public void addNotificationListener(ObjectName name, NotificationListener listener, NotificationFilter filter, Object handback) - throws InstanceNotFoundException, IOException - { - _mbsc.addNotificationListener(name, listener, filter, handback); - } - - public void removeNotificationListener(ObjectName name, NotificationListener listener) - throws InstanceNotFoundException, IOException, ListenerNotFoundException - { - _mbsc.removeNotificationListener(name, listener); - } - - /** - * Create a non-durable exchange with the requested name - * - * @throws JMException if a exchange with this name already exists - * @throws IOException if there is a problem with the JMX Connection - * @throws MBeanException if there is another problem creating the exchange - */ - public void createExchange(String virtualHostName, String name, String type, boolean durable) - throws JMException, IOException, MBeanException - { - ManagedBroker managedBroker = getManagedBroker(virtualHostName); - - managedBroker.createNewExchange(name, type, durable); - } - - /** - * Create a non-durable queue (with no owner) that is named after the - * creating test. - * - * @throws JMException if a queue with this name already exists - * @throws IOException if there is a problem with the JMX Connection - * @throws MBeanException if there is another problem creating the exchange - */ - public void createQueue(String virtualHostName, String name, String owner, boolean durable) - throws JMException, MBeanException, IOException - { - ManagedBroker managedBroker = getManagedBroker(virtualHostName); - - managedBroker.createNewQueue(name, owner, durable); - } - - /** - * Unregisters all the channels, queuebindings etc and unregisters - * this exchange from managed objects. - * - * @throws JMException if an exchange with this name does not exist - * @throws IOException if there is a problem with the JMX Connection - * @throws MBeanException if there is another problem creating the exchange - */ - public void unregisterExchange(String virtualHostName, String exchange) - throws IOException, JMException, MBeanException - { - ManagedBroker managedBroker = getManagedBroker(virtualHostName); - managedBroker.unregisterExchange(exchange); - } - - /** - * Unregisters the Queue bindings, removes the subscriptions and unregisters - * from the managed objects. - * - * @throws JMException if a queue with this name does not exist - * @throws IOException if there is a problem with the JMX Connection - * @throws MBeanException if there is another problem creating the exchange - */ - public void deleteQueue(String virtualHostName, String queueName) - throws IOException, JMException, MBeanException - { - ManagedBroker managedBroker = getManagedBroker(virtualHostName); - managedBroker.deleteQueue(queueName); - } - - /** - * Sets the logging level. - * - * @throws JMException - * @throws IOException if there is a problem with the JMX Connection - * @throws MBeanException - */ - public void setRuntimeLoggerLevel(String logger, String level) - throws IOException, JMException, MBeanException - { - LoggingManagement loggingManagement = getLoggingManagement(); - loggingManagement.setRuntimeLoggerLevel(logger, level); - } - - /** - * Reload logging config file. - * - * @throws JMException - * @throws IOException if there is a problem with the JMX Connection - * @throws MBeanException - */ - public void reloadConfigFile() - throws IOException, JMException, MBeanException - { - LoggingManagement loggingManagement = getLoggingManagement(); - loggingManagement.reloadConfigFile(); - } - - /** - * Get list of available logger levels. - * - * @throws JMException - * @throws IOException if there is a problem with the JMX Connection - * @throws MBeanException - */ - public String[] getAvailableLoggerLevels() - throws IOException, JMException, MBeanException - { - LoggingManagement loggingManagement = getLoggingManagement(); - return loggingManagement.getAvailableLoggerLevels(); - } - - /** - * Set root logger level. - * - * @throws JMException - * @throws IOException if there is a problem with the JMX Connection - * @throws MBeanException - */ - public void setRuntimeRootLoggerLevel(String level) - throws IOException, JMException, MBeanException - { - LoggingManagement loggingManagement = getLoggingManagement(); - loggingManagement.setRuntimeRootLoggerLevel(level); - } - - /** - * Get root logger level. - * - * @throws JMException - * @throws IOException if there is a problem with the JMX Connection - * @throws MBeanException - */ - public String getRuntimeRootLoggerLevel() - throws IOException, JMException, MBeanException - { - LoggingManagement loggingManagement = getLoggingManagement(); - return loggingManagement.getRuntimeRootLoggerLevel(); - } - - /** - * Retrieve the ObjectName for a Virtualhost. - * - * This is then used to create a proxy to the ManagedBroker MBean. - * - * @param virtualHostName the VirtualHost to retrieve - * @return the ObjectName for the VirtualHost - */ - @SuppressWarnings("static-access") - public ObjectName getVirtualHostManagerObjectName(String vhostName) - { - // Get the name of the test manager - String query = "org.apache.qpid:type=VirtualHost.VirtualHostManager,VirtualHost=" - + ObjectName.quote(vhostName) + ",*"; - - Set<ObjectName> objectNames = queryObjects(query); - - _test.assertNotNull("Null ObjectName Set returned", objectNames); - _test.assertEquals("Incorrect number test vhosts returned", 1, objectNames.size()); - - // We have verified we have only one value in objectNames so return it - ObjectName objectName = objectNames.iterator().next(); - _test.getLogger().info("Loading: " + objectName); - return objectName; - } - - /** - * Retrieve the ObjectName for the given Queue on a Virtualhost. - * - * This is then used to create a proxy to the ManagedQueue MBean. - * - * @param virtualHostName the VirtualHost the Queue is on - * @param queue The Queue to retireve - * @return the ObjectName for the given queue on the VirtualHost - */ - @SuppressWarnings("static-access") - public ObjectName getQueueObjectName(String virtualHostName, String queue) - { - // Get the name of the test manager - String query = getQueueObjectNameString(virtualHostName, queue); - - Set<ObjectName> objectNames = queryObjects(query); - - _test.assertNotNull("Null ObjectName Set returned", objectNames); - _test.assertEquals("Incorrect number of queues with name '" + queue + "' returned", 1, objectNames.size()); - - // We have verified we have only one value in objectNames so return it - ObjectName objectName = objectNames.iterator().next(); - _test.getLogger().info("Loading: " + objectName); - return objectName; - } - - public String getQueueObjectNameString(String virtualHostName, String queue) { - return "org.apache.qpid:type=VirtualHost.Queue,VirtualHost=" - + ObjectName.quote(virtualHostName) + ",name=" - + ObjectName.quote(queue) + ",*"; - } - - /** - * Generate the ObjectName for the given Exchange on a VirtualHost. - */ - public String getExchangeObjectName(String virtualHostName, String exchange) - { - return "org.apache.qpid:type=VirtualHost.Exchange,VirtualHost=" - + ObjectName.quote(virtualHostName) + ",name=" - + ObjectName.quote(exchange) + ",*"; - } - - @SuppressWarnings("static-access") - public <T> T getManagedObject(Class<T> managedClass, String query) - { - Set<ObjectName> objectNames = queryObjects(query); - - _test.assertNotNull("Null ObjectName Set returned", objectNames); - _test.assertEquals("Unexpected number of objects matching " + managedClass + " returned", 1, objectNames.size()); - - ObjectName objectName = objectNames.iterator().next(); - _test.getLogger().info("Loading: " + objectName); - return getManagedObject(managedClass, objectName); - } - - public boolean doesManagedObjectExist(String query) - { - return !queryObjects(query).isEmpty(); - } - - public int getNumberOfObjects(String query) - { - return queryObjects(query).size(); - } - - public <T> T getManagedObject(Class<T> managedClass, ObjectName objectName) - { - return MBeanServerInvocationHandler.newProxyInstance(_mbsc, objectName, managedClass, false); - } - - public <T> List<T> getManagedObjectList(Class<T> managedClass, Set<ObjectName> objectNames) - { - List<T> objects = new ArrayList<T>(); - for (ObjectName name : objectNames) - { - objects.add(getManagedObject(managedClass, name)); - } - return objects; - } - - public ManagedBroker getManagedBroker(String virtualHost) - { - return getManagedObject(ManagedBroker.class, getVirtualHostManagerObjectName(virtualHost)); - } - - @SuppressWarnings("static-access") - public ManagedExchange getManagedExchange(String exchangeName) - { - String query = getExchangeObjectName("test", exchangeName); - - Set<ObjectName> objectNames = queryObjects(query); - - _test.assertNotNull("Null ObjectName Set returned", objectNames); - _test.assertEquals("Incorrect number of exchange with name '" + exchangeName + "' returned", 1, objectNames.size()); - - // We have verified we have only one value in objectNames so return an mbean proxy for it - ObjectName objectName = objectNames.iterator().next(); - _test.getLogger().info("Loading: " + objectName); - - return MBeanServerInvocationHandler.newProxyInstance(_mbsc, objectName, ManagedExchange.class, false); - } - - public ManagedQueue getManagedQueue(String queueName) - { - ObjectName objectName = getQueueObjectName("test", queueName); - return getManagedObject(ManagedQueue.class, objectName); - } - - public LoggingManagement getLoggingManagement() throws MalformedObjectNameException - { - ObjectName objectName = new ObjectName("org.apache.qpid:type=LoggingManagement,name=LoggingManagement"); - return getManagedObject(LoggingManagement.class, objectName); - } - - public UserManagement getUserManagement(String name) throws MalformedObjectNameException - { - String umName = ObjectName.quote(UserManagement.TYPE + "-" + name); - ObjectName objectName = new ObjectName("org.apache.qpid:type=UserManagement,name=" + umName); - return getManagedObject(UserManagement.class, objectName); - } - - /** - * Retrieve {@link ServerInformation} JMX MBean. - */ - public ServerInformation getServerInformation() - { - // Get the name of the test manager - String query = "org.apache.qpid:type=ServerInformation,name=ServerInformation,*"; - - Set<ObjectName> objectNames = queryObjects(query); - - TestCase.assertNotNull("Null ObjectName Set returned", objectNames); - TestCase.assertEquals("Incorrect number of objects returned", 1, objectNames.size()); - - // We have verified we have only one value in objectNames so return it - return getManagedObject(ServerInformation.class, objectNames.iterator().next()); - } - - /** - * Retrieve all {@link ManagedConnection} objects. - */ - public List<ManagedConnection> getAllManagedConnections() - { - // Get the name of the test manager - String query = "org.apache.qpid:type=VirtualHost.Connection,VirtualHost=*,name=*"; - - Set<ObjectName> objectNames = queryObjects(query); - - TestCase.assertNotNull("Null ObjectName Set returned", objectNames); - - return getManagedObjectList(ManagedConnection.class, objectNames); - } - - /** - * Retrieve all {@link ManagedConnection} objects for a particular virtual host. - */ - public List<ManagedConnection> getManagedConnections(String vhost) - { - // Get the name of the test manager - String query = "org.apache.qpid:type=VirtualHost.Connection,VirtualHost=" + ObjectName.quote(vhost) + ",name=*"; - - Set<ObjectName> objectNames = queryObjects(query); - - TestCase.assertNotNull("Null ObjectName Set returned", objectNames); - - return getManagedObjectList(ManagedConnection.class, objectNames); - } - - /** - * Returns the Set of ObjectNames returned by the broker for the given query. - */ - private Set<ObjectName> queryObjects(String query) - { - try - { - return _mbsc.queryNames(new ObjectName(query), null); - } - catch (Exception e) - { - throw new RuntimeException("Error using query: " + query, e); - } - } -} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/Piper.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/Piper.java deleted file mode 100644 index 98e3c96c0a..0000000000 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/Piper.java +++ /dev/null @@ -1,120 +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.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public final class Piper extends Thread -{ - private static final Logger LOGGER = LoggerFactory.getLogger(Piper.class); - - private final BufferedReader _in; - private final Logger _out; - private final String _ready; - private final CountDownLatch _latch; - private final String _stopped; - private volatile boolean _seenReady; - private volatile String _stopLine; - - public Piper(InputStream in, String ready, String stopped, String threadName, String loggerName) - { - super(threadName); - _in = new BufferedReader(new InputStreamReader(in)); - _out = LoggerFactory.getLogger(loggerName); - _ready = ready; - _stopped = stopped; - _seenReady = false; - - if (this._ready != null && !this._ready.equals("")) - { - this._latch = new CountDownLatch(1); - } - else - { - this._latch = null; - } - } - - public boolean await(long timeout, TimeUnit unit) throws InterruptedException - { - if (_latch == null) - { - return true; - } - else - { - _latch.await(timeout, unit); - return _seenReady; - } - } - - public void run() - { - try - { - String line; - while ((line = _in.readLine()) != null) - { - _out.info(line); - - if (_latch != null && line.contains(_ready)) - { - _seenReady = true; - _latch.countDown(); - } - - if (!_seenReady && line.contains(_stopped)) - { - _stopLine = line; - } - } - } - catch (IOException e) - { - LOGGER.warn(e.getMessage() + " : Broker stream from unexpectedly closed; last log lines written by Broker may be lost."); - } - finally - { - if (_latch != null) - { - _latch.countDown(); - } - } - } - - public String getStopLine() - { - return _stopLine; - } - - String getReady() - { - return _ready; - } -} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java deleted file mode 100755 index 9bcc2cb3ae..0000000000 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java +++ /dev/null @@ -1,1318 +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; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.jms.BytesMessage; -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MapMessage; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.ObjectMessage; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.StreamMessage; -import javax.jms.TextMessage; -import javax.jms.Topic; -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; - -import org.apache.log4j.FileAppender; -import org.apache.log4j.LogManager; -import org.apache.log4j.Logger; -import org.apache.log4j.xml.DOMConfigurator; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.AMQConnectionFactory; -import org.apache.qpid.client.AMQConnectionURL; -import org.apache.qpid.client.AMQQueue; -import org.apache.qpid.client.AMQTopic; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.server.Broker; -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.configuration.updater.TaskExecutorImpl; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.store.MemoryConfigurationStore; -import org.apache.qpid.server.virtualhostnode.AbstractVirtualHostNode; -import org.apache.qpid.server.virtualhostnode.JsonVirtualHostNode; -import org.apache.qpid.url.URLSyntaxException; -import org.apache.qpid.util.FileUtils; -import org.apache.qpid.util.SystemUtils; - -/** - * Qpid base class for system testing test cases. - */ -public class QpidBrokerTestCase extends QpidTestCase -{ - private TaskExecutor _taskExecutor; - - public static final String GUEST_USERNAME = "guest"; - public static final String GUEST_PASSWORD = "guest"; - - private final File _configFile = new File(System.getProperty("broker.config")); - private File _spawnedBrokerLogConfigFile; - protected final String _brokerStoreType = System.getProperty("broker.config-store-type", "JSON"); - protected static final Logger _logger = Logger.getLogger(QpidBrokerTestCase.class); - protected static final int LOGMONITOR_TIMEOUT = 5000; - - protected long RECEIVE_TIMEOUT = 1000l; - - private Map<String, String> _propertiesSetForBroker = new HashMap<String, String>(); - - private Map<Integer, TestBrokerConfiguration> _brokerConfigurations; - - protected static final String INDEX = "index"; - protected static final String CONTENT = "content"; - - private static final String DEFAULT_INITIAL_CONTEXT = "org.apache.qpid.jndi.PropertiesFileInitialContextFactory"; - - static - { - String initialContext = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); - - if (initialContext == null || initialContext.length() == 0) - { - System.setProperty(Context.INITIAL_CONTEXT_FACTORY, DEFAULT_INITIAL_CONTEXT); - } - } - - // system properties - private static final String BROKER_LANGUAGE = "broker.language"; - protected static final String BROKER_TYPE = "broker.type"; - private static final String BROKER_COMMAND = "broker.command"; - private static final String BROKER_COMMAND_PLATFORM = "broker.command." + SystemUtils.getOSConfigSuffix(); - private static final String BROKER_CLEAN_BETWEEN_TESTS = "broker.clean.between.tests"; - private static final String BROKER_VERSION = "broker.version"; - private static final String TEST_OUTPUT = "test.output"; - private static final String BROKER_PERSITENT = "broker.persistent"; - public static final String PROFILE_USE_SSL = "profile.use_ssl"; - - public static final int DEFAULT_PORT_VALUE = 5672; - public static final int DEFAULT_SSL_PORT_VALUE = 5671; - public static final int DEFAULT_JMXPORT_REGISTRYSERVER = 8999; - public static final int JMXPORT_CONNECTORSERVER_OFFSET = 100; - public static final int DEFAULT_HTTP_MANAGEMENT_PORT_VALUE = 8080; - - public static final String TEST_AMQP_PORT_PROTOCOLS_PROPERTY="test.amqp_port_protocols"; - - // values - protected static final String JAVA = "java"; - - public static final int DEFAULT_PORT = Integer.getInteger("test.port", DEFAULT_PORT_VALUE); - public static final int FAILING_PORT = Integer.parseInt(System.getProperty("test.port.alt")); - public static final int DEFAULT_MANAGEMENT_PORT = Integer.getInteger("test.mport", DEFAULT_JMXPORT_REGISTRYSERVER); - public static final int DEFAULT_HTTP_MANAGEMENT_PORT = Integer.getInteger("test.hport", DEFAULT_HTTP_MANAGEMENT_PORT_VALUE); - public static final int DEFAULT_SSL_PORT = Integer.getInteger("test.port.ssl", DEFAULT_SSL_PORT_VALUE); - - protected String _brokerLanguage = System.getProperty(BROKER_LANGUAGE, JAVA); - protected BrokerHolder.BrokerType _brokerType = BrokerHolder.BrokerType.valueOf(System.getProperty(BROKER_TYPE, "").toUpperCase()); - - private static final String BROKER_COMMAND_TEMPLATE = System.getProperty(BROKER_COMMAND_PLATFORM, System.getProperty(BROKER_COMMAND)); - - private Boolean _brokerCleanBetweenTests = Boolean.getBoolean(BROKER_CLEAN_BETWEEN_TESTS); - private final Protocol _brokerProtocol = Protocol.valueOf("AMQP_" + System.getProperty(BROKER_VERSION, " ").substring(1)); - protected String _output = System.getProperty(TEST_OUTPUT, System.getProperty("java.io.tmpdir")); - protected Boolean _brokerPersistent = Boolean.getBoolean(BROKER_PERSITENT); - - protected File _outputFile; - - protected Map<Integer, BrokerHolder> _brokers = new HashMap<Integer, BrokerHolder>(); - - protected InitialContext _initialContext; - protected AMQConnectionFactory _connectionFactory; - - // the connections created for a given test - protected List<Connection> _connections = new ArrayList<Connection>(); - public static final String QUEUE = "queue"; - public static final String TOPIC = "topic"; - public static final String MANAGEMENT_MODE_PASSWORD = "mm_password"; - - /** Map to hold test defined environment properties */ - private Map<String, String> _env; - - /** Ensure our messages have some sort of size */ - protected static final int DEFAULT_MESSAGE_SIZE = 1024; - - /** Size to create our message*/ - private int _messageSize = DEFAULT_MESSAGE_SIZE; - private String _brokerCommandTemplate; - - /** Type of message*/ - protected enum MessageType - { - BYTES, - MAP, - OBJECT, - STREAM, - TEXT - } - private MessageType _messageType = MessageType.TEXT; - - public QpidBrokerTestCase() - { - super(); - _brokerConfigurations = new HashMap<Integer, TestBrokerConfiguration>(); - initialiseSpawnedBrokerLogConfigFile(); - _brokerCommandTemplate = BROKER_COMMAND_TEMPLATE; - - - if (JAVA.equals(_brokerLanguage)) - { - try - { - Broker.populateSystemPropertiesFromDefaults(null); - } - catch (IOException ioe) - { - throw new RuntimeException("Failed to load Java broker system properties", ioe); - } - } - } - - public TestBrokerConfiguration getBrokerConfiguration(int port) - { - int actualPort = getPort(port); - - synchronized (_brokerConfigurations) - { - TestBrokerConfiguration configuration = _brokerConfigurations.get(actualPort); - if (configuration == null) - { - configuration = createBrokerConfiguration(actualPort); - } - return configuration; - } - } - - public TestBrokerConfiguration getBrokerConfiguration() - { - return getBrokerConfiguration(DEFAULT_PORT); - } - - public TestBrokerConfiguration createBrokerConfiguration(int port) - { - int actualPort = getPort(port); - if(_taskExecutor == null) - { - _taskExecutor = new TaskExecutorImpl(); - _taskExecutor.start(); - } - TestBrokerConfiguration configuration = new TestBrokerConfiguration(_brokerStoreType, _configFile.getAbsolutePath(), _taskExecutor); - synchronized (_brokerConfigurations) - { - _brokerConfigurations.put(actualPort, configuration); - } - if (actualPort != DEFAULT_PORT) - { - configuration.setObjectAttribute(Port.class, TestBrokerConfiguration.ENTRY_NAME_AMQP_PORT, Port.PORT, actualPort); - configuration.setObjectAttribute(Port.class, TestBrokerConfiguration.ENTRY_NAME_RMI_PORT, Port.PORT, getManagementPort(actualPort)); - configuration.setObjectAttribute(Port.class, TestBrokerConfiguration.ENTRY_NAME_JMX_PORT, Port.PORT, getManagementPort(actualPort) + JMXPORT_CONNECTORSERVER_OFFSET); - - String workDir = System.getProperty("QPID_WORK") + File.separator + TestBrokerConfiguration.ENTRY_NAME_VIRTUAL_HOST + File.separator + actualPort; - configuration.setObjectAttribute(VirtualHostNode.class, TestBrokerConfiguration.ENTRY_NAME_VIRTUAL_HOST, JsonVirtualHostNode.STORE_PATH, workDir); - } - - return configuration; - } - - private void initialiseSpawnedBrokerLogConfigFile() - { - _spawnedBrokerLogConfigFile = new File(SPAWNED_BROKER_LOG4J_CONFIG_FILE_PATH); - if(!_spawnedBrokerLogConfigFile.exists()) - { - throw new RuntimeException("Log config file " + _spawnedBrokerLogConfigFile.getAbsolutePath() + " does not exist"); - } - } - - public Logger getLogger() - { - return QpidBrokerTestCase._logger; - } - - @Override - public void runBare() throws Throwable - { - // Initialize this for each test run - _env = new HashMap<String, String>(); - - // Log4j properties expects this to be set - System.setProperty("qpid.testMethod", "-" + getName()); - System.setProperty("qpid.testClass", getClass().getName()); - - String log4jConfigFile = System.getProperty("log4j.configuration.file"); - DOMConfigurator.configure(log4jConfigFile); - - // get log file from file appender - _outputFile = new File(((FileAppender)LogManager.getRootLogger().getAllAppenders().nextElement()).getFile()); - - try - { - super.runBare(); - } - catch (Exception e) - { - _logger.error("exception", e); - throw e; - } - finally - { - stopAllBrokers(); - - // reset properties used in the test - revertSystemProperties(); - revertLoggingLevels(); - - if (_brokerCleanBetweenTests) - { - final String qpidWork = System.getProperty("QPID_WORK"); - cleanBrokerWork(qpidWork); - createBrokerWork(qpidWork); - } - - _logger.info("========== stop " + getTestName() + " =========="); - - LogManager.resetConfiguration(); - } - } - - @Override - protected void setUp() throws Exception - { - super.setUp(); - _taskExecutor = new TaskExecutorImpl(); - _taskExecutor.start(); - if (!_configFile.exists()) - { - fail("Unable to test without config file:" + _configFile); - } - - startBroker(); - } - - /** - * Return the management port in use by the broker on this main port - * - * @param mainPort the broker's main port. - * - * @return the management port that corresponds to the broker on the given port - */ - protected int getManagementPort(int mainPort) - { - return mainPort + (DEFAULT_MANAGEMENT_PORT - DEFAULT_PORT); - } - - /** - * The returned set of port numbers is only a guess because it assumes no ports have been overridden - * using system properties. - */ - protected Set<Integer> guessAllPortsUsedByBroker(int mainPort) - { - Set<Integer> ports = new HashSet<Integer>(); - int managementPort = getManagementPort(mainPort); - int connectorServerPort = managementPort + JMXPORT_CONNECTORSERVER_OFFSET; - - ports.add(mainPort); - ports.add(managementPort); - ports.add(connectorServerPort); - ports.add(DEFAULT_SSL_PORT); - - return ports; - } - - /** - * Get the Port that is use by the current broker - * - * @return the current port - */ - protected int getPort() - { - return getPort(0); - } - - protected int getPort(int port) - { - if (!_brokerType.equals(BrokerHolder.BrokerType.EXTERNAL)) - { - return port == 0 ? DEFAULT_PORT : port; - } - else - { - return port; - } - } - - public void startBroker() throws Exception - { - startBroker(0); - } - - public void startBroker(int port) throws Exception - { - startBroker(port, false); - } - - public void startBroker(int port, boolean managementMode) throws Exception - { - startBroker(port, managementMode, null); - } - - public void startBroker(int port, boolean managementMode, String log4jFile) throws Exception - { - int actualPort = getPort(port); - TestBrokerConfiguration configuration = getBrokerConfiguration(actualPort); - startBroker(actualPort, configuration, managementMode, log4jFile); - } - - protected File getBrokerCommandLog4JFile() - { - return _spawnedBrokerLogConfigFile; - } - - protected void setBrokerCommandLog4JFile(File file) - { - _spawnedBrokerLogConfigFile = file; - _logger.info("Modified log config file to: " + file); - } - - public void startBroker(int port, TestBrokerConfiguration testConfiguration, String log4jFile) throws Exception - { - startBroker(port, testConfiguration, false, log4jFile); - } - - protected void startBroker(int port, TestBrokerConfiguration testConfiguration, boolean managementMode, String log4jFile) throws Exception - { - port = getPort(port); - - if(_brokers.get(port) != null) - { - throw new IllegalStateException("There is already an existing broker running on port " + port); - } - - String testConfig = saveTestConfiguration(port, testConfiguration); - String log4jConfig = log4jFile == null ? getBrokerCommandLog4JFile().getAbsolutePath() : log4jFile; - BrokerOptions options = getBrokerOptions(managementMode, testConfig, log4jConfig, log4jFile == null); - BrokerHolder holder = new BrokerHolderFactory().create(_brokerType, port, this); - _brokers.put(port, holder); - holder.start(options); - } - - private boolean existingInternalBroker() - { - for(BrokerHolder holder : _brokers.values()) - { - if(holder instanceof InternalBrokerHolder) - { - return true; - } - } - - return false; - } - - public String getTestConfigFile(int port) - { - return _output + File.separator + getTestQueueName() + "-" + port + "-config"; - } - - protected String getPathRelativeToWorkingDirectory(String file) - { - File configLocation = new File(file); - File workingDirectory = new File(System.getProperty("user.dir")); - - _logger.debug("Converting path to be relative to working directory: " + file); - - try - { - String configPath = configLocation.getAbsolutePath(); - String workingDirectoryPath = workingDirectory.getCanonicalPath(); - if (SystemUtils.isWindows()) - { - configPath = configPath.toLowerCase(); - workingDirectoryPath = workingDirectoryPath.toLowerCase(); - } - if(!configPath.startsWith(workingDirectoryPath)) - { - throw new RuntimeException("Provided path is not a child of the working directory: " + workingDirectoryPath); - } - - String substring = configPath.replace(workingDirectoryPath, "").substring(1); - _logger.debug("Converted relative path: " + substring); - - return substring; - } - catch (IOException e) - { - throw new RuntimeException("Problem while converting to relative path", e); - } - } - - protected String saveTestConfiguration(int port, TestBrokerConfiguration testConfiguration) - { - String testConfig = getTestConfigFile(port); - String relative = getPathRelativeToWorkingDirectory(testConfig); - if (testConfiguration != null && !testConfiguration.isSaved()) - { - _logger.info("Saving test broker configuration at: " + testConfig); - testConfiguration.save(new File(testConfig)); - testConfiguration.setSaved(true); - } - return relative; - } - - protected void cleanBrokerWork(final String qpidWork) - { - if (qpidWork != null) - { - _logger.info("Cleaning broker work dir: " + qpidWork); - - File file = new File(qpidWork); - if (file.exists()) - { - final boolean success = FileUtils.delete(file, true); - if(!success) - { - throw new RuntimeException("Failed to recursively delete beneath : " + file); - } - } - } - } - - protected void createBrokerWork(final String qpidWork) - { - if (qpidWork != null) - { - final File dir = new File(qpidWork); - dir.mkdirs(); - if (!dir.isDirectory()) - { - throw new RuntimeException("Failed to created Qpid work directory : " + qpidWork); - } - } - } - - public void stopBroker() - { - stopBroker(0); - } - - public void stopAllBrokers() - { - boolean exceptionOccured = false; - Set<Integer> runningBrokerPorts = new HashSet<Integer>(getBrokerPortNumbers()); - for (int brokerPortNumber : runningBrokerPorts) - { - if (!stopBrokerSafely(brokerPortNumber)) - { - exceptionOccured = true; - } - } - if (exceptionOccured) - { - throw new RuntimeException("Exception occurred on stopping of test broker. Please, examine logs for details"); - } - } - - protected boolean stopBrokerSafely(int brokerPortNumber) - { - boolean success = true; - BrokerHolder broker = _brokers.get(brokerPortNumber); - try - { - stopBroker(brokerPortNumber); - } - catch(Exception e) - { - success = false; - _logger.error("Failed to stop broker " + broker + " at port " + brokerPortNumber, e); - if (broker != null) - { - // save the thread dump in case of dead locks - try - { - _logger.error("Broker " + broker + " thread dump:" + broker.dumpThreads()); - } - finally - { - // try to kill broker - try - { - broker.kill(); - } - catch(Exception killException) - { - // ignore - } - } - } - } - return success; - } - - public void stopBroker(int port) - { - if (isBrokerPresent(port)) - { - port = getPort(port); - - _logger.info("stopping broker on port : " + port); - BrokerHolder broker = _brokers.remove(port); - broker.shutdown(); - } - } - - public void killBroker() - { - killBroker(0); - } - - public void killBroker(int port) - { - if (isBrokerPresent(port)) - { - port = getPort(port); - - _logger.info("killing broker on port : " + port); - BrokerHolder broker = _brokers.remove(port); - broker.kill(); - } - } - - public boolean isBrokerPresent(int port) - { - port = getPort(port); - - return _brokers.containsKey(port); - } - - public BrokerHolder getBroker(int port) throws Exception - { - port = getPort(port); - return _brokers.get(port); - } - - public Set<Integer> getBrokerPortNumbers() - { - return new HashSet<Integer>(_brokers.keySet()); - } - - /** - * Creates a new virtual host node in broker configuration for given broker port - * @param brokerPort broker port - * @param virtualHostNodeName virtual host node name - */ - protected void createTestVirtualHostNode(int brokerPort, String virtualHostNodeName, boolean withBlueprint) - { - String storeType = getTestProfileVirtualHostNodeType(); - String storeDir = null; - - if (System.getProperty("profile", "").startsWith("java-dby-mem")) - { - storeDir = ":memory:"; - } - else if (!MemoryConfigurationStore.TYPE.equals(storeType)) - { - storeDir = "${QPID_WORK}" + File.separator + virtualHostNodeName + File.separator + brokerPort; - } - - // add new virtual host node with vhost blueprint configuration to the broker store - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(VirtualHostNode.NAME, virtualHostNodeName); - attributes.put(VirtualHostNode.TYPE, storeType); - if (storeDir != null) - { - attributes.put(JsonVirtualHostNode.STORE_PATH, storeDir); - } - - if (withBlueprint) - { - final String blueprint = getTestProfileVirtualHostNodeBlueprint(); - - attributes.put(ConfiguredObject.CONTEXT, - Collections.singletonMap(AbstractVirtualHostNode.VIRTUALHOST_BLUEPRINT_CONTEXT_VAR, - blueprint)); - } - - int port = getPort(brokerPort); - getBrokerConfiguration(port).addObjectConfiguration(VirtualHostNode.class, attributes); - } - - protected void createTestVirtualHostNode(int brokerPort, String virtualHostNodeName) - { - createTestVirtualHostNode(brokerPort, virtualHostNodeName, true); - } - - /** - * Set a System property that is to be applied only to the external test - * broker. - * - * This is a convenience method to enable the setting of a -Dproperty=value - * entry in QPID_OPTS - * - * This is only useful for the External Java Broker tests. - * - * @param property the property name - * @param value the value to set the property to - */ - protected void setBrokerOnlySystemProperty(String property, String value) - { - synchronized (_propertiesSetForBroker) - { - if (!_propertiesSetForBroker.containsKey(property)) - { - _propertiesSetForBroker.put(property, value); - } - } - } - - /** - * Set a System (-D) property for this test run. - * - * This convenience method copies the current VMs System Property - * for the external VM Broker. - * - * @param property the System property to set - */ - protected void setSystemProperty(String property) - { - String value = System.getProperty(property); - if (value != null) - { - setSystemProperty(property, value); - } - } - - /** - * Set a System property for the duration of this test. - * - * When the test run is complete the value will be reverted. - * - * The values set using this method will also be propagated to the external - * Java Broker via a -D value defined in QPID_OPTS. - * - * If the value should not be set on the broker then use - * setTestClientSystemProperty(). - * - * @param property the property to set - * @param value the new value to use - */ - protected void setSystemProperty(String property, String value) - { - synchronized(_propertiesSetForBroker) - { - // Record the value for the external broker - if (value == null) - { - _propertiesSetForBroker.remove(property); - } - else - { - _propertiesSetForBroker.put(property, value); - } - } - //Set the value for the test client vm aswell. - setTestClientSystemProperty(property, value); - } - - /** - * Set a System property for the client (and broker if using the same vm) of this test. - * - * @param property The property to set - * @param value the value to set it to. - */ - protected void setTestClientSystemProperty(String property, String value) - { - setTestSystemProperty(property, value); - } - - /** - * Restore the System property values that were set before this test run. - */ - protected void revertSystemProperties() - { - revertTestSystemProperties(); - - // We don't change the current VMs settings for Broker only properties - // so we can just clear this map - _propertiesSetForBroker.clear(); - } - - /** - * Add an environment variable for the external broker environment - * - * @param property the property to set - * @param value the value to set it to - */ - protected void setBrokerEnvironment(String property, String value) - { - _env.put(property, value); - } - - /** - * Check whether the broker is an 0.8 - * - * @return true if the broker is an 0_8 version, false otherwise. - */ - public boolean isBroker08() - { - return _brokerProtocol.equals(Protocol.AMQP_0_8); - } - - public boolean isBroker010() - { - return _brokerProtocol.equals(Protocol.AMQP_0_10); - } - - public Protocol getBrokerProtocol() - { - return _brokerProtocol; - } - - protected boolean isJavaBroker() - { - return _brokerLanguage.equals("java"); - } - - protected boolean isCppBroker() - { - return _brokerLanguage.equals("cpp"); - } - - protected boolean isExternalBroker() - { - return !isInternalBroker(); - } - - protected boolean isInternalBroker() - { - return _brokerType.equals(BrokerHolder.BrokerType.INTERNAL); - } - - protected boolean isBrokerStorePersistent() - { - return _brokerPersistent; - } - - public void restartBroker() throws Exception - { - restartBroker(0); - } - - public void restartBroker(int port) throws Exception - { - stopBroker(port); - startBroker(port); - } - - /** - * we assume that the environment is correctly set - * i.e. -Djava.naming.provider.url="..//example010.properties" - * - * @return an initial context - * - * @throws NamingException if there is an error getting the context - */ - public InitialContext getInitialContext() throws NamingException - { - if (_initialContext == null) - { - _initialContext = new InitialContext(); - } - return _initialContext; - } - - /** - * Get the default connection factory for the currently used broker - * Default factory is "local" - * - * @return A connection factory - * - * @throws Exception if there is an error getting the factory - */ - public AMQConnectionFactory getConnectionFactory() throws NamingException - { - if (_connectionFactory == null) - { - if (Boolean.getBoolean(PROFILE_USE_SSL)) - { - _connectionFactory = getConnectionFactory("default.ssl"); - } - else - { - _connectionFactory = getConnectionFactory("default"); - } - } - return _connectionFactory; - } - - /** - * Get a connection factory for the currently used broker - * - * @param factoryName The factory name - * - * @return A connection factory - * - * @throws Exception if there is an error getting the factory - */ - public AMQConnectionFactory getConnectionFactory(String factoryName) throws NamingException - { - return (AMQConnectionFactory) getInitialContext().lookup(factoryName); - } - - public Connection getConnection() throws JMSException, NamingException - { - return getConnection(GUEST_USERNAME, GUEST_PASSWORD); - } - - public Connection getConnectionWithOptions(Map<String, String> options) - throws URLSyntaxException, NamingException, JMSException - { - ConnectionURL curl = new AMQConnectionURL(getConnectionFactory().getConnectionURLString()); - for(Map.Entry<String,String> entry : options.entrySet()) - { - curl.setOption(entry.getKey(), entry.getValue()); - } - curl = new AMQConnectionURL(curl.toString()); - - curl.setUsername(GUEST_USERNAME); - curl.setPassword(GUEST_PASSWORD); - return getConnection(curl); - } - - - public Connection getConnection(ConnectionURL url) throws JMSException - { - _logger.debug("get connection for " + url.getURL()); - Connection connection = new AMQConnectionFactory(url).createConnection(url.getUsername(), url.getPassword()); - - _connections.add(connection); - - return connection; - } - - /** - * Get a connection (remote or in-VM) - * - * @param username The user name - * @param password The user password - * - * @return a newly created connection - * - * @throws Exception if there is an error getting the connection - */ - public Connection getConnection(String username, String password) throws JMSException, NamingException - { - _logger.debug("get connection for username " + username); - Connection con = getConnectionFactory().createConnection(username, password); - //add the connection in the list of connections - _connections.add(con); - return con; - } - - protected Connection getClientConnection(String username, String password, String id) throws JMSException, URLSyntaxException, AMQException, NamingException - { - _logger.debug("get connection for id " + id); - Connection con = getConnectionFactory().createConnection(username, password, id); - //add the connection in the list of connections - _connections.add(con); - return con; - } - - /** - * Useful, for example, to avoid the connection being automatically closed in {@link #tearDown()} - * if it has deliberately been put into an error state already. - */ - protected void forgetConnection(Connection connection) - { - _logger.debug("Forgetting about connection " + connection); - boolean removed = _connections.remove(connection); - assertTrue( - "The supplied connection " + connection + " should have been one that I already know about", - removed); - } - - /** - * Return a uniqueName for this test. - * In this case it returns a queue Named by the TestCase and TestName - * - * @return String name for a queue - */ - protected String getTestQueueName() - { - return getClass().getSimpleName() + "-" + getName(); - } - - /** - * Return a Queue specific for this test. - * Uses getTestQueueName() as the name of the queue - * @return - */ - public Queue getTestQueue() - { - return new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME, getTestQueueName()); - } - - /** - * Return a Topic specific for this test. - * Uses getTestQueueName() as the name of the topic - * @return - */ - public Topic getTestTopic() - { - return new AMQTopic(AMQShortString.valueOf(ExchangeDefaults.TOPIC_EXCHANGE_NAME), getTestQueueName()); - } - - @Override - protected void tearDown() throws java.lang.Exception - { - super.tearDown(); - - // close all the connections used by this test. - for (Connection c : _connections) - { - c.close(); - } - if(_taskExecutor != null) - { - _taskExecutor.stop(); - } - } - - /** - * Consume all the messages in the specified queue. Helper to ensure - * persistent tests don't leave data behind. - * - * @param queue the queue to purge - * - * @return the count of messages drained - * - * @throws Exception if a problem occurs - */ - protected int drainQueue(Queue queue) throws Exception - { - Connection connection = getConnection(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageConsumer consumer = session.createConsumer(queue); - - connection.start(); - - int count = 0; - while (consumer.receive(1000) != null) - { - count++; - } - - connection.close(); - - return count; - } - - /** - * Send messages to the given destination. - * - * If session is transacted then messages will be committed before returning - * - * @param session the session to use for sending - * @param destination where to send them to - * @param count no. of messages to send - * - * @return the sent messages - * - * @throws Exception - */ - public List<Message> sendMessage(Session session, Destination destination, - int count) throws Exception - { - return sendMessage(session, destination, count, 0, 0); - } - - /** - * Send messages to the given destination. - * - * If session is transacted then messages will be committed before returning - * - * @param session the session to use for sending - * @param destination where to send them to - * @param count no. of messages to send - * - * @param batchSize the batchSize in which to commit, 0 means no batching, - * but a single commit at the end - * @return the sent message - * - * @throws Exception - */ - public List<Message> sendMessage(Session session, Destination destination, - int count, int batchSize) throws Exception - { - return sendMessage(session, destination, count, 0, batchSize); - } - - /** - * Send messages to the given destination. - * - * If session is transacted then messages will be committed before returning - * - * @param session the session to use for sending - * @param destination where to send them to - * @param count no. of messages to send - * - * @param offset offset allows the INDEX value of the message to be adjusted. - * @param batchSize the batchSize in which to commit, 0 means no batching, - * but a single commit at the end - * @return the sent message - * - * @throws Exception - */ - public List<Message> sendMessage(Session session, Destination destination, - int count, int offset, int batchSize) throws Exception - { - List<Message> messages = new ArrayList<Message>(count); - - MessageProducer producer = session.createProducer(destination); - - int i = offset; - for (; i < (count + offset); i++) - { - Message next = createNextMessage(session, i); - - producer.send(next); - - if (session.getTransacted() && batchSize > 0) - { - if (i % batchSize == 0) - { - session.commit(); - } - - } - - messages.add(next); - } - - // Ensure we commit the last messages - // Commit the session if we are transacted and - // we have no batchSize or - // our count is not divible by batchSize. - if (session.getTransacted() && - ( batchSize == 0 || (i-1) % batchSize != 0)) - { - session.commit(); - } - - return messages; - } - - public Message createNextMessage(Session session, int msgCount) throws JMSException - { - Message message = createMessage(session, _messageSize); - message.setIntProperty(INDEX, msgCount); - - return message; - - } - - public Message createMessage(Session session, int messageSize) throws JMSException - { - String payload = new String(new byte[messageSize]); - - Message message; - - switch (_messageType) - { - case BYTES: - message = session.createBytesMessage(); - ((BytesMessage) message).writeUTF(payload); - break; - case MAP: - message = session.createMapMessage(); - ((MapMessage) message).setString(CONTENT, payload); - break; - default: // To keep the compiler happy - case TEXT: - message = session.createTextMessage(); - ((TextMessage) message).setText(payload); - break; - case OBJECT: - message = session.createObjectMessage(); - ((ObjectMessage) message).setObject(payload); - break; - case STREAM: - message = session.createStreamMessage(); - ((StreamMessage) message).writeString(payload); - break; - } - - return message; - } - - public BrokerDetails getBroker() - { - try - { - if (getConnectionFactory().getConnectionURL().getBrokerCount() > 0) - { - return getConnectionFactory().getConnectionURL().getBrokerDetails(0); - } - else - { - fail("No broker details are available."); - } - } - catch (NamingException e) - { - fail(e.getMessage()); - } - - //keep compiler happy - return null; - } - - protected int getFailingPort() - { - return FAILING_PORT; - } - - public int getHttpManagementPort(int mainPort) - { - return mainPort + (DEFAULT_HTTP_MANAGEMENT_PORT - DEFAULT_PORT); - } - - public void assertProducingConsuming(final Connection connection) throws Exception - { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Destination destination = session.createQueue(getTestQueueName()); - MessageConsumer consumer = session.createConsumer(destination); - sendMessage(session, destination, 1); - session.commit(); - connection.start(); - Message m1 = consumer.receive(RECEIVE_TIMEOUT); - assertNotNull("Message 1 is not received", m1); - assertEquals("Unexpected first message received", 0, m1.getIntProperty(INDEX)); - session.commit(); - session.close(); - } - - protected BrokerOptions getBrokerOptions( boolean managementMode, String testConfig, String log4jConfig, boolean skipLoggingConfiguration) - { - BrokerOptions options = new BrokerOptions(); - - options.setConfigurationStoreType(_brokerStoreType); - options.setConfigurationStoreLocation(testConfig); - options.setManagementMode(managementMode); - if (managementMode) - { - options.setManagementModePassword(MANAGEMENT_MODE_PASSWORD); - } - options.setSkipLoggingConfiguration(skipLoggingConfiguration); - options.setLogConfigFileLocation(log4jConfig); - options.setStartupLoggedToSystemOut(false); - return options; - } - - private Map<String, String> getJvmProperties() - { - Map<String,String> jvmOptions = new HashMap(); - synchronized (_propertiesSetForBroker) - { - jvmOptions.putAll(_propertiesSetForBroker); - - copySystemProperty("amqj.protocol.logging.level", jvmOptions); - copySystemProperty("root.logging.level", jvmOptions); - - copySystemProperty("test.port", jvmOptions); - copySystemProperty("test.mport", jvmOptions); - copySystemProperty("test.cport", jvmOptions); - copySystemProperty("test.hport", jvmOptions); - copySystemProperty("test.hsport", jvmOptions); - copySystemProperty("test.port.ssl", jvmOptions); - copySystemProperty("test.port.alt", jvmOptions); - copySystemProperty("test.port.alt.ssl", jvmOptions); - copySystemProperty("test.amqp_port_protocols", jvmOptions); - - copySystemProperty("virtualhostnode.type", jvmOptions); - copySystemProperty("virtualhostnode.context.blueprint", jvmOptions); - } - return jvmOptions; - } - - private void copySystemProperty(String name, Map<String, String> jvmOptions) - { - String value = System.getProperty(name); - if (value != null) - { - jvmOptions.put(name, value); - } - } - - private Map<String, String> getEnvironmentProperties() - { - return new HashMap<>(_env); - } - - private String getBrokerCommandTemplate() - { - return _brokerCommandTemplate; - } - - public static class BrokerHolderFactory - { - - public BrokerHolder create(BrokerHolder.BrokerType brokerType, int port, QpidBrokerTestCase testCase) - { - Set<Integer> portsUsedByBroker = testCase.guessAllPortsUsedByBroker(port); - BrokerHolder holder = null; - if (brokerType.equals(BrokerHolder.BrokerType.INTERNAL) && !testCase.existingInternalBroker()) - { - testCase.setSystemProperty(BrokerProperties.PROPERTY_USE_CUSTOM_RMI_SOCKET_FACTORY, "false"); - holder = new InternalBrokerHolder(portsUsedByBroker); - } - else if (!brokerType.equals(BrokerHolder.BrokerType.EXTERNAL)) - { - - Map<String,String> jvmOptions = testCase.getJvmProperties(); - Map<String,String> environmentProperties = testCase.getEnvironmentProperties(); - - holder = new SpawnedBrokerHolder(testCase.getBrokerCommandTemplate(), port, testCase.getTestName(), jvmOptions, environmentProperties, brokerType, portsUsedByBroker); - } - return holder; - } - } - -} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtils.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtils.java deleted file mode 100644 index 83294c13ad..0000000000 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtils.java +++ /dev/null @@ -1,259 +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.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * Provides helper methods for operating on classes and methods using reflection. Reflection methods tend to return - * a lot of checked exception so writing code to use them can be tedious and harder to read, especially when such errors - * are not expected to occur. This class always works with {@link ReflectionUtilsException}, which is a runtime exception, - * to wrap the checked exceptions raised by the standard Java reflection methods. Code using it does not normally - * expect these errors to occur, usually does not have a recovery mechanism for them when they do, but is cleaner, - * quicker to write and easier to read in the majority of cases. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Look up Classes by name. - * <tr><td> Instantiate Classes by no-arg constructor. - * </table> - */ -public class ReflectionUtils -{ - /** - * Gets the Class object for a named class. - * - * @param className The class to get the Class object for. - * - * @return The Class object for the named class. - */ - public static Class<?> forName(String className) - { - try - { - return Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new ReflectionUtilsException("ClassNotFoundException whilst finding class.", e); - } - } - - /** - * Creates an instance of a Class, instantiated through its no-args constructor. - * - * @param cls The Class to instantiate. - * @param <T> The Class type. - * - * @return An instance of the class. - */ - public static <T> T newInstance(Class<? extends T> cls) - { - try - { - return cls.newInstance(); - } - catch (InstantiationException e) - { - throw new ReflectionUtilsException("InstantiationException whilst instantiating class.", e); - } - catch (IllegalAccessException e) - { - throw new ReflectionUtilsException("IllegalAccessException whilst instantiating class.", e); - } - } - - /** - * Calls a named method on an object with a specified set of parameters, any Java access modifier are overridden. - * - * @param o The object to call. - * @param method The method name to call. - * @param params The parameters to pass. - * @param paramClasses The argument types. - * - * @return The return value from the method call. - */ - public static Object callMethodOverridingIllegalAccess(Object o, String method, Object[] params, Class[] paramClasses) - { - // Get the objects class. - Class cls = o.getClass(); - - // Get the classes of the parameters. - /*Class[] paramClasses = new Class[params.length]; - - for (int i = 0; i < params.length; i++) - { - paramClasses[i] = params[i].getClass(); - }*/ - - try - { - // Try to find the matching method on the class. - Method m = cls.getDeclaredMethod(method, paramClasses); - - // Make it accessible. - m.setAccessible(true); - - // Invoke it with the parameters. - return m.invoke(o, params); - } - catch (NoSuchMethodException e) - { - throw new ReflectionUtilsException("NoSuchMethodException.", e); - } - catch (IllegalAccessException e) - { - throw new ReflectionUtilsException("IllegalAccessException.", e); - } - catch (InvocationTargetException e) - { - throw new ReflectionUtilsException("InvocationTargetException", e); - } - } - - /** - * Calls a named method on an object with a specified set of parameters. - * - * @param o The object to call. - * @param method The method name to call. - * @param params The parameters to pass. - * - * @return The return value from the method call. - */ - public static Object callMethod(Object o, String method, Object[] params) - { - // Get the objects class. - Class cls = o.getClass(); - - // Get the classes of the parameters. - Class[] paramClasses = new Class[params.length]; - - for (int i = 0; i < params.length; i++) - { - paramClasses[i] = params[i].getClass(); - } - - try - { - // Try to find the matching method on the class. - Method m = cls.getMethod(method, paramClasses); - - // Invoke it with the parameters. - return m.invoke(o, params); - } - catch (NoSuchMethodException e) - { - throw new ReflectionUtilsException("NoSuchMethodException.", e); - } - catch (IllegalAccessException e) - { - throw new ReflectionUtilsException("IllegalAccessException", e); - } - catch (InvocationTargetException e) - { - throw new ReflectionUtilsException("InvocationTargetException", e); - } - } - - /** - * Calls a constuctor witht the specified arguments. - * - * @param constructor The constructor. - * @param args The arguments. - * @param <T> The Class type. - * - * @return An instance of the class that the constructor is for. - */ - public static <T> T newInstance(Constructor<T> constructor, Object[] args) - { - try - { - return constructor.newInstance(args); - } - catch (InstantiationException e) - { - throw new ReflectionUtilsException("InstantiationException", e); - } - catch (IllegalAccessException e) - { - throw new ReflectionUtilsException("IllegalAccessException", e); - } - catch (InvocationTargetException e) - { - throw new ReflectionUtilsException("InvocationTargetException", e); - } - } - - /** - * Gets the constructor of a class that takes the specified set of arguments if any matches. If no matching - * constructor is found then a runtime exception is raised. - * - * @param cls The class to get a constructor from. - * @param args The arguments to match. - * @param <T> The class type. - * - * @return The constructor. - */ - public static <T> Constructor<T> getConstructor(Class<T> cls, Class[] args) - { - try - { - return cls.getConstructor(args); - } - catch (NoSuchMethodException e) - { - throw new ReflectionUtilsException("NoSuchMethodException", e); - } - } - - @SuppressWarnings("unchecked") - public static <T> T getDeclaredField(final Object obj, final String fieldName) - { - try - { - final Field field = obj.getClass().getDeclaredField(fieldName); - if (!field.isAccessible()) - { - field.setAccessible(true); - } - return (T) field.get(obj); - } - catch (NoSuchFieldException e) - { - throw new ReflectionUtilsException("Unable to read field " + fieldName + "from object " + obj, e); - } - catch (SecurityException e) - { - throw new ReflectionUtilsException("Unable to read field " + fieldName + "from object " + obj, e); - } - catch (IllegalArgumentException e) - { - throw new ReflectionUtilsException("Unable to read field " + fieldName + "from object " + obj, e); - } - catch (IllegalAccessException e) - { - throw new ReflectionUtilsException("Unable to read field " + fieldName + "from object " + obj, e); - } - } -} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtilsException.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtilsException.java deleted file mode 100644 index 838828598b..0000000000 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtilsException.java +++ /dev/null @@ -1,44 +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; - -/** - * Wraps a checked exception that occurs when {@link ReflectionUtils} encounters checked exceptions using standard - * Java reflection methods. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Wrap a checked reflection exception. - * </table> - */ -public class ReflectionUtilsException extends RuntimeException -{ - /** - * Creates a runtime reflection exception, from a checked one. - * - * @param message The message. - * @param cause The causing exception. - */ - public ReflectionUtilsException(String message, Throwable cause) - { - super(message, cause); - } -} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/SpawnedBrokerHolder.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/SpawnedBrokerHolder.java deleted file mode 100644 index cd436b98cf..0000000000 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/SpawnedBrokerHolder.java +++ /dev/null @@ -1,469 +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.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.logging.messages.BrokerMessages; -import org.apache.qpid.util.FileUtils; -import org.apache.qpid.util.SystemUtils; - -public class SpawnedBrokerHolder implements BrokerHolder -{ - private static final Logger LOGGER = LoggerFactory.getLogger(SpawnedBrokerHolder.class); - protected static final String BROKER_READY = System.getProperty("broker.ready", BrokerMessages.READY().toString()); - private static final String BROKER_STOPPED = System.getProperty("broker.stopped", BrokerMessages.STOPPED().toString()); - - private final BrokerType _type; - private final int _port; - private final String _name; - private final Map<String, String> _jvmOptions; - private final Map<String, String> _environmentSettings; - protected BrokerCommandHelper _brokerCommandHelper; - - private Process _process; - private Integer _pid; - private Set<Integer> _portsUsedByBroker; - private String _brokerCommand; - - public SpawnedBrokerHolder(String brokerCommandTemplate, int port, String name, Map<String, String> jvmOptions, Map<String, String> environmentSettings, BrokerType type, Set<Integer> portsUsedByBroker) - { - _type = type; - _portsUsedByBroker = portsUsedByBroker; - _port = port; - _name = name; - _jvmOptions = jvmOptions; - _environmentSettings = environmentSettings; - _brokerCommandHelper = new BrokerCommandHelper(brokerCommandTemplate); - } - - - @Override - public void start(BrokerOptions brokerOptions) throws Exception - { - // Add the port to QPID_WORK to ensure unique working dirs for multi broker tests - final String qpidWork = getQpidWork(_type, _port); - - String[] cmd = _brokerCommandHelper.getBrokerCommand(_port, brokerOptions.getConfigurationStoreLocation(), brokerOptions.getConfigurationStoreType(), - new File(brokerOptions.getLogConfigFileLocation())); - if (brokerOptions.isManagementMode()) - { - String[] newCmd = new String[cmd.length + 3]; - System.arraycopy(cmd, 0, newCmd, 0, cmd.length); - newCmd[cmd.length] = "-mm"; - newCmd[cmd.length + 1] = "-mmpass"; - newCmd[cmd.length + 2] = brokerOptions.getManagementModePassword(); - cmd = newCmd; - } - ProcessBuilder pb = new ProcessBuilder(cmd); - pb.redirectErrorStream(true); - Map<String, String> processEnv = pb.environment(); - String qpidHome = System.getProperty(BrokerProperties.PROPERTY_QPID_HOME); - processEnv.put(BrokerProperties.PROPERTY_QPID_HOME, qpidHome); - - //Augment Path with bin directory in QPID_HOME. - boolean foundPath = false; - final String pathEntry = qpidHome + File.separator + "bin"; - for(Map.Entry<String,String> entry : processEnv.entrySet()) - { - if(entry.getKey().equalsIgnoreCase("path")) - { - entry.setValue(entry.getValue().concat(File.pathSeparator + pathEntry)); - foundPath = true; - } - } - if(!foundPath) - { - processEnv.put("PATH", pathEntry); - } - //Add the test name to the broker run. - // DON'T change PNAME, qpid.stop needs this value. - processEnv.put("QPID_PNAME", "-DPNAME=QPBRKR -DTNAME=\"" + _name + "\""); - processEnv.put("QPID_WORK", qpidWork); - - // Use the environment variable to set amqj.logging.level for the broker - // The value used is a 'server' value in the test configuration to - // allow a differentiation between the client and broker logging levels. - if (System.getProperty("amqj.server.logging.level") != null) - { - processEnv.put("AMQJ_LOGGING_LEVEL", System.getProperty("amqj.server.logging.level")); - } - - // Add all the environment settings the test requested - if (!_environmentSettings.isEmpty()) - { - for (Map.Entry<String, String> entry : _environmentSettings.entrySet()) - { - processEnv.put(entry.getKey(), entry.getValue()); - } - } - - String qpidOpts = ""; - - // Add all the specified system properties to QPID_OPTS - if (!_jvmOptions.isEmpty()) - { - for (String key : _jvmOptions.keySet()) - { - qpidOpts += " -D" + key + "=" + _jvmOptions.get(key); - } - } - - if (processEnv.containsKey("QPID_OPTS")) - { - qpidOpts = processEnv.get("QPID_OPTS") + qpidOpts; - } - processEnv.put("QPID_OPTS", qpidOpts); - - // cpp broker requires that the work directory is created - createBrokerWork(qpidWork); - - _process = pb.start(); - - Piper standardOutputPiper = new Piper(_process.getInputStream(), - BROKER_READY, - BROKER_STOPPED, - "STD", "BROKER-" + _port); - - standardOutputPiper.start(); - - new Piper(_process.getErrorStream(), null, null, "ERROR", "BROKER-" + _port).start(); - - StringBuilder cmdLine = new StringBuilder(cmd[0]); - for(int i = 1; i< cmd.length; i++) - { - cmdLine.append(' '); - cmdLine.append(cmd[i]); - } - - _brokerCommand = cmdLine.toString(); - _pid = retrieveUnixPidIfPossible(); - - if (!standardOutputPiper.await(30, TimeUnit.SECONDS)) - { - LOGGER.info("broker failed to become ready (" + standardOutputPiper.getReady() + "):" + standardOutputPiper.getStopLine()); - String threadDump = dumpThreads(); - if (!threadDump.isEmpty()) - { - LOGGER.info("the result of a try to capture thread dump:" + threadDump); - } - //Ensure broker has stopped - _process.destroy(); - cleanBrokerWork(qpidWork); - throw new RuntimeException("broker failed to become ready:" - + standardOutputPiper.getStopLine()); - } - - try - { - //test that the broker is still running and hasn't exited unexpectedly - int exit = _process.exitValue(); - LOGGER.info("broker aborted: " + exit); - cleanBrokerWork(qpidWork); - throw new RuntimeException("broker aborted: " + exit); - } - catch (IllegalThreadStateException e) - { - // this is expect if the broker started successfully - } - - } - - protected void createBrokerWork(final String qpidWork) - { - if (qpidWork != null) - { - final File dir = new File(qpidWork); - dir.mkdirs(); - if (!dir.isDirectory()) - { - throw new RuntimeException("Failed to created Qpid work directory : " + qpidWork); - } - } - } - - private String getQpidWork(BrokerType broker, int port) - { - if (!broker.equals(BrokerType.EXTERNAL)) - { - return System.getProperty(BrokerProperties.PROPERTY_QPID_WORK) + File.separator + port; - } - - return System.getProperty(BrokerProperties.PROPERTY_QPID_WORK); - } - - private void cleanBrokerWork(final String qpidWork) - { - if (qpidWork != null) - { - LOGGER.info("Cleaning broker work dir: " + qpidWork); - - File file = new File(qpidWork); - if (file.exists()) - { - final boolean success = FileUtils.delete(file, true); - if(!success) - { - throw new RuntimeException("Failed to recursively delete beneath : " + file); - } - } - } - } - - public void shutdown() - { - if(SystemUtils.isWindows()) - { - doWindowsKill(); - } - - LOGGER.info("Destroying broker process"); - _process.destroy(); - - reapChildProcess(); - - waitUntilPortsAreFree(); - } - - private void doWindowsKill() - { - try - { - Process p = Runtime.getRuntime().exec(new String[] {"wmic", "process", "list"}); - try(BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()))) - { - String line; - String headers = reader.readLine(); - int processIdOffset = headers.indexOf(" ProcessId") + 1; - int parentProcessIdOffset = headers.indexOf(" ParentProcessId") + 1; - String parentProcess = null; - Map<String, List<String>> parentProcessMap = new HashMap<String, List<String>>(); - - while ((line = reader.readLine()) != null) - { - if (line.length() > processIdOffset) - { - String processIdStr = line.substring(processIdOffset); - processIdStr = processIdStr.substring(0, processIdStr.indexOf(' ')); - processIdStr = processIdStr.trim(); - - String parentProcessIdStr = line.substring(parentProcessIdOffset); - parentProcessIdStr = parentProcessIdStr.substring(0, parentProcessIdStr.indexOf(' ')); - parentProcessIdStr = parentProcessIdStr.trim(); - if (parentProcessIdStr.length() > 0 && (parentProcess == null || parentProcess.equals( - parentProcessIdStr))) - { - List<String> children = parentProcessMap.get(parentProcessIdStr); - if (children == null) - { - children = new ArrayList<String>(); - parentProcessMap.put(parentProcessIdStr, children); - } - children.add(processIdStr); - } - if (line.substring(0, _brokerCommand.length() + 7) - .toLowerCase() - .contains(_brokerCommand.toLowerCase())) - { - parentProcess = processIdStr; - } - - } - if (parentProcess != null) - { - List<String> children = parentProcessMap.get(parentProcess); - if (children != null) - { - for (String child : children) - { - p = Runtime.getRuntime().exec(new String[]{"taskkill", "/PID", child, "/T", "/F"}); - consumeAllOutput(p); - } - } - p = Runtime.getRuntime().exec(new String[]{"taskkill", "/PID", parentProcess, "/T", "/F"}); - consumeAllOutput(p); - } - - } - } - } - catch (IOException e) - { - LOGGER.error("Error whilst killing process " + _brokerCommand, e); - } - } - - private static void consumeAllOutput(Process p) throws IOException - { - try(InputStreamReader inputStreamReader = new InputStreamReader(p.getInputStream())) - { - try (BufferedReader reader = new BufferedReader(inputStreamReader)) - { - while (reader.readLine() != null) - { - } - } - } - } - - @Override - public void kill() - { - if (_pid == null) - { - if(SystemUtils.isWindows()) - { - doWindowsKill(); - } - LOGGER.info("Destroying broker process (no PID)"); - _process.destroy(); - } - else - { - LOGGER.info("Killing broker process with PID " + _pid); - sendSigkillForImmediateShutdown(_pid); - } - - reapChildProcess(); - - waitUntilPortsAreFree(); - } - - private void sendSigkillForImmediateShutdown(Integer pid) - { - boolean killSuccessful = false; - try - { - final Process killProcess = Runtime.getRuntime().exec("kill -KILL " + pid); - killProcess.waitFor(); - killSuccessful = killProcess.exitValue() == 0; - } - catch (IOException e) - { - LOGGER.error("Error whilst killing process " + _pid, e); - } - catch (InterruptedException e) - { - Thread.currentThread().interrupt(); - } - finally - { - if (!killSuccessful) - { - _process.destroy(); - } - } - } - - private Integer retrieveUnixPidIfPossible() - { - if(!SystemUtils.isWindows()) - { - try - { - Integer pid = ReflectionUtils.getDeclaredField(_process, "pid"); - LOGGER.info("PID " + pid); - return pid; - } - catch (ReflectionUtilsException e) - { - LOGGER.warn("Could not get pid for process, Broker process shutdown will be graceful"); - } - } - return null; - } - - private void reapChildProcess() - { - try - { - _process.waitFor(); - LOGGER.info("broker exited: " + _process.exitValue()); - } - catch (InterruptedException e) - { - LOGGER.error("Interrupted whilst waiting for process shutdown"); - Thread.currentThread().interrupt(); - } - finally - { - try - { - _process.getInputStream().close(); - _process.getErrorStream().close(); - _process.getOutputStream().close(); - } - catch (IOException e) - { - } - } - } - - private void waitUntilPortsAreFree() - { - new PortHelper().waitUntilPortsAreFree(_portsUsedByBroker); - } - - @Override - public String dumpThreads() - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try - { - Process process = Runtime.getRuntime().exec("jstack " + _pid); - InputStream is = process.getInputStream(); - byte[] buffer = new byte[1024]; - int length = -1; - while ((length = is.read(buffer)) != -1) - { - baos.write(buffer, 0, length); - } - } - catch (Exception e) - { - LOGGER.error("Error whilst collecting thread dump for " + _pid, e); - } - return new String(baos.toByteArray()); - } - - @Override - public String toString() - { - return "SpawnedBrokerHolder [_pid=" + _pid + ", _portsUsedByBroker=" - + _portsUsedByBroker + "]"; - } -} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java deleted file mode 100644 index a091d01661..0000000000 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java +++ /dev/null @@ -1,443 +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 static org.mockito.Mockito.mock; - -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.LogRecorder; -import org.apache.qpid.server.model.*; -import org.apache.qpid.server.model.adapter.FileBasedGroupProvider; -import org.apache.qpid.server.model.adapter.FileBasedGroupProviderImpl; -import org.apache.qpid.server.plugin.PluggableFactoryLoader; -import org.apache.qpid.server.plugin.SystemConfigFactory; -import org.apache.qpid.server.security.access.FileAccessControlProviderConstants; -import org.apache.qpid.server.store.AbstractMemoryStore; -import org.apache.qpid.server.store.ConfiguredObjectRecord; -import org.apache.qpid.server.store.ConfiguredObjectRecordConverter; -import org.apache.qpid.server.store.ConfiguredObjectRecordImpl; -import org.apache.qpid.server.store.DurableConfigurationStore; -import org.apache.qpid.server.store.handler.ConfiguredObjectRecordHandler; -import org.apache.qpid.util.Strings; - -public class TestBrokerConfiguration -{ - - public static final String ENTRY_NAME_HTTP_PORT = "http"; - public static final String ENTRY_NAME_AMQP_PORT = "amqp"; - public static final String ENTRY_NAME_RMI_PORT = "rmi"; - public static final String ENTRY_NAME_JMX_PORT = "jmx"; - public static final String ENTRY_NAME_VIRTUAL_HOST = "test"; - public static final String ENTRY_NAME_AUTHENTICATION_PROVIDER = "plain"; - public static final String ENTRY_NAME_EXTERNAL_PROVIDER = "external"; - public static final String ENTRY_NAME_SSL_PORT = "sslPort"; - public static final String ENTRY_NAME_HTTP_MANAGEMENT = "MANAGEMENT-HTTP"; - public static final String MANAGEMENT_HTTP_PLUGIN_TYPE = "MANAGEMENT-HTTP"; - public static final String ENTRY_NAME_JMX_MANAGEMENT = "MANAGEMENT-JMX"; - public static final String MANAGEMENT_JMX_PLUGIN_TYPE = "MANAGEMENT-JMX"; - public static final String ENTRY_NAME_ANONYMOUS_PROVIDER = "anonymous"; - public static final String ENTRY_NAME_SSL_KEYSTORE = "systestsKeyStore"; - public static final String ENTRY_NAME_SSL_TRUSTSTORE = "systestsTrustStore"; - public static final String ENTRY_NAME_GROUP_FILE = "groupFile"; - public static final String ENTRY_NAME_ACL_FILE = "aclFile"; - private final TaskExecutor _taskExecutor; - private final String _storeType; - - private DurableConfigurationStore _store; - private boolean _saved; - - public TestBrokerConfiguration(String storeType, String initialStoreLocation, final TaskExecutor taskExecutor) - { - BrokerOptions brokerOptions = new BrokerOptions(); - _taskExecutor = taskExecutor; - _storeType = storeType; - brokerOptions.setInitialConfigurationLocation(initialStoreLocation); - final AbstractSystemConfig parentObject = new JsonSystemConfigImpl(taskExecutor, - mock(EventLogger.class), - mock(LogRecorder.class), - brokerOptions.convertToSystemConfigAttributes(), - mock(BrokerShutdownProvider.class)); - - ConfiguredObjectRecordConverter converter = new ConfiguredObjectRecordConverter(BrokerModel.getInstance()); - - Reader reader; - try - { - try - { - URL url = new URL(initialStoreLocation); - try(InputStream urlStream = url.openStream()) - { - reader = new InputStreamReader(urlStream); - } - } - catch (MalformedURLException e) - { - reader = new FileReader(initialStoreLocation); - } - - Collection<ConfiguredObjectRecord> records = converter.readFromJson(org.apache.qpid.server.model.Broker.class, parentObject, reader); - reader.close(); - - _store = new AbstractMemoryStore(Broker.class){}; - - ConfiguredObjectRecord[] initialRecords = records.toArray(new ConfiguredObjectRecord[records.size()]); - _store.openConfigurationStore(parentObject,false, initialRecords); - } - catch (IOException e) - { - throw new RuntimeException("Unable to load initial store", e); - } - - _store.visitConfiguredObjectRecords(new ConfiguredObjectRecordHandler() - { - @Override - public boolean handle(ConfiguredObjectRecord record) - { - Map<String, Object> attributes = record.getAttributes(); - String rawType = (String)attributes.get("type"); - if (rawType != null) - { - String interpolatedType = Strings.expand(rawType, false, Strings.ENV_VARS_RESOLVER, Strings.JAVA_SYS_PROPS_RESOLVER); - if (!interpolatedType.equals(rawType)) - { - setObjectAttribute(record, "type", interpolatedType); - } - } - return true; - } - - @Override - public void end() - { - } - - @Override - public void begin() - { - } - }); - } - - public boolean setBrokerAttribute(String name, Object value) - { - ConfiguredObjectRecord entry = findObject(Broker.class, null); - if (entry == null) - { - return false; - } - - return setObjectAttribute(entry, name, value); - } - - public boolean setObjectAttribute(final Class<? extends ConfiguredObject> category, - String objectName, - String attributeName, - Object value) - { - ConfiguredObjectRecord entry = findObject(category, objectName); - if (entry == null) - { - return false; - } - return setObjectAttribute(entry, attributeName, value); - } - - public boolean setObjectAttributes(final Class<? extends ConfiguredObject> category, - String objectName, - Map<String, Object> attributes) - { - ConfiguredObjectRecord entry = findObject(category, objectName); - if (entry == null) - { - return false; - } - return setObjectAttributes(entry, attributes); - } - - public boolean save(File configFile) - { - BrokerOptions brokerOptions = new BrokerOptions(); - brokerOptions.setConfigurationStoreLocation(configFile.getAbsolutePath()); - - SystemConfigFactory configFactory = - (new PluggableFactoryLoader<>(SystemConfigFactory.class)).get(_storeType); - - Map<String, Object> attributes = new HashMap<>(brokerOptions.convertToSystemConfigAttributes()); - attributes.put(SystemConfig.STARTUP_LOGGED_TO_SYSTEM_OUT, false); - attributes.put(ConfiguredObject.DESIRED_STATE, State.QUIESCED); - final SystemConfig parentObject = configFactory.newInstance(_taskExecutor, - mock(EventLogger.class), - mock(LogRecorder.class), - attributes, - mock(BrokerShutdownProvider.class)); - - parentObject.open(); - DurableConfigurationStore configurationStore = parentObject.getConfigurationStore(); - configurationStore.closeConfigurationStore(); - - final List<ConfiguredObjectRecord> initialRecords = new ArrayList<>(); - _store.visitConfiguredObjectRecords(new ConfiguredObjectRecordHandler() - { - @Override - public void begin() - { - - } - - @Override - public boolean handle(final ConfiguredObjectRecord record) - { - initialRecords.add(record); - return true; - } - - @Override - public void end() - { - - } - }); - - - configurationStore.openConfigurationStore(parentObject,true,initialRecords.toArray(new ConfiguredObjectRecord[initialRecords.size()])); - configurationStore.closeConfigurationStore(); - parentObject.close(); - return true; - } - - public UUID[] removeObjectConfiguration(final Class<? extends ConfiguredObject> category, - final String name) - { - final ConfiguredObjectRecord entry = findObject(category, name); - - if (entry != null) - { - - if(category == VirtualHostNode.class) - { - final List<ConfiguredObjectRecord> aliasRecords = new ArrayList<>(); - // remove vhost aliases associated with the vhost - final ConfiguredObjectRecordHandler visitor = new ConfiguredObjectRecordHandler() - { - @Override - public void begin() - { - - } - - @Override - public boolean handle(final ConfiguredObjectRecord record) - { - if (record.getType().equals(VirtualHostAlias.class.getSimpleName()) - && name.equals(record.getAttributes().get(ConfiguredObject.NAME))) - { - aliasRecords.add(record); - } - return true; - } - - @Override - public void end() - { - - } - }; - _store.visitConfiguredObjectRecords(visitor); - _store.remove(aliasRecords.toArray(new ConfiguredObjectRecord[aliasRecords.size()])); - } - return _store.remove(entry); - - } - return null; - } - - public UUID addObjectConfiguration(Class<? extends ConfiguredObject> type, Map<String, Object> attributes) - { - UUID id = UUIDGenerator.generateRandomUUID(); - addObjectConfiguration(id, type.getSimpleName(), attributes); - return id; - } - - public UUID addObjectConfiguration(final Class<? extends ConfiguredObject> parentCategory, final String parentName, - Class<? extends ConfiguredObject> type, Map<String, Object> attributes) - { - UUID id = UUIDGenerator.generateRandomUUID(); - ConfiguredObjectRecord entry = - new ConfiguredObjectRecordImpl(id, type.getSimpleName(), attributes, - Collections.singletonMap(parentCategory.getSimpleName(), findObject(parentCategory,parentName).getId())); - - _store.update(true, entry); - return id; - } - - public UUID addJmxManagementConfiguration() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Plugin.TYPE, MANAGEMENT_JMX_PLUGIN_TYPE); - attributes.put(Plugin.NAME, ENTRY_NAME_JMX_MANAGEMENT); - return addObjectConfiguration(Plugin.class, attributes); - } - - public UUID addHttpManagementConfiguration() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Plugin.TYPE, MANAGEMENT_HTTP_PLUGIN_TYPE); - attributes.put(Plugin.NAME, ENTRY_NAME_HTTP_MANAGEMENT); - return addObjectConfiguration(Plugin.class, attributes); - } - - public UUID addGroupFileConfiguration(String groupFilePath) - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(GroupProvider.NAME, ENTRY_NAME_GROUP_FILE); - attributes.put(GroupProvider.TYPE, FileBasedGroupProviderImpl.GROUP_FILE_PROVIDER_TYPE); - attributes.put(FileBasedGroupProvider.PATH, groupFilePath); - - return addObjectConfiguration(GroupProvider.class, attributes); - } - - public UUID addAclFileConfiguration(String aclFilePath) - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(AccessControlProvider.NAME, ENTRY_NAME_ACL_FILE); - attributes.put(AccessControlProvider.TYPE, FileAccessControlProviderConstants.ACL_FILE_PROVIDER_TYPE); - attributes.put(FileAccessControlProviderConstants.PATH, aclFilePath); - - return addObjectConfiguration(AccessControlProvider.class, attributes); - } - - private boolean setObjectAttributes(ConfiguredObjectRecord entry, Map<String, Object> attributes) - { - Map<String, Object> newAttributes = new HashMap<String, Object>(entry.getAttributes()); - newAttributes.putAll(attributes); - ConfiguredObjectRecord newEntry = new ConfiguredObjectRecordImpl(entry.getId(), entry.getType(), newAttributes, - entry.getParents()); - _store.update(false, newEntry); - return true; - } - - private ConfiguredObjectRecord findObject(final Class<? extends ConfiguredObject> category, final String objectName) - { - final RecordFindingVisitor visitor = new RecordFindingVisitor(category, objectName); - _store.visitConfiguredObjectRecords(visitor); - return visitor.getFoundRecord(); - } - - private void addObjectConfiguration(UUID id, String type, Map<String, Object> attributes) - { - ConfiguredObjectRecord entry = new ConfiguredObjectRecordImpl(id, type, attributes, Collections.singletonMap(Broker.class.getSimpleName(), findObject(Broker.class,null).getId())); - - _store.update(true, entry); - } - - private boolean setObjectAttribute(ConfiguredObjectRecord entry, String attributeName, Object value) - { - Map<String, Object> attributes = new HashMap<String, Object>(entry.getAttributes()); - attributes.put(attributeName, value); - ConfiguredObjectRecord newEntry = new ConfiguredObjectRecordImpl(entry.getId(), entry.getType(), attributes, entry.getParents()); - _store.update(false, newEntry); - return true; - } - - public boolean isSaved() - { - return _saved; - } - - public void setSaved(boolean saved) - { - _saved = saved; - } - - public void addPreferencesProviderConfiguration(String authenticationProvider, Map<String, Object> attributes) - { - ConfiguredObjectRecord authProviderRecord = findObject(AuthenticationProvider.class, authenticationProvider); - ConfiguredObjectRecord pp = new ConfiguredObjectRecordImpl(UUIDGenerator.generateRandomUUID(), - PreferencesProvider.class.getSimpleName(), attributes, Collections.singletonMap(AuthenticationProvider.class.getSimpleName(),authProviderRecord.getId())); - - _store.create(pp); - } - - public Map<String,Object> getObjectAttributes(final Class<? extends ConfiguredObject> category, final String name) - { - return findObject(category, name).getAttributes(); - } - - private static class RecordFindingVisitor implements ConfiguredObjectRecordHandler - { - private final Class<? extends ConfiguredObject> _category; - private final String _objectName; - public ConfiguredObjectRecord _foundRecord; - - public RecordFindingVisitor(final Class<? extends ConfiguredObject> category, final String objectName) - { - _category = category; - _objectName = objectName; - } - - @Override - public void begin() - { - } - - @Override - public boolean handle(final ConfiguredObjectRecord object) - { - if (object.getType().equals(_category.getSimpleName()) - && (_objectName == null - || _objectName.equals(object.getAttributes().get(ConfiguredObject.NAME)))) - { - _foundRecord = object; - return false; - } - return true; - } - - @Override - public void end() - { - } - - public ConfiguredObjectRecord getFoundRecord() - { - return _foundRecord; - } - } -} diff --git a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/TestUtils.java b/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/TestUtils.java deleted file mode 100644 index 5069e20335..0000000000 --- a/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/TestUtils.java +++ /dev/null @@ -1,55 +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.lang.management.ManagementFactory; -import java.lang.management.ThreadInfo; -import java.lang.management.ThreadMXBean; - -public class TestUtils -{ - public static String dumpThreads() - { - ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); - ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true); - StringBuilder dump = new StringBuilder(); - dump.append(String.format("%n")); - for (ThreadInfo threadInfo : threadInfos) - { - dump.append(threadInfo); - } - - long[] deadLocks = threadMXBean.findDeadlockedThreads(); - if (deadLocks != null && deadLocks.length > 0) - { - ThreadInfo[] deadlockedThreads = threadMXBean.getThreadInfo(deadLocks); - dump.append(String.format("%n")); - dump.append("Deadlock is detected!"); - dump.append(String.format("%n")); - for (ThreadInfo threadInfo : deadlockedThreads) - { - dump.append(threadInfo); - } - } - return dump.toString(); - } -} |
