http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java ---------------------------------------------------------------------- diff --git a/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java b/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java deleted file mode 100755 index 0725d69..0000000 --- a/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java +++ /dev/null @@ -1,974 +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.apache.qpid.systests.Utils.getAmqpManagementFacade; -import static org.apache.qpid.systests.Utils.getProtocol; - -import java.io.File; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import javax.jms.BytesMessage; -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -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.NamingException; - -import ch.qos.logback.classic.sift.SiftingAppender; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.Appender; -import ch.qos.logback.core.FileAppender; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.store.MemoryConfigurationStore; -import org.apache.qpid.systests.AmqpManagementFacade; -import org.apache.qpid.systests.ConnectionBuilder; -import org.apache.qpid.systests.JmsProvider; -import org.apache.qpid.systests.Utils; - -/** - * Qpid base class for system testing test cases. - */ -public class QpidBrokerTestCase extends QpidTestCase -{ - public static final int LOGBACK_REMOTE_PORT = LogbackSocketPortNumberDefiner.getLogbackSocketPortNumber(); - public static final String GUEST_USERNAME = "guest"; - public static final String GUEST_PASSWORD = "guest"; - public static final String PROFILE_USE_SSL = "profile.use_ssl"; - public static final String TEST_AMQP_PORT_PROTOCOLS_PROPERTY = "test.amqp_port_protocols"; - public static final int DEFAULT_PORT = Integer.getInteger("test.port", 0); - public static final int FAILING_PORT = Integer.getInteger("test.port.alt", 0); - public static final int DEFAULT_SSL_PORT = Integer.getInteger("test.port.ssl", 0); - public static final String QUEUE = "queue"; - public static final String TOPIC = "topic"; - public static final String MANAGEMENT_MODE_PASSWORD = "mm_password"; - private static final Logger LOGGER = LoggerFactory.getLogger(QpidBrokerTestCase.class); - protected static final long RECEIVE_TIMEOUT = Long.getLong("qpid.test_receive_timeout", 1000L); - protected static final String INDEX = "index"; - protected static final String CONTENT = "content"; - protected static final int DEFAULT_MESSAGE_SIZE = 1024; - private static final String JAVA = "java"; - private static final String BROKER_LANGUAGE = System.getProperty("broker.language", JAVA); - private static final BrokerHolder.BrokerType DEFAULT_BROKER_TYPE = BrokerHolder.BrokerType.valueOf( - System.getProperty("broker.type", BrokerHolder.BrokerType.INTERNAL.name()).toUpperCase()); - private static final Boolean BROKER_CLEAN_BETWEEN_TESTS = Boolean.getBoolean("broker.clean.between.tests"); - private static final Boolean BROKER_PERSISTENT = Boolean.getBoolean("broker.persistent"); - private static final Protocol BROKER_PROTOCOL = getProtocol(); - private static List<BrokerHolder> _brokerList = new ArrayList<>(); - - private final Map<String, String> _propertiesSetForBroker = new HashMap<>(); - private final List<Connection> _connections = new ArrayList<>(); - private AmqpManagementFacade _managementFacade; - private BrokerHolder _defaultBroker; - private MessageType _messageType = MessageType.TEXT; - - private JmsProvider _jmsProvider; - - @Override - public void runBare() throws Throwable - { - try - { - _managementFacade = getAmqpManagementFacade(); - _jmsProvider = Utils.getJmsProvider(); - - _defaultBroker = new BrokerHolderFactory().create(DEFAULT_BROKER_TYPE, DEFAULT_PORT, this); - super.runBare(); - } - catch (Exception e) - { - LOGGER.error("exception", e); - throw e; - } - finally - { - stopAllBrokers(); - - // reset properties used in the test - revertSystemProperties(); - - LOGGER.info("========== stop " + getTestName() + " =========="); - } - } - - public Logger getLogger() - { - return QpidBrokerTestCase.LOGGER; - } - - public File getOutputFile() - { - final ch.qos.logback.classic.Logger logger = - (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); - - return getFileFromSiftingAppender(logger); - } - - public BrokerHolder getDefaultBroker() - { - return _defaultBroker; - } - - public void startDefaultBroker() throws Exception - { - startDefaultBroker(false); - } - - public void startDefaultBroker(boolean managementMode) throws Exception - { - getDefaultBroker().start(managementMode); - setTestSystemProperty("test.port", getDefaultBroker().getAmqpPort() + ""); - } - - public void stopDefaultBroker() throws Exception - { - getDefaultBroker().shutdown(); - } - - public TestBrokerConfiguration getDefaultBrokerConfiguration() - { - return getDefaultBroker().getConfiguration(); - } - - public BrokerHolder createSpawnedBroker() throws Exception - { - return createSpawnedBroker(0); - } - - public BrokerHolder createSpawnedBroker(int amqpPort) throws Exception - { - return new BrokerHolderFactory().create(BrokerHolder.BrokerType.SPAWNED, amqpPort, this); - } - - public void killDefaultBroker() - { - getDefaultBroker().kill(); - } - - /** - * Check whether the broker is an 0.8 - * - * @return true if the broker is an 0_8 version, false otherwise. - */ - public boolean isBroker08() - { - return BROKER_PROTOCOL.equals(Protocol.AMQP_0_8); - } - - public boolean isBrokerPre010() - { - return EnumSet.of(Protocol.AMQP_0_8, Protocol.AMQP_0_9, Protocol.AMQP_0_9_1).contains(BROKER_PROTOCOL); - } - - public boolean isBroker010() - { - return BROKER_PROTOCOL.equals(Protocol.AMQP_0_10); - } - - public boolean isBroker10() - { - return BROKER_PROTOCOL.equals(Protocol.AMQP_1_0); - } - - public Protocol getBrokerProtocol() - { - return BROKER_PROTOCOL; - } - - public void restartDefaultBroker() throws Exception - { - getDefaultBroker().restart(); - } - - public JmsProvider getJmsProvider() - { - return _jmsProvider; - } - - public ConnectionBuilder getConnectionBuilder() - { - final ConnectionBuilder connectionBuilder = _jmsProvider.getConnectionBuilder() - .setPort(Integer.getInteger("test.port")) - .setSslPort(Integer.getInteger("test.port.ssl")) - .setVirtualHost("test") - .setTls(Boolean.getBoolean(PROFILE_USE_SSL)) - .setPopulateJMSXUserID(true) - .setUsername(GUEST_USERNAME) - .setPassword(GUEST_PASSWORD); - - return (ConnectionBuilder) Proxy.newProxyInstance(getClass().getClassLoader(), - new Class<?>[]{ConnectionBuilder.class}, - new ConectionBuilderHandler(connectionBuilder, _connections)); - } - - /** - * Get the default connection factory for the currently used broker - * Default factory is "local" - * - * @return A connection factory - * @throws NamingException if there is an error getting the factory - */ - public ConnectionFactory getConnectionFactory() throws NamingException - { - return getConnectionFactory(Collections.emptyMap()); - } - - public ConnectionFactory getConnectionFactory(final Map<String, String> options) throws NamingException - { - return getConnectionBuilder().setOptions(options).buildConnectionFactory(); - } - - public Connection getConnection() throws JMSException, NamingException - { - return getConnection(GUEST_USERNAME, GUEST_PASSWORD); - } - - public Connection getConnection(String username, String password) throws JMSException, NamingException - { - return getConnectionBuilder().setUsername(username).setPassword(password).build(); - } - - public Connection getConnectionWithPrefetch(int prefetch) throws Exception - { - return getConnectionBuilder().setPrefetch(prefetch).build(); - } - - public Connection getConnectionWithOptions(Map<String, String> options) throws Exception - { - return getConnectionBuilder().setOptions(options).build(); - } - - public Connection getConnectionWithOptions(String vhost, Map<String, String> options) throws Exception - { - return getConnectionBuilder().setOptions(options) - .setVirtualHost(vhost) - .build(); - } - - public Connection getConnectionForVHost(String vhost) throws Exception - { - return getConnectionBuilder().setVirtualHost(vhost).build(); - } - - public Connection getConnection(String urlString) throws Exception - { - Connection connection = _jmsProvider.getConnection(urlString); - _connections.add(connection); - return connection; - } - - public Queue getTestQueue() throws NamingException - { - return _jmsProvider.getTestQueue(getTestQueueName()); - } - - public Queue getQueueFromName(Session session, String name) throws JMSException - { - return _jmsProvider.getQueueFromName(session, name); - } - - public Queue createTestQueue(Session session) throws JMSException - { - return _jmsProvider.createQueue(session, getTestQueueName()); - } - - public Queue createTestQueue(Session session, String queueName) throws JMSException - { - return _jmsProvider.createQueue(session, queueName); - } - - /** - * Return a Topic specific for this test. - * Uses getTestQueueName() as the name of the topic - */ - public Topic getTestTopic() throws NamingException - { - return _jmsProvider.getTestTopic(getTestQueueName()); - } - - protected Topic createTopic(final Connection con, final String topicName) throws JMSException - { - return _jmsProvider.createTopic(con, topicName); - } - - protected Topic createTopicOnDirect(final Connection con, String topicName) throws JMSException, URISyntaxException - { - return _jmsProvider.createTopicOnDirect(con, topicName); - } - - protected Topic createTopicOnFanout(final Connection con, String topicName) throws JMSException, URISyntaxException - { - return _jmsProvider.createTopicOnFanout(con, topicName); - } - - protected void createEntityUsingAmqpManagement(final String name, final Session session, final String type) - throws JMSException - { - _managementFacade.createEntityUsingAmqpManagement(name, session, type); - } - - protected void createEntityUsingAmqpManagement(final String name, final Session session, final String type, Map<String, Object> attributes) - throws JMSException - { - - _managementFacade.createEntityUsingAmqpManagement(name, session, type, attributes); - } - - protected void updatenEntityUsingAmqpManagement(final String name, final Session session, final String type, Map<String, Object> attributes) - throws JMSException - { - _managementFacade.updateEntityUsingAmqpManagement(name, session, type, attributes); - } - - protected void deleteEntityUsingAmqpManagement(final String name, final Session session, final String type) - throws JMSException - { - - _managementFacade.deleteEntityUsingAmqpManagement(name, session, type); - } - - protected Object performOperationUsingAmqpManagement(final String name, final String operation, final Session session, final String type, Map<String,Object> arguments) - throws JMSException - { - return _managementFacade.performOperationUsingAmqpManagement(name, operation, session, type, arguments); - } - - protected List<Map<String, Object>> managementQueryObjects(final Session session, final String type) throws JMSException - { - - return _managementFacade.managementQueryObjects(session, type); - } - - protected Map<String, Object> managementReadObject(Session session, String type, String name, boolean actuals) throws JMSException - { - return _managementFacade.readEntityUsingAmqpManagement(session, type, name, actuals); - } - - public long getQueueDepth(final Connection con, final Queue destination) throws Exception - { - Connection connection = getConnection(); - try - { - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { - return _managementFacade.getQueueDepth(destination, session); - } - - finally - { - session.close(); - } - } - finally - { - connection.close(); - } - } - - public boolean isQueueExist(final Connection con, final Queue destination) throws Exception - { - Connection connection = getConnection(); - try - { - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - try - { - return _managementFacade.isQueueExist(destination, session); - } - - finally - { - session.close(); - } - } - finally - { - connection.close(); - } - } - - /** - * Send messages to the given destination. - * <p/> - * 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. - * <p/> - * 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. - * <p/> - * 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<>(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, DEFAULT_MESSAGE_SIZE); - 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 String getBrokerDetailsFromDefaultConnectionUrl() - { - return "tcp://localhost:" + (getDefaultBroker().getAmqpTlsPort() > 0 - ? getDefaultBroker().getAmqpTlsPort() - : getDefaultBroker().getAmqpPort()); - } - - /** - * Tests that a connection is functional by producing and consuming a single message. - * Will fail if failover interrupts either transaction. - */ - 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(getReceiveTimeout()); - assertNotNull("Message 1 is not received", m1); - assertEquals("Unexpected first message received", 0, m1.getIntProperty(INDEX)); - session.commit(); - session.close(); - } - - @Override - protected void setUp() throws Exception - { - super.setUp(); - startDefaultBroker(); - } - - @Override - protected void tearDown() throws java.lang.Exception - { - LOGGER.debug("tearDown started"); - try - { - for (Connection c : _connections) - { - c.close(); - } - } - finally - { - try - { - _defaultBroker.shutdown(); - } - finally - { - super.tearDown(); - } - } - } - - protected int getDefaultAmqpPort() - { - return getDefaultBroker().getAmqpPort(); - } - - protected boolean stopBrokerSafely(BrokerHolder broker) - { - boolean success = true; - try - { - broker.shutdown(); - - if (BROKER_CLEAN_BETWEEN_TESTS) - { - broker.cleanUp(); - } - } - catch (Exception e) - { - success = false; - LOGGER.error("Failed to stop broker " + broker, e); - if (broker != null) - { - // save the thread dump in case of dead locks - try - { - LOGGER.error("Broker " + broker + " thread dump:" + broker.dumpThreads()); - } - finally - { - try - { - broker.kill(); - } - catch (Exception killException) - { - // ignore - } - } - } - } - return success; - } - - protected void createTestVirtualHostNode(String virtualHostNodeName) - { - createTestVirtualHostNode(getDefaultBroker(), virtualHostNodeName, true); - } - - protected void createTestVirtualHostNode(BrokerHolder broker, 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_dir}" + File.separator + virtualHostNodeName; - } - - String blueprint = null; - if (withBlueprint) - { - blueprint = getTestProfileVirtualHostNodeBlueprint(); - } - - broker.createVirtualHostNode(virtualHostNodeName, storeType, storeDir, blueprint); - } - - /** - * Set a System property for the duration of this test. - * <p/> - * When the test run is complete the value will be reverted. - * <p/> - * The values set using this method will also be propagated to the external - * Apache Qpid Broker-J via a -D value defined in QPID_OPTS. - * <p/> - * 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(); - } - - protected boolean isJavaBroker() - { - return BROKER_LANGUAGE.equals("java"); - } - - protected boolean isCppBroker() - { - return BROKER_LANGUAGE.equals("cpp"); - } - - protected boolean isExternalBroker() - { - return !isInternalBroker(); - } - - protected boolean isInternalBroker() - { - return DEFAULT_BROKER_TYPE.equals(BrokerHolder.BrokerType.INTERNAL); - } - - protected boolean isBrokerStorePersistent() - { - return BROKER_PERSISTENT; - } - - protected Connection getConnectionWithSyncPublishing() throws Exception - { - return getConnectionBuilder().setSyncPublish(true).build(); - } - - protected Connection getClientConnection(String username, String password, String id) - throws Exception - { - return getConnectionBuilder().setClientId(id).setUsername(username).setPassword(password).build(); - } - - /** - * 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(); - } - - protected int getFailingPort() - { - return FAILING_PORT; - } - - @Override - protected void setTestOverriddenProperties(Properties properties) - { - for (String propertyName : properties.stringPropertyNames()) - { - setSystemProperty(propertyName, properties.getProperty(propertyName)); - } - } - - protected long getReceiveTimeout() - { - return Long.getLong("qpid.test_receive_timeout", 1000L); - } - - protected long getLongReceiveTimeout() - { - return Long.getLong("qpid.test_receive_long_timeout", 5000L); - } - - protected long getShortReceiveTimeout() - { - return Long.getLong("qpid.test_receive_short_timeout", 500L); - } - - private File getFileFromSiftingAppender(final ch.qos.logback.classic.Logger logger) - { - String key = logger.getLoggerContext().getProperty(LogbackPropertyValueDiscriminator.CLASS_QUALIFIED_TEST_NAME); - - for (Iterator<Appender<ILoggingEvent>> index = logger.iteratorForAppenders(); index.hasNext(); /* do nothing */) - { - Appender<ILoggingEvent> appender = index.next(); - if (appender instanceof SiftingAppender) - { - SiftingAppender siftingAppender = (SiftingAppender) appender; - Appender subAppender = siftingAppender.getAppenderTracker().find(key); - if (subAppender instanceof FileAppender) - { - return new File(((FileAppender) subAppender).getFile()); - } - } - } - return null; - } - - private boolean existingInternalBroker() - { - for (BrokerHolder holder : _brokerList) - { - if (holder instanceof InternalBrokerHolder) - { - return true; - } - } - - return false; - } - - private void stopAllBrokers() - { - boolean exceptionOccurred = false; - for (BrokerHolder brokerHolder : _brokerList) - { - if (!stopBrokerSafely(brokerHolder)) - { - exceptionOccurred = true; - } - } - _brokerList.clear(); - if (exceptionOccurred) - { - throw new RuntimeException("Exception occurred on stopping of test broker. Please, examine logs for details"); - } - } - - private Map<String, String> getJvmProperties() - { - Map<String, String> jvmOptions = new HashMap<>(); - synchronized (_propertiesSetForBroker) - { - jvmOptions.putAll(_propertiesSetForBroker); - - copySystemProperty("test.port", jvmOptions); - copySystemProperty("test.hport", jvmOptions); - copySystemProperty("test.port.ssl", jvmOptions); - copySystemProperty("test.port.alt", jvmOptions); - copySystemProperty("test.port.alt.ssl", jvmOptions); - copySystemProperty("test.amqp_port_protocols", jvmOptions); - - copySystemProperty("qpid.globalAddressDomains", 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); - } - } - - /** - * Type of message - */ - protected enum MessageType - { - BYTES, - MAP, - OBJECT, - STREAM, - TEXT - } - - public static class BrokerHolderFactory - { - public BrokerHolder create(BrokerHolder.BrokerType brokerType, int port, QpidBrokerTestCase testCase) - { - // This will force the creation of the file appender - LOGGER.debug("Creating BrokerHolder"); - - final File logFile = testCase.getOutputFile(); - final String classQualifiedTestName = testCase.getClassQualifiedTestName(); - BrokerHolder holder = null; - if (brokerType.equals(BrokerHolder.BrokerType.INTERNAL) && !testCase.existingInternalBroker()) - { - holder = new InternalBrokerHolder(port, classQualifiedTestName, logFile); - } - else if (!brokerType.equals(BrokerHolder.BrokerType.EXTERNAL)) - { - Map<String, String> jvmOptions = testCase.getJvmProperties(); - Map<String, String> environmentProperties = new HashMap<>(testCase._propertiesSetForBroker); - - holder = new SpawnedBrokerHolder(port, classQualifiedTestName, logFile, - jvmOptions, environmentProperties); - } - _brokerList.add(holder); - return holder; - } - } - - private static class ConectionBuilderHandler implements InvocationHandler - { - private final ConnectionBuilder _connectionBuilder; - private final List<Connection> _connections; - - public ConectionBuilderHandler(final ConnectionBuilder connectionBuilder, - final List<Connection> connections) - { - _connectionBuilder = connectionBuilder; - _connections = connections; - } - - @Override - public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable - { - if (method.getName().equals("build")) - { - Connection connection = _connectionBuilder.build(); - _connections.add(connection); - return connection; - } - else if (method.getName().equals("buildConnectionFactory")) - { - return _connectionBuilder.buildConnectionFactory(); - } - else - { - method.invoke(_connectionBuilder, args); - return proxy; - } - } - } -}
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtils.java ---------------------------------------------------------------------- diff --git a/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtils.java b/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtils.java deleted file mode 100644 index 83294c1..0000000 --- a/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); - } - } -} http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtilsException.java ---------------------------------------------------------------------- diff --git a/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtilsException.java b/systests/src/main/java/org/apache/qpid/test/utils/ReflectionUtilsException.java deleted file mode 100644 index 8388285..0000000 --- a/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); - } -} http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/SpawnedBrokerHolder.java ---------------------------------------------------------------------- diff --git a/systests/src/main/java/org/apache/qpid/test/utils/SpawnedBrokerHolder.java b/systests/src/main/java/org/apache/qpid/test/utils/SpawnedBrokerHolder.java deleted file mode 100644 index 6156f36..0000000 --- a/systests/src/main/java/org/apache/qpid/test/utils/SpawnedBrokerHolder.java +++ /dev/null @@ -1,530 +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.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.Main; -import org.apache.qpid.server.logging.logback.BrokerLogbackSocketLogger; -import org.apache.qpid.server.logging.logback.BrokerNameAndLevelLogInclusionRule; -import org.apache.qpid.server.logging.messages.BrokerMessages; -import org.apache.qpid.server.model.BrokerLogInclusionRule; -import org.apache.qpid.server.model.BrokerLogger; -import org.apache.qpid.server.util.SystemUtils; - -public class SpawnedBrokerHolder extends AbstractBrokerHolder -{ - 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 static final String BROKER_COMMAND_PLATFORM = "broker.command." + SystemUtils.getOSConfigSuffix(); - private static final String BROKER_COMMAND_TEMPLATE = System.getProperty(BROKER_COMMAND_PLATFORM, System.getProperty("broker.command")); - private static final int BROKER_STARTUP_TIME = Integer.parseInt(System.getProperty("SpawnedBrokerHolder.brokerStartupTime", "30000")); - - private final Map<String, String> _jvmOptions; - private final Map<String, String> _environmentSettings; - protected BrokerCommandHelper _brokerCommandHelper; - - private Process _process; - private Integer _pid; - private List<String> _windowsPids; - private String _brokerCommand; - private String _pseudoThreadName; - - public SpawnedBrokerHolder(final int port, - final String classQualifiedTestName, - final File logFile, - Map<String, String> jvmOptions, - Map<String, String> environmentSettings) - { - super(port, classQualifiedTestName, logFile); - _jvmOptions = jvmOptions; - _environmentSettings = environmentSettings; - _brokerCommandHelper = new BrokerCommandHelper(BROKER_COMMAND_TEMPLATE); - _pseudoThreadName = "BROKER-" + getBrokerIndex(); - } - - @Override - public void start(final boolean managementMode, final int amqpPort) throws Exception - { - LOGGER.debug("Spawning broker with jvmOptions: {} environmentSettings: {} permitted start-up time: {}", - _jvmOptions, _environmentSettings, BROKER_STARTUP_TIME); - - String[] cmd = _brokerCommandHelper.getBrokerCommand(amqpPort, - getWorkDir().toString(), - getConfigurationPath(), - getBrokerStoreType()); - if (managementMode) - { - String[] newCmd = new String[cmd.length + 3]; - System.arraycopy(cmd, 0, newCmd, 0, cmd.length); - newCmd[cmd.length] = "-mm"; - newCmd[cmd.length + 1] = "-mmpass"; - newCmd[cmd.length + 2] = QpidBrokerTestCase.MANAGEMENT_MODE_PASSWORD; - cmd = newCmd; - } - - // bat files will treat = as an argument separator, so if an argument contains = it needs to be quoted - if(cmd[0].endsWith(".bat")) - { - for(int i = 1 ; i < cmd.length; i++) - { - String orig = cmd[i]; - if(orig.contains("=") && !orig.contains("\"")) - { - cmd[i] = "\"" + orig + "\""; - } - } - } - - ProcessBuilder pb = new ProcessBuilder(cmd); - pb.redirectErrorStream(true); - Map<String, String> processEnv = pb.environment(); - String qpidHome = System.getProperty(Main.PROPERTY_QPID_HOME); - processEnv.put(Main.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=\"" + getClassQualifiedTestName() + "\""); - - // 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()) - { - boolean isWindows = SystemUtils.isWindows(); - for (String key : _jvmOptions.keySet()) - { - qpidOpts += " -D" + key + "=" +(isWindows ? doWindowsCommandEscaping(_jvmOptions.get(key)) : _jvmOptions.get(key)); - } - } - - if (processEnv.containsKey("QPID_OPTS")) - { - qpidOpts = processEnv.get("QPID_OPTS") + qpidOpts; - } - processEnv.put("QPID_OPTS", qpidOpts); - - _process = pb.start(); - - Piper standardOutputPiper = new Piper(_process.getInputStream(), - BROKER_READY, - BROKER_STOPPED, - _pseudoThreadName, getClass().getName()); - - standardOutputPiper.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(BROKER_STARTUP_TIME, TimeUnit.MILLISECONDS)) - { - LOGGER.info("Spawned broker failed to become ready within {} ms." - + " Ready line '{}'", - BROKER_STARTUP_TIME, standardOutputPiper.getReady()); - String threadDump = dumpThreads(); - if (!threadDump.isEmpty()) - { - LOGGER.info("the result of a try to capture thread dump:" + threadDump); - } - //Ensure broker has stopped - _process.destroy(); - throw new RuntimeException(String.format("Broker failed to become ready within %d ms. Stop line : %s", - BROKER_STARTUP_TIME, - standardOutputPiper.getStopLine())); - } - - _windowsPids = retrieveWindowsPidsIfPossible(); - - try - { - //test that the broker is still running and hasn't exited unexpectedly - int exit = _process.exitValue(); - LOGGER.info("broker aborted: {}", exit); - throw new RuntimeException("broker aborted: " + exit); - } - catch (IllegalThreadStateException e) - { - // this is expect if the broker started successfully - } - - } - - private String doWindowsCommandEscaping(String value) - { - if(value.contains("\"") && !value.startsWith("\"")) - { - return "\"" + value.replaceAll("\"", "\"\"") + "\""; - - } - else - { - return value; - } - } - - @Override - public void shutdown() - { - if(SystemUtils.isWindows()) - { - doWindowsKill(); - } - - if (_process != null) - { - LOGGER.info("Destroying broker process"); - _process.destroy(); - - reapChildProcess(); - waitUntilPortsAreFreeIfRequired(); - } - } - - @Override - protected String getLogPrefix() - { - return _pseudoThreadName; - } - - private List<String> retrieveWindowsPidsIfPossible() - { - if(SystemUtils.isWindows()) - { - 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.toLowerCase() - .contains(_brokerCommand.toLowerCase())) - { - parentProcess = processIdStr; - } - - } - - } - LOGGER.debug("Parent process: " + parentProcess); - if (parentProcess != null) - { - List<String> returnVal = new ArrayList<>(); - returnVal.add(parentProcess); - List<String> children = parentProcessMap.get(parentProcess); - if (children != null) - { - for (String child : children) - { - returnVal.add(child); - } - } - return returnVal; - } - - - } - } - catch (IOException e) - { - LOGGER.error("Error whilst killing process " + _brokerCommand, e); - } - } - return null; - } - - private void doWindowsKill() - { - if(_windowsPids != null && !_windowsPids.isEmpty()) - { - String parentProcess = _windowsPids.remove(0); - try - { - - Process p; - for (String child : _windowsPids) - { - 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(); - - waitUntilPortsAreFreeIfRequired(); - } - - 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) - { - } - } - } - - @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 + ", _amqpPort=" - + getAmqpPort() + "]"; - } - - @Override - protected TestBrokerConfiguration createBrokerConfiguration() - { - TestBrokerConfiguration configuration = super.createBrokerConfiguration(); - - String remotelogback = "remotelogback"; - - Map<String, String> mdc = new HashMap<>(); - mdc.put("origin", getLogPrefix()); - - Map<String, String> contextProperties = new HashMap<>(); - contextProperties.put(LogbackPropertyValueDiscriminator.CLASS_QUALIFIED_TEST_NAME, getClassQualifiedTestName()); - - Map<String, Object> loggerAttrs = new HashMap<>(); - loggerAttrs.put(BrokerLogger.TYPE, BrokerLogbackSocketLogger.TYPE); - loggerAttrs.put(BrokerLogbackSocketLogger.NAME, remotelogback); - loggerAttrs.put(BrokerLogbackSocketLogger.PORT, QpidBrokerTestCase.LOGBACK_REMOTE_PORT); - loggerAttrs.put(BrokerLogbackSocketLogger.MAPPED_DIAGNOSTIC_CONTEXT, mdc); - loggerAttrs.put(BrokerLogbackSocketLogger.CONTEXT_PROPERTIES, contextProperties); - - configuration.addObjectConfiguration(BrokerLogger.class, loggerAttrs); - - Map<String, Object> qpidRuleAttrs = new HashMap<>(); - qpidRuleAttrs.put(BrokerLogInclusionRule.NAME, "Qpid"); - qpidRuleAttrs.put(BrokerLogInclusionRule.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); - qpidRuleAttrs.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "DEBUG"); - qpidRuleAttrs.put(BrokerNameAndLevelLogInclusionRule.LOGGER_NAME, "org.apache.qpid.*"); - - configuration.addObjectConfiguration(BrokerLogger.class, remotelogback, - BrokerLogInclusionRule.class, qpidRuleAttrs); - - Map<String, Object> operationalLoggingRuleAttrs = new HashMap<>(); - operationalLoggingRuleAttrs.put(BrokerLogInclusionRule.NAME, "Operational"); - operationalLoggingRuleAttrs.put(BrokerLogInclusionRule.TYPE, BrokerNameAndLevelLogInclusionRule.TYPE); - operationalLoggingRuleAttrs.put(BrokerNameAndLevelLogInclusionRule.LEVEL, "INFO"); - operationalLoggingRuleAttrs.put(BrokerNameAndLevelLogInclusionRule.LOGGER_NAME, "qpid.message.*"); - - configuration.addObjectConfiguration(BrokerLogger.class, remotelogback, - BrokerLogInclusionRule.class, operationalLoggingRuleAttrs); - - return configuration; - } - -} http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java ---------------------------------------------------------------------- diff --git a/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java b/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java deleted file mode 100644 index 526efaa..0000000 --- a/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java +++ /dev/null @@ -1,493 +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.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -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.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.management.plugin.HttpManagement; -import org.apache.qpid.server.model.AbstractSystemConfig; -import org.apache.qpid.server.model.AccessControlProvider; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerModel; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.GroupProvider; -import org.apache.qpid.server.model.JsonSystemConfigImpl; -import org.apache.qpid.server.model.Plugin; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.SystemConfig; -import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.model.VirtualHostAlias; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.model.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.plugins.AclFileAccessControlProvider; -import org.apache.qpid.server.security.access.plugins.AclRule; -import org.apache.qpid.server.security.access.plugins.RuleBasedAccessControlProvider; -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.server.virtualhostnode.JsonVirtualHostNode; -import org.apache.qpid.server.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_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_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"; - public static final String ENTRY_NAME_ACL_RULES = "aclRules"; - private final TaskExecutor _taskExecutor; - private final String _storeType; - - private AbstractMemoryStore _store; - private boolean _saved; - private File _passwdFile; - - private static final Logger LOGGER = LoggerFactory.getLogger(TestBrokerConfiguration.class); - - public TestBrokerConfiguration(String storeType, String initialStoreLocation) - { - _taskExecutor = new CurrentThreadTaskExecutor(); - _taskExecutor.start(); - _storeType = storeType; - Map<String,Object> config = new HashMap<>(); - config.put("storePath", initialStoreLocation); - final AbstractSystemConfig parentObject = new JsonSystemConfigImpl(_taskExecutor, - mock(EventLogger.class), - null, - config) - { - - { - updateModel(BrokerModel.getInstance()); - } - }; - - 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.init(parentObject); - - _store.openConfigurationStore(new ConfiguredObjectRecordHandler() - { - @Override - public void 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); - } - } - } - - }, initialRecords); - } - catch (IOException e) - { - throw new RuntimeException("Unable to load initial store", e); - } - - - } - - 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) - { - - Map<String, Object> attributes = new HashMap<>(); - attributes.put("storePath", configFile.getAbsolutePath()); - - SystemConfigFactory configFactory = - (new PluggableFactoryLoader<>(SystemConfigFactory.class)).get(_storeType); - - 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), - null, attributes); - - parentObject.open(); - DurableConfigurationStore configurationStore = parentObject.getConfigurationStore(); - configurationStore.closeConfigurationStore(); - - final List<ConfiguredObjectRecord> records = getConfiguredObjectRecords(); - - - configurationStore.init(parentObject); - - clearStore(configurationStore); - - configurationStore.update(true, records.toArray(new ConfiguredObjectRecord[records.size()])); - - - configurationStore.closeConfigurationStore(); - parentObject.close(); - return true; - } - - public void clearStore(final DurableConfigurationStore configurationStore) - { - final List<ConfiguredObjectRecord> recordsToDelete = new ArrayList<>(); - configurationStore.openConfigurationStore(new ConfiguredObjectRecordHandler() - { - - @Override - public void handle(final ConfiguredObjectRecord record) - { - recordsToDelete.add(record); - } - - }); - if(!recordsToDelete.isEmpty()) - { - configurationStore.remove(recordsToDelete.toArray(new ConfiguredObjectRecord[recordsToDelete.size()])); - } - } - - public List<ConfiguredObjectRecord> getConfiguredObjectRecords() - { - return _store.getConfiguredObjectRecords(); - - } - - 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 - - for(ConfiguredObjectRecord record : getConfiguredObjectRecords()) - { - if (record.getType().equals(VirtualHostAlias.class.getSimpleName()) - && name.equals(record.getAttributes().get(ConfiguredObject.NAME))) - { - aliasRecords.add(record); - } - } - - _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 addHttpManagementConfiguration() - { - setObjectAttribute(AuthenticationProvider.class, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER, - "secureOnlyMechanisms", "{}"); - setObjectAttribute(Port.class, TestBrokerConfiguration.ENTRY_NAME_HTTP_PORT, Port.AUTHENTICATION_PROVIDER, - TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER); - - Map<String, Object> attributes = new HashMap<>(); - attributes.put(Plugin.TYPE, MANAGEMENT_HTTP_PLUGIN_TYPE); - attributes.put(Plugin.NAME, ENTRY_NAME_HTTP_MANAGEMENT); - attributes.put(HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED, true); - 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, AclFileAccessControlProvider.ACL_FILE_PROVIDER_TYPE); - attributes.put(AclFileAccessControlProvider.PATH, aclFilePath); - - return addObjectConfiguration(AccessControlProvider.class, attributes); - } - - public UUID addAclRuleConfiguration(AclRule[] aclRules) - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(AccessControlProvider.NAME, ENTRY_NAME_ACL_RULES); - attributes.put(AccessControlProvider.TYPE, RuleBasedAccessControlProvider.RULE_BASED_TYPE); - attributes.put(RuleBasedAccessControlProvider.RULES, aclRules); - - 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) - { - Collection<ConfiguredObjectRecord> records = getConfiguredObjectRecords(); - for(ConfiguredObjectRecord record : records) - { - if (record.getType().equals(category.getSimpleName()) - && (objectName == null - || objectName.equals(record.getAttributes().get(ConfiguredObject.NAME)))) - { - return record; - } - } - return null; - - } - - 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 Map<String,Object> getObjectAttributes(final Class<? extends ConfiguredObject> category, final String name) - { - return findObject(category, name).getAttributes(); - } - - public void createVirtualHostNode(final String virtualHostNodeName, - final String storeType, - final String storeDir, - final String blueprint) - { - Map<String, Object> attributes = new HashMap<>(); - attributes.put(VirtualHostNode.NAME, virtualHostNodeName); - attributes.put(VirtualHostNode.TYPE, storeType); - if (storeDir != null) - { - attributes.put(JsonVirtualHostNode.STORE_PATH, storeDir); - } - - if (blueprint != null) - { - attributes.put(VirtualHostNode.CONTEXT, - Collections.singletonMap(VirtualHostNode.VIRTUALHOST_BLUEPRINT_CONTEXT_VAR, blueprint)); - } - - addObjectConfiguration(VirtualHostNode.class, attributes); - } - - public void configureTemporaryPasswordFile(String... users) throws IOException - { - _passwdFile = createTemporaryPasswordFile(users); - - setObjectAttribute(AuthenticationProvider.class, TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER, - "path", _passwdFile.getAbsolutePath()); - } - - public void cleanUp() - { - if (_passwdFile != null) - { - if (_passwdFile.exists()) - { - _passwdFile.delete(); - } - } - } - - public File createTemporaryPasswordFile(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(); - } - } - } - -} http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/768f4fb0/systests/src/main/java/org/apache/qpid/test/utils/TestUtils.java ---------------------------------------------------------------------- diff --git a/systests/src/main/java/org/apache/qpid/test/utils/TestUtils.java b/systests/src/main/java/org/apache/qpid/test/utils/TestUtils.java deleted file mode 100644 index 5069e20..0000000 --- a/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(); - } -} --------------------------------------------------------------------- To unsubscribe, e-mail: commits-unsubscr...@qpid.apache.org For additional commands, e-mail: commits-h...@qpid.apache.org