From d964eae817b538c532996af0b41993d128fa5a5c Mon Sep 17 00:00:00 2001 From: Robert Godfrey Date: Thu, 24 Apr 2008 17:49:03 +0000 Subject: QPID-832 : Fix eol-style git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk/qpid@651325 13f79535-47bb-0310-9956-ffa450edef68 --- .../exchange/MessagingTestConfigProperties.java | 616 ++++++------- .../ReturnUnroutableMandatoryMessageTest.java | 624 ++++++------- .../apache/qpid/test/framework/AMQPPublisher.java | 108 +-- .../qpid/test/framework/BrokerLifecycleAware.java | 140 +-- .../apache/qpid/test/framework/CauseFailure.java | 84 +- .../test/framework/CauseFailureUserPrompt.java | 130 +-- .../qpid/test/framework/FrameworkTestContext.java | 96 +- .../test/framework/LocalAMQPCircuitFactory.java | 336 +++---- .../qpid/test/framework/LocalCircuitFactory.java | 632 ++++++------- .../qpid/test/framework/MessageIdentityVector.java | 334 +++---- .../test/framework/NotApplicableAssertion.java | 224 ++--- .../apache/qpid/test/framework/TestCaseVector.java | 176 ++-- .../framework/distributedtesting/TestClient.java | 994 ++++++++++----------- .../localcircuit/LocalAMQPPublisherImpl.java | 266 +++--- .../test/framework/qpid/AMQPFeatureDecorator.java | 192 ++-- .../test/framework/qpid/CauseFailureDecorator.java | 190 ++-- .../qpid/test/framework/qpid/CauseFailureInVM.java | 140 +-- .../test/framework/qpid/InVMBrokerDecorator.java | 270 +++--- .../apache/qpid/test/testcases/FailoverTest.java | 238 ++--- .../qpid/test/testcases/ImmediateMessageTest.java | 606 ++++++------- .../qpid/test/testcases/MandatoryMessageTest.java | 642 ++++++------- .../apache/qpid/test/testcases/RollbackTest.java | 264 +++--- .../org/apache/qpid/test/testcases/TTLTest.java | 302 +++---- .../qpid/testutil/QpidClientConnectionHelper.java | 592 ++++++------ 24 files changed, 4098 insertions(+), 4098 deletions(-) (limited to 'java/systests/src') diff --git a/java/systests/src/main/java/org/apache/qpid/server/exchange/MessagingTestConfigProperties.java b/java/systests/src/main/java/org/apache/qpid/server/exchange/MessagingTestConfigProperties.java index 3a3b7f92dd..2d89d319d7 100644 --- a/java/systests/src/main/java/org/apache/qpid/server/exchange/MessagingTestConfigProperties.java +++ b/java/systests/src/main/java/org/apache/qpid/server/exchange/MessagingTestConfigProperties.java @@ -1,308 +1,308 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.exchange; - -import org.apache.qpid.jms.Session; -import org.apache.qpid.junit.extensions.util.ParsedProperties; - -/** - * MessagingTestConfigProperties defines a set of property names and default values for specifying a messaging topology, - * and test parameters for running a messaging test over that topology. A Properties object holding some of these - * properties, superimposed onto the defaults, is used to establish test topologies and control test behaviour. - * - *

A complete list of the parameters, default values and comments on their usage is provided here: - * - *

- *
Parameters
Parameter Default Comments - *
messageSize 0 Message size in bytes. Not including any headers. - *
destinationName ping The root name to use to generate destination names to ping. - *
persistent false Determines whether peristent delivery is used. - *
transacted false Determines whether messages are sent/received in transactions. - *
broker tcp://localhost:5672 Determines the broker to connect to. - *
virtualHost test Determines the virtual host to send all ping over. - *
rate 0 The maximum rate (in hertz) to send messages at. 0 means no limit. - *
verbose false The verbose flag for debugging. Prints to console on every message. - *
pubsub false Whether to ping topics or queues. Uses p2p by default. - *
username guest The username to access the broker with. - *
password guest The password to access the broker with. - *
selector null Not used. Defines a message selector to filter pings with. - *
destinationCount 1 The number of receivers listening to the pings. - *
timeout 30000 In milliseconds. The timeout to stop waiting for replies. - *
commitBatchSize 1 The number of messages per transaction in transactional mode. - *
uniqueDests true Whether each receiver only listens to one ping destination or all. - *
durableDests false Whether or not durable destinations are used. - *
ackMode AUTO_ACK The message acknowledgement mode. Possible values are: - * 0 - SESSION_TRANSACTED - * 1 - AUTO_ACKNOWLEDGE - * 2 - CLIENT_ACKNOWLEDGE - * 3 - DUPS_OK_ACKNOWLEDGE - * 257 - NO_ACKNOWLEDGE - * 258 - PRE_ACKNOWLEDGE - *
maxPending 0 The maximum size in bytes, of messages sent but not yet received. - * Limits the volume of messages currently buffered on the client - * or broker. Can help scale test clients by limiting amount of buffered - * data to avoid out of memory errors. - *
- * - *

- *
CRC Card
Responsibilities Collaborations - *
Provide the names and defaults of all test parameters. - *
- */ -public class MessagingTestConfigProperties -{ - // ====================== Connection Properties ================================== - - /** Holds the name of the default connection configuration. */ - public static final String CONNECTION_NAME = "broker"; - - /** Holds the name of the property to get the initial context factory name from. */ - public static final String INITIAL_CONTEXT_FACTORY_PROPNAME = "java.naming.factory.initial"; - - /** Defines the class to use as the initial context factory by default. */ - public static final String INITIAL_CONTEXT_FACTORY_DEFAULT = "org.apache.qpid.jndi.PropertiesFileInitialContextFactory"; - - /** Holds the name of the default connection factory configuration property. */ - public static final String CONNECTION_PROPNAME = "connectionfactory.broker"; - - /** Defeins the default connection configuration. */ - public static final String CONNECTION_DEFAULT = "amqp://guest:guest@clientid/?brokerlist='vm://:1'"; - - /** Holds the name of the property to get the test broker url from. */ - public static final String BROKER_PROPNAME = "qpid.test.broker"; - - /** Holds the default broker url for the test. */ - public static final String BROKER_DEFAULT = "vm://:1"; - - /** Holds the name of the property to get the test broker virtual path. */ - public static final String VIRTUAL_HOST_PROPNAME = "virtualHost"; - - /** Holds the default virtual path for the test. */ - public static final String VIRTUAL_HOST_DEFAULT = ""; - - /** Holds the name of the property to get the broker access username from. */ - public static final String USERNAME_PROPNAME = "username"; - - /** Holds the default broker log on username. */ - public static final String USERNAME_DEFAULT = "guest"; - - /** Holds the name of the property to get the broker access password from. */ - public static final String PASSWORD_PROPNAME = "password"; - - /** Holds the default broker log on password. */ - public static final String PASSWORD_DEFAULT = "guest"; - - // ====================== Messaging Topology Properties ========================== - - /** Holds the name of the property to get the bind publisher procuder flag from. */ - public static final String PUBLISHER_PRODUCER_BIND_PROPNAME = "publisherProducerBind"; - - /** Holds the default value of the publisher producer flag. */ - public static final boolean PUBLISHER_PRODUCER_BIND_DEFAULT = true; - - /** Holds the name of the property to get the bind publisher procuder flag from. */ - public static final String PUBLISHER_CONSUMER_BIND_PROPNAME = "publisherConsumerBind"; - - /** Holds the default value of the publisher consumer flag. */ - public static final boolean PUBLISHER_CONSUMER_BIND_DEFAULT = false; - - /** Holds the name of the property to get the bind receiver procuder flag from. */ - public static final String RECEIVER_PRODUCER_BIND_PROPNAME = "receiverProducerBind"; - - /** Holds the default value of the receiver producer flag. */ - public static final boolean RECEIVER_PRODUCER_BIND_DEFAULT = false; - - /** Holds the name of the property to get the bind receiver procuder flag from. */ - public static final String RECEIVER_CONSUMER_BIND_PROPNAME = "receiverConsumerBind"; - - /** Holds the default value of the receiver consumer flag. */ - public static final boolean RECEIVER_CONSUMER_BIND_DEFAULT = true; - - /** Holds the name of the property to get the destination name root from. */ - public static final String SEND_DESTINATION_NAME_ROOT_PROPNAME = "sendDestinationRoot"; - - /** Holds the root of the name of the default destination to send to. */ - public static final String SEND_DESTINATION_NAME_ROOT_DEFAULT = "sendTo"; - - /** Holds the name of the property to get the destination name root from. */ - public static final String RECEIVE_DESTINATION_NAME_ROOT_PROPNAME = "receiveDestinationRoot"; - - /** Holds the root of the name of the default destination to send to. */ - public static final String RECEIVE_DESTINATION_NAME_ROOT_DEFAULT = "receiveFrom"; - - /** Holds the name of the proeprty to get the destination count from. */ - public static final String DESTINATION_COUNT_PROPNAME = "destinationCount"; - - /** Defines the default number of destinations to ping. */ - public static final int DESTINATION_COUNT_DEFAULT = 1; - - /** Holds the name of the property to get the p2p or pub/sub messaging mode from. */ - public static final String PUBSUB_PROPNAME = "pubsub"; - - /** Holds the pub/sub mode default, true means ping a topic, false means ping a queue. */ - public static final boolean PUBSUB_DEFAULT = false; - - // ====================== JMS Options and Flags ================================= - - /** Holds the name of the property to get the test delivery mode from. */ - public static final String PERSISTENT_MODE_PROPNAME = "persistent"; - - /** Holds the message delivery mode to use for the test. */ - public static final boolean PERSISTENT_MODE_DEFAULT = false; - - /** Holds the name of the property to get the test transactional mode from. */ - public static final String TRANSACTED_PROPNAME = "transacted"; - - /** Holds the transactional mode to use for the test. */ - public static final boolean TRANSACTED_DEFAULT = false; - - /** Holds the name of the property to set the no local flag from. */ - public static final String NO_LOCAL_PROPNAME = "noLocal"; - - /** Defines the default value of the no local flag to use when consuming messages. */ - public static final boolean NO_LOCAL_DEFAULT = false; - - /** Holds the name of the property to get the message acknowledgement mode from. */ - public static final String ACK_MODE_PROPNAME = "ackMode"; - - /** Defines the default message acknowledgement mode. */ - public static final int ACK_MODE_DEFAULT = Session.AUTO_ACKNOWLEDGE; - - /** Holds the name of the property to get the durable subscriptions flag from, when doing pub/sub messaging. */ - public static final String DURABLE_SUBSCRIPTION_PROPNAME = "durableSubscription"; - - /** Defines the default value of the durable subscriptions flag. */ - public static final boolean DURABLE_SUBSCRIPTION_DEFAULT = false; - - // ====================== Qpid Options and Flags ================================ - - /** Holds the name of the property to set the exclusive flag from. */ - public static final String EXCLUSIVE_PROPNAME = "exclusive"; - - /** Defines the default value of the exclusive flag to use when consuming messages. */ - public static final boolean EXCLUSIVE_DEFAULT = false; - - /** Holds the name of the property to set the immediate flag from. */ - public static final String IMMEDIATE_PROPNAME = "immediate"; - - /** Defines the default value of the immediate flag to use when sending messages. */ - public static final boolean IMMEDIATE_DEFAULT = false; - - /** Holds the name of the property to set the mandatory flag from. */ - public static final String MANDATORY_PROPNAME = "mandatory"; - - /** Defines the default value of the mandatory flag to use when sending messages. */ - public static final boolean MANDATORY_DEFAULT = false; - - /** Holds the name of the property to get the durable destinations flag from. */ - public static final String DURABLE_DESTS_PROPNAME = "durableDests"; - - /** Default value for the durable destinations flag. */ - public static final boolean DURABLE_DESTS_DEFAULT = false; - - /** Holds the name of the proeprty to set the prefetch size from. */ - public static final String PREFECTH_PROPNAME = "prefetch"; - - /** Defines the default prefetch size to use when consuming messages. */ - public static final int PREFETCH_DEFAULT = 100; - - // ====================== Common Test Parameters ================================ - - /** Holds the name of the property to get the test message size from. */ - public static final String MESSAGE_SIZE_PROPNAME = "messageSize"; - - /** Used to set up a default message size. */ - public static final int MESSAGE_SIZE_DEAFULT = 0; - - /** Holds the name of the property to get the message rate from. */ - public static final String RATE_PROPNAME = "rate"; - - /** Defines the default rate (in pings per second) to send pings at. 0 means as fast as possible, no restriction. */ - public static final int RATE_DEFAULT = 0; - - /** Holds the name of the proeprty to get the. */ - public static final String SELECTOR_PROPNAME = "selector"; - - /** Holds the default message selector. */ - public static final String SELECTOR_DEFAULT = ""; - - /** Holds the name of the property to get the waiting timeout for response messages. */ - public static final String TIMEOUT_PROPNAME = "timeout"; - - /** Default time to wait before assuming that a ping has timed out. */ - public static final long TIMEOUT_DEFAULT = 30000; - - /** Holds the name of the property to get the commit batch size from. */ - public static final String TX_BATCH_SIZE_PROPNAME = "commitBatchSize"; - - /** Defines the default number of pings to send in each transaction when running transactionally. */ - public static final int TX_BATCH_SIZE_DEFAULT = 1; - - /** Holds the name of the property to set the maximum amount of pending message data for a producer to hold. */ - public static final String MAX_PENDING_PROPNAME = "maxPending"; - - /** Defines the default maximum quantity of pending message data to allow producers to hold. */ - public static final int MAX_PENDING_DEFAULT = 0; - - /** Holds the name of the property to get the verbose mode proeprty from. */ - public static final String VERBOSE_PROPNAME = "verbose"; - - /** Holds the default verbose mode. */ - public static final boolean VERBOSE_DEFAULT = false; - - /** Holds the default configuration properties. */ - public static ParsedProperties defaults = new ParsedProperties(); - - static - { - defaults.setPropertyIfNull(INITIAL_CONTEXT_FACTORY_PROPNAME, INITIAL_CONTEXT_FACTORY_DEFAULT); - defaults.setPropertyIfNull(CONNECTION_PROPNAME, CONNECTION_DEFAULT); - defaults.setPropertyIfNull(MESSAGE_SIZE_PROPNAME, MESSAGE_SIZE_DEAFULT); - defaults.setPropertyIfNull(PUBLISHER_PRODUCER_BIND_PROPNAME, PUBLISHER_PRODUCER_BIND_DEFAULT); - defaults.setPropertyIfNull(PUBLISHER_CONSUMER_BIND_PROPNAME, PUBLISHER_CONSUMER_BIND_DEFAULT); - defaults.setPropertyIfNull(RECEIVER_PRODUCER_BIND_PROPNAME, RECEIVER_PRODUCER_BIND_DEFAULT); - defaults.setPropertyIfNull(RECEIVER_CONSUMER_BIND_PROPNAME, RECEIVER_CONSUMER_BIND_DEFAULT); - defaults.setPropertyIfNull(SEND_DESTINATION_NAME_ROOT_PROPNAME, SEND_DESTINATION_NAME_ROOT_DEFAULT); - defaults.setPropertyIfNull(RECEIVE_DESTINATION_NAME_ROOT_PROPNAME, RECEIVE_DESTINATION_NAME_ROOT_DEFAULT); - defaults.setPropertyIfNull(PERSISTENT_MODE_PROPNAME, PERSISTENT_MODE_DEFAULT); - defaults.setPropertyIfNull(TRANSACTED_PROPNAME, TRANSACTED_DEFAULT); - defaults.setPropertyIfNull(BROKER_PROPNAME, BROKER_DEFAULT); - defaults.setPropertyIfNull(VIRTUAL_HOST_PROPNAME, VIRTUAL_HOST_DEFAULT); - defaults.setPropertyIfNull(RATE_PROPNAME, RATE_DEFAULT); - defaults.setPropertyIfNull(VERBOSE_PROPNAME, VERBOSE_DEFAULT); - defaults.setPropertyIfNull(PUBSUB_PROPNAME, PUBSUB_DEFAULT); - defaults.setPropertyIfNull(USERNAME_PROPNAME, USERNAME_DEFAULT); - defaults.setPropertyIfNull(PASSWORD_PROPNAME, PASSWORD_DEFAULT); - defaults.setPropertyIfNull(SELECTOR_PROPNAME, SELECTOR_DEFAULT); - defaults.setPropertyIfNull(DESTINATION_COUNT_PROPNAME, DESTINATION_COUNT_DEFAULT); - defaults.setPropertyIfNull(TIMEOUT_PROPNAME, TIMEOUT_DEFAULT); - defaults.setPropertyIfNull(TX_BATCH_SIZE_PROPNAME, TX_BATCH_SIZE_DEFAULT); - defaults.setPropertyIfNull(DURABLE_DESTS_PROPNAME, DURABLE_DESTS_DEFAULT); - defaults.setPropertyIfNull(ACK_MODE_PROPNAME, ACK_MODE_DEFAULT); - defaults.setPropertyIfNull(DURABLE_SUBSCRIPTION_PROPNAME, DURABLE_SUBSCRIPTION_DEFAULT); - defaults.setPropertyIfNull(MAX_PENDING_PROPNAME, MAX_PENDING_DEFAULT); - defaults.setPropertyIfNull(PREFECTH_PROPNAME, PREFETCH_DEFAULT); - defaults.setPropertyIfNull(NO_LOCAL_PROPNAME, NO_LOCAL_DEFAULT); - defaults.setPropertyIfNull(EXCLUSIVE_PROPNAME, EXCLUSIVE_DEFAULT); - defaults.setPropertyIfNull(IMMEDIATE_PROPNAME, IMMEDIATE_DEFAULT); - defaults.setPropertyIfNull(MANDATORY_PROPNAME, MANDATORY_DEFAULT); - } -} +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.exchange; + +import org.apache.qpid.jms.Session; +import org.apache.qpid.junit.extensions.util.ParsedProperties; + +/** + * MessagingTestConfigProperties defines a set of property names and default values for specifying a messaging topology, + * and test parameters for running a messaging test over that topology. A Properties object holding some of these + * properties, superimposed onto the defaults, is used to establish test topologies and control test behaviour. + * + *

A complete list of the parameters, default values and comments on their usage is provided here: + * + *

+ *
Parameters
Parameter Default Comments + *
messageSize 0 Message size in bytes. Not including any headers. + *
destinationName ping The root name to use to generate destination names to ping. + *
persistent false Determines whether peristent delivery is used. + *
transacted false Determines whether messages are sent/received in transactions. + *
broker tcp://localhost:5672 Determines the broker to connect to. + *
virtualHost test Determines the virtual host to send all ping over. + *
rate 0 The maximum rate (in hertz) to send messages at. 0 means no limit. + *
verbose false The verbose flag for debugging. Prints to console on every message. + *
pubsub false Whether to ping topics or queues. Uses p2p by default. + *
username guest The username to access the broker with. + *
password guest The password to access the broker with. + *
selector null Not used. Defines a message selector to filter pings with. + *
destinationCount 1 The number of receivers listening to the pings. + *
timeout 30000 In milliseconds. The timeout to stop waiting for replies. + *
commitBatchSize 1 The number of messages per transaction in transactional mode. + *
uniqueDests true Whether each receiver only listens to one ping destination or all. + *
durableDests false Whether or not durable destinations are used. + *
ackMode AUTO_ACK The message acknowledgement mode. Possible values are: + * 0 - SESSION_TRANSACTED + * 1 - AUTO_ACKNOWLEDGE + * 2 - CLIENT_ACKNOWLEDGE + * 3 - DUPS_OK_ACKNOWLEDGE + * 257 - NO_ACKNOWLEDGE + * 258 - PRE_ACKNOWLEDGE + *
maxPending 0 The maximum size in bytes, of messages sent but not yet received. + * Limits the volume of messages currently buffered on the client + * or broker. Can help scale test clients by limiting amount of buffered + * data to avoid out of memory errors. + *
+ * + *

+ *
CRC Card
Responsibilities Collaborations + *
Provide the names and defaults of all test parameters. + *
+ */ +public class MessagingTestConfigProperties +{ + // ====================== Connection Properties ================================== + + /** Holds the name of the default connection configuration. */ + public static final String CONNECTION_NAME = "broker"; + + /** Holds the name of the property to get the initial context factory name from. */ + public static final String INITIAL_CONTEXT_FACTORY_PROPNAME = "java.naming.factory.initial"; + + /** Defines the class to use as the initial context factory by default. */ + public static final String INITIAL_CONTEXT_FACTORY_DEFAULT = "org.apache.qpid.jndi.PropertiesFileInitialContextFactory"; + + /** Holds the name of the default connection factory configuration property. */ + public static final String CONNECTION_PROPNAME = "connectionfactory.broker"; + + /** Defeins the default connection configuration. */ + public static final String CONNECTION_DEFAULT = "amqp://guest:guest@clientid/?brokerlist='vm://:1'"; + + /** Holds the name of the property to get the test broker url from. */ + public static final String BROKER_PROPNAME = "qpid.test.broker"; + + /** Holds the default broker url for the test. */ + public static final String BROKER_DEFAULT = "vm://:1"; + + /** Holds the name of the property to get the test broker virtual path. */ + public static final String VIRTUAL_HOST_PROPNAME = "virtualHost"; + + /** Holds the default virtual path for the test. */ + public static final String VIRTUAL_HOST_DEFAULT = ""; + + /** Holds the name of the property to get the broker access username from. */ + public static final String USERNAME_PROPNAME = "username"; + + /** Holds the default broker log on username. */ + public static final String USERNAME_DEFAULT = "guest"; + + /** Holds the name of the property to get the broker access password from. */ + public static final String PASSWORD_PROPNAME = "password"; + + /** Holds the default broker log on password. */ + public static final String PASSWORD_DEFAULT = "guest"; + + // ====================== Messaging Topology Properties ========================== + + /** Holds the name of the property to get the bind publisher procuder flag from. */ + public static final String PUBLISHER_PRODUCER_BIND_PROPNAME = "publisherProducerBind"; + + /** Holds the default value of the publisher producer flag. */ + public static final boolean PUBLISHER_PRODUCER_BIND_DEFAULT = true; + + /** Holds the name of the property to get the bind publisher procuder flag from. */ + public static final String PUBLISHER_CONSUMER_BIND_PROPNAME = "publisherConsumerBind"; + + /** Holds the default value of the publisher consumer flag. */ + public static final boolean PUBLISHER_CONSUMER_BIND_DEFAULT = false; + + /** Holds the name of the property to get the bind receiver procuder flag from. */ + public static final String RECEIVER_PRODUCER_BIND_PROPNAME = "receiverProducerBind"; + + /** Holds the default value of the receiver producer flag. */ + public static final boolean RECEIVER_PRODUCER_BIND_DEFAULT = false; + + /** Holds the name of the property to get the bind receiver procuder flag from. */ + public static final String RECEIVER_CONSUMER_BIND_PROPNAME = "receiverConsumerBind"; + + /** Holds the default value of the receiver consumer flag. */ + public static final boolean RECEIVER_CONSUMER_BIND_DEFAULT = true; + + /** Holds the name of the property to get the destination name root from. */ + public static final String SEND_DESTINATION_NAME_ROOT_PROPNAME = "sendDestinationRoot"; + + /** Holds the root of the name of the default destination to send to. */ + public static final String SEND_DESTINATION_NAME_ROOT_DEFAULT = "sendTo"; + + /** Holds the name of the property to get the destination name root from. */ + public static final String RECEIVE_DESTINATION_NAME_ROOT_PROPNAME = "receiveDestinationRoot"; + + /** Holds the root of the name of the default destination to send to. */ + public static final String RECEIVE_DESTINATION_NAME_ROOT_DEFAULT = "receiveFrom"; + + /** Holds the name of the proeprty to get the destination count from. */ + public static final String DESTINATION_COUNT_PROPNAME = "destinationCount"; + + /** Defines the default number of destinations to ping. */ + public static final int DESTINATION_COUNT_DEFAULT = 1; + + /** Holds the name of the property to get the p2p or pub/sub messaging mode from. */ + public static final String PUBSUB_PROPNAME = "pubsub"; + + /** Holds the pub/sub mode default, true means ping a topic, false means ping a queue. */ + public static final boolean PUBSUB_DEFAULT = false; + + // ====================== JMS Options and Flags ================================= + + /** Holds the name of the property to get the test delivery mode from. */ + public static final String PERSISTENT_MODE_PROPNAME = "persistent"; + + /** Holds the message delivery mode to use for the test. */ + public static final boolean PERSISTENT_MODE_DEFAULT = false; + + /** Holds the name of the property to get the test transactional mode from. */ + public static final String TRANSACTED_PROPNAME = "transacted"; + + /** Holds the transactional mode to use for the test. */ + public static final boolean TRANSACTED_DEFAULT = false; + + /** Holds the name of the property to set the no local flag from. */ + public static final String NO_LOCAL_PROPNAME = "noLocal"; + + /** Defines the default value of the no local flag to use when consuming messages. */ + public static final boolean NO_LOCAL_DEFAULT = false; + + /** Holds the name of the property to get the message acknowledgement mode from. */ + public static final String ACK_MODE_PROPNAME = "ackMode"; + + /** Defines the default message acknowledgement mode. */ + public static final int ACK_MODE_DEFAULT = Session.AUTO_ACKNOWLEDGE; + + /** Holds the name of the property to get the durable subscriptions flag from, when doing pub/sub messaging. */ + public static final String DURABLE_SUBSCRIPTION_PROPNAME = "durableSubscription"; + + /** Defines the default value of the durable subscriptions flag. */ + public static final boolean DURABLE_SUBSCRIPTION_DEFAULT = false; + + // ====================== Qpid Options and Flags ================================ + + /** Holds the name of the property to set the exclusive flag from. */ + public static final String EXCLUSIVE_PROPNAME = "exclusive"; + + /** Defines the default value of the exclusive flag to use when consuming messages. */ + public static final boolean EXCLUSIVE_DEFAULT = false; + + /** Holds the name of the property to set the immediate flag from. */ + public static final String IMMEDIATE_PROPNAME = "immediate"; + + /** Defines the default value of the immediate flag to use when sending messages. */ + public static final boolean IMMEDIATE_DEFAULT = false; + + /** Holds the name of the property to set the mandatory flag from. */ + public static final String MANDATORY_PROPNAME = "mandatory"; + + /** Defines the default value of the mandatory flag to use when sending messages. */ + public static final boolean MANDATORY_DEFAULT = false; + + /** Holds the name of the property to get the durable destinations flag from. */ + public static final String DURABLE_DESTS_PROPNAME = "durableDests"; + + /** Default value for the durable destinations flag. */ + public static final boolean DURABLE_DESTS_DEFAULT = false; + + /** Holds the name of the proeprty to set the prefetch size from. */ + public static final String PREFECTH_PROPNAME = "prefetch"; + + /** Defines the default prefetch size to use when consuming messages. */ + public static final int PREFETCH_DEFAULT = 100; + + // ====================== Common Test Parameters ================================ + + /** Holds the name of the property to get the test message size from. */ + public static final String MESSAGE_SIZE_PROPNAME = "messageSize"; + + /** Used to set up a default message size. */ + public static final int MESSAGE_SIZE_DEAFULT = 0; + + /** Holds the name of the property to get the message rate from. */ + public static final String RATE_PROPNAME = "rate"; + + /** Defines the default rate (in pings per second) to send pings at. 0 means as fast as possible, no restriction. */ + public static final int RATE_DEFAULT = 0; + + /** Holds the name of the proeprty to get the. */ + public static final String SELECTOR_PROPNAME = "selector"; + + /** Holds the default message selector. */ + public static final String SELECTOR_DEFAULT = ""; + + /** Holds the name of the property to get the waiting timeout for response messages. */ + public static final String TIMEOUT_PROPNAME = "timeout"; + + /** Default time to wait before assuming that a ping has timed out. */ + public static final long TIMEOUT_DEFAULT = 30000; + + /** Holds the name of the property to get the commit batch size from. */ + public static final String TX_BATCH_SIZE_PROPNAME = "commitBatchSize"; + + /** Defines the default number of pings to send in each transaction when running transactionally. */ + public static final int TX_BATCH_SIZE_DEFAULT = 1; + + /** Holds the name of the property to set the maximum amount of pending message data for a producer to hold. */ + public static final String MAX_PENDING_PROPNAME = "maxPending"; + + /** Defines the default maximum quantity of pending message data to allow producers to hold. */ + public static final int MAX_PENDING_DEFAULT = 0; + + /** Holds the name of the property to get the verbose mode proeprty from. */ + public static final String VERBOSE_PROPNAME = "verbose"; + + /** Holds the default verbose mode. */ + public static final boolean VERBOSE_DEFAULT = false; + + /** Holds the default configuration properties. */ + public static ParsedProperties defaults = new ParsedProperties(); + + static + { + defaults.setPropertyIfNull(INITIAL_CONTEXT_FACTORY_PROPNAME, INITIAL_CONTEXT_FACTORY_DEFAULT); + defaults.setPropertyIfNull(CONNECTION_PROPNAME, CONNECTION_DEFAULT); + defaults.setPropertyIfNull(MESSAGE_SIZE_PROPNAME, MESSAGE_SIZE_DEAFULT); + defaults.setPropertyIfNull(PUBLISHER_PRODUCER_BIND_PROPNAME, PUBLISHER_PRODUCER_BIND_DEFAULT); + defaults.setPropertyIfNull(PUBLISHER_CONSUMER_BIND_PROPNAME, PUBLISHER_CONSUMER_BIND_DEFAULT); + defaults.setPropertyIfNull(RECEIVER_PRODUCER_BIND_PROPNAME, RECEIVER_PRODUCER_BIND_DEFAULT); + defaults.setPropertyIfNull(RECEIVER_CONSUMER_BIND_PROPNAME, RECEIVER_CONSUMER_BIND_DEFAULT); + defaults.setPropertyIfNull(SEND_DESTINATION_NAME_ROOT_PROPNAME, SEND_DESTINATION_NAME_ROOT_DEFAULT); + defaults.setPropertyIfNull(RECEIVE_DESTINATION_NAME_ROOT_PROPNAME, RECEIVE_DESTINATION_NAME_ROOT_DEFAULT); + defaults.setPropertyIfNull(PERSISTENT_MODE_PROPNAME, PERSISTENT_MODE_DEFAULT); + defaults.setPropertyIfNull(TRANSACTED_PROPNAME, TRANSACTED_DEFAULT); + defaults.setPropertyIfNull(BROKER_PROPNAME, BROKER_DEFAULT); + defaults.setPropertyIfNull(VIRTUAL_HOST_PROPNAME, VIRTUAL_HOST_DEFAULT); + defaults.setPropertyIfNull(RATE_PROPNAME, RATE_DEFAULT); + defaults.setPropertyIfNull(VERBOSE_PROPNAME, VERBOSE_DEFAULT); + defaults.setPropertyIfNull(PUBSUB_PROPNAME, PUBSUB_DEFAULT); + defaults.setPropertyIfNull(USERNAME_PROPNAME, USERNAME_DEFAULT); + defaults.setPropertyIfNull(PASSWORD_PROPNAME, PASSWORD_DEFAULT); + defaults.setPropertyIfNull(SELECTOR_PROPNAME, SELECTOR_DEFAULT); + defaults.setPropertyIfNull(DESTINATION_COUNT_PROPNAME, DESTINATION_COUNT_DEFAULT); + defaults.setPropertyIfNull(TIMEOUT_PROPNAME, TIMEOUT_DEFAULT); + defaults.setPropertyIfNull(TX_BATCH_SIZE_PROPNAME, TX_BATCH_SIZE_DEFAULT); + defaults.setPropertyIfNull(DURABLE_DESTS_PROPNAME, DURABLE_DESTS_DEFAULT); + defaults.setPropertyIfNull(ACK_MODE_PROPNAME, ACK_MODE_DEFAULT); + defaults.setPropertyIfNull(DURABLE_SUBSCRIPTION_PROPNAME, DURABLE_SUBSCRIPTION_DEFAULT); + defaults.setPropertyIfNull(MAX_PENDING_PROPNAME, MAX_PENDING_DEFAULT); + defaults.setPropertyIfNull(PREFECTH_PROPNAME, PREFETCH_DEFAULT); + defaults.setPropertyIfNull(NO_LOCAL_PROPNAME, NO_LOCAL_DEFAULT); + defaults.setPropertyIfNull(EXCLUSIVE_PROPNAME, EXCLUSIVE_DEFAULT); + defaults.setPropertyIfNull(IMMEDIATE_PROPNAME, IMMEDIATE_DEFAULT); + defaults.setPropertyIfNull(MANDATORY_PROPNAME, MANDATORY_DEFAULT); + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/server/exchange/ReturnUnroutableMandatoryMessageTest.java b/java/systests/src/main/java/org/apache/qpid/server/exchange/ReturnUnroutableMandatoryMessageTest.java index a6a2bbb80f..bae3f844d7 100644 --- a/java/systests/src/main/java/org/apache/qpid/server/exchange/ReturnUnroutableMandatoryMessageTest.java +++ b/java/systests/src/main/java/org/apache/qpid/server/exchange/ReturnUnroutableMandatoryMessageTest.java @@ -1,312 +1,312 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.exchange; - -import junit.framework.TestCase; -import org.apache.log4j.Logger; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.util.NullApplicationRegistry; -import org.apache.qpid.client.*; -import org.apache.qpid.client.transport.TransportConnection; -import org.apache.qpid.url.AMQBindingURL; -import org.apache.qpid.url.BindingURL; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.FieldTable; - -import javax.jms.*; -import java.util.List; -import java.util.Collections; -import java.util.ArrayList; - -public class ReturnUnroutableMandatoryMessageTest extends TestCase implements ExceptionListener -{ - private static final Logger _logger = Logger.getLogger(ReturnUnroutableMandatoryMessageTest.class); - - private final List _bouncedMessageList = Collections.synchronizedList(new ArrayList()); - private static final String VIRTUALHOST = "test"; - private static final String BROKER = "vm://:1"; - - static - { - String workdir = System.getProperty("QPID_WORK"); - if (workdir == null || workdir.equals("")) - { - String tempdir = System.getProperty("java.io.tmpdir"); - System.out.println("QPID_WORK not set using tmp directory: " + tempdir); - System.setProperty("QPID_WORK", tempdir); - } -// DOMConfigurator.configure("../broker/etc/log4j.xml"); - } - - protected void setUp() throws Exception - { - super.setUp(); - TransportConnection.createVMBroker(1); - ApplicationRegistry.initialise(new NullApplicationRegistry(), 1); - } - - protected void tearDown() throws Exception - { - super.tearDown(); - TransportConnection.killAllVMBrokers(); - } - - /** - * Tests that mandatory message which are not routable are returned to the producer - * - * @throws Exception - */ - public void testReturnUnroutableMandatoryMessage_HEADERS() throws Exception - { - _bouncedMessageList.clear(); - Connection con = new AMQConnection(BROKER, "guest", "guest", "consumer1", VIRTUALHOST); - - - AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - AMQHeadersExchange queue = new AMQHeadersExchange(new AMQBindingURL(ExchangeDefaults.HEADERS_EXCHANGE_CLASS + "://" + ExchangeDefaults.HEADERS_EXCHANGE_NAME + "/test/queue1?" + BindingURL.OPTION_ROUTING_KEY + "='F0000=1'")); - FieldTable ft = new FieldTable(); - ft.setString("F1000", "1"); - MessageConsumer consumer = consumerSession.createConsumer(queue, AMQSession.DEFAULT_PREFETCH_LOW_MARK, AMQSession.DEFAULT_PREFETCH_HIGH_MARK, false, false, (String) null, ft); - - //force synch to ensure the consumer has resulted in a bound queue - //((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.HEADERS_EXCHANGE_NAME, ExchangeDefaults.HEADERS_EXCHANGE_CLASS); - // This is the default now - - Connection con2 = new AMQConnection(BROKER, "guest", "guest", "producer1", VIRTUALHOST); - - con2.setExceptionListener(this); - AMQSession producerSession = (AMQSession) con2.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - // Need to start the "producer" connection in order to receive bounced messages - _logger.info("Starting producer connection"); - con2.start(); - - - MessageProducer nonMandatoryProducer = producerSession.createProducer(queue, false, false); - MessageProducer mandatoryProducer = producerSession.createProducer(queue); - - // First test - should neither be bounced nor routed - _logger.info("Sending non-routable non-mandatory message"); - TextMessage msg1 = producerSession.createTextMessage("msg1"); - nonMandatoryProducer.send(msg1); - - // Second test - should be bounced - _logger.info("Sending non-routable mandatory message"); - TextMessage msg2 = producerSession.createTextMessage("msg2"); - mandatoryProducer.send(msg2); - - // Third test - should be routed - _logger.info("Sending routable message"); - TextMessage msg3 = producerSession.createTextMessage("msg3"); - msg3.setStringProperty("F1000", "1"); - mandatoryProducer.send(msg3); - - - _logger.info("Starting consumer connection"); - con.start(); - TextMessage tm = (TextMessage) consumer.receive(1000L); - - assertTrue("No message routed to receiver", tm != null); - assertTrue("Wrong message routed to receiver: " + tm.getText(), "msg3".equals(tm.getText())); - - try - { - Thread.sleep(1000L); - } - catch (InterruptedException e) - { - ; - } - - assertTrue("Wrong number of messages bounced (expect 1): " + _bouncedMessageList.size(), _bouncedMessageList.size() == 1); - Message m = _bouncedMessageList.get(0); - assertTrue("Wrong message bounced: " + m.toString(), m.toString().contains("msg2")); - - - con.close(); - con2.close(); - - - } - - public void testReturnUnroutableMandatoryMessage_QUEUE() throws Exception - { - _bouncedMessageList.clear(); - Connection con = new AMQConnection(BROKER, "guest", "guest", "consumer1", VIRTUALHOST); - - - AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - AMQQueue valid_queue = new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_CLASS, "testReturnUnroutableMandatoryMessage_QUEUE"); - AMQQueue invalid_queue = new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_CLASS, "testReturnUnroutableMandatoryMessage_QUEUE_INVALID"); - MessageConsumer consumer = consumerSession.createConsumer(valid_queue); - - //force synch to ensure the consumer has resulted in a bound queue - //((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.HEADERS_EXCHANGE_NAME, ExchangeDefaults.HEADERS_EXCHANGE_CLASS); - // This is the default now - - Connection con2 = new AMQConnection(BROKER, "guest", "guest", "producer1", VIRTUALHOST); - - con2.setExceptionListener(this); - AMQSession producerSession = (AMQSession) con2.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - // Need to start the "producer" connection in order to receive bounced messages - _logger.info("Starting producer connection"); - con2.start(); - - - MessageProducer nonMandatoryProducer = producerSession.createProducer(valid_queue, false, false); - MessageProducer mandatoryProducer = producerSession.createProducer(invalid_queue); - - // First test - should be routed - _logger.info("Sending non-mandatory message"); - TextMessage msg1 = producerSession.createTextMessage("msg1"); - nonMandatoryProducer.send(msg1); - - // Second test - should be bounced - _logger.info("Sending non-routable mandatory message"); - TextMessage msg2 = producerSession.createTextMessage("msg2"); - mandatoryProducer.send(msg2); - - - _logger.info("Starting consumer connection"); - con.start(); - TextMessage tm = (TextMessage) consumer.receive(1000L); - - assertTrue("No message routed to receiver", tm != null); - assertTrue("Wrong message routed to receiver: " + tm.getText(), "msg1".equals(tm.getText())); - - try - { - Thread.sleep(1000L); - } - catch (InterruptedException e) - { - ; - } - - assertTrue("Wrong number of messages bounced (expect 1): " + _bouncedMessageList.size(), _bouncedMessageList.size() == 1); - Message m = _bouncedMessageList.get(0); - assertTrue("Wrong message bounced: " + m.toString(), m.toString().contains("msg2")); - - - con.close(); - con2.close(); - } - - - public void testReturnUnroutableMandatoryMessage_TOPIC() throws Exception - { - _bouncedMessageList.clear(); - Connection con = new AMQConnection(BROKER, "guest", "guest", "consumer1", VIRTUALHOST); - - - AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - AMQTopic valid_topic = new AMQTopic(ExchangeDefaults.TOPIC_EXCHANGE_CLASS, "test.Return.Unroutable.Mandatory.Message.TOPIC"); - AMQTopic invalid_topic = new AMQTopic(ExchangeDefaults.TOPIC_EXCHANGE_CLASS, "test.Return.Unroutable.Mandatory.Message.TOPIC.invalid"); - MessageConsumer consumer = consumerSession.createConsumer(valid_topic); - - //force synch to ensure the consumer has resulted in a bound queue - //((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.HEADERS_EXCHANGE_NAME, ExchangeDefaults.HEADERS_EXCHANGE_CLASS); - // This is the default now - - Connection con2 = new AMQConnection(BROKER, "guest", "guest", "producer1", VIRTUALHOST); - - con2.setExceptionListener(this); - AMQSession producerSession = (AMQSession) con2.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - // Need to start the "producer" connection in order to receive bounced messages - _logger.info("Starting producer connection"); - con2.start(); - - - MessageProducer nonMandatoryProducer = producerSession.createProducer(valid_topic, false, false); - MessageProducer mandatoryProducer = producerSession.createProducer(invalid_topic); - - // First test - should be routed - _logger.info("Sending non-mandatory message"); - TextMessage msg1 = producerSession.createTextMessage("msg1"); - nonMandatoryProducer.send(msg1); - - // Second test - should be bounced - _logger.info("Sending non-routable mandatory message"); - TextMessage msg2 = producerSession.createTextMessage("msg2"); - mandatoryProducer.send(msg2); - - - _logger.info("Starting consumer connection"); - con.start(); - TextMessage tm = (TextMessage) consumer.receive(1000L); - - assertTrue("No message routed to receiver", tm != null); - assertTrue("Wrong message routed to receiver: " + tm.getText(), "msg1".equals(tm.getText())); - - try - { - Thread.sleep(1000L); - } - catch (InterruptedException e) - { - ; - } - - assertEquals("Wrong number of messages bounced: ", 1, _bouncedMessageList.size()); - Message m = _bouncedMessageList.get(0); - assertTrue("Wrong message bounced: " + m.toString(), m.toString().contains("msg2")); - - - con.close(); - con2.close(); - } - - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(ReturnUnroutableMandatoryMessageTest.class); - } - - public void onException(JMSException jmsException) - { - - Exception linkedException = null; - try - { - linkedException = jmsException.getLinkedException(); - } catch (Exception e) - { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - if (linkedException instanceof AMQNoRouteException) - { - AMQNoRouteException noRoute = (AMQNoRouteException) linkedException; - Message bounced = (Message) noRoute.getUndeliveredMessage(); - _bouncedMessageList.add(bounced); - _logger.info("Caught expected NoRouteException"); - } - else - { - _logger.warn("Caught exception on producer: ", jmsException); - } - } -} +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.qpid.server.exchange; + +import junit.framework.TestCase; +import org.apache.log4j.Logger; +import org.apache.qpid.server.registry.ApplicationRegistry; +import org.apache.qpid.server.util.NullApplicationRegistry; +import org.apache.qpid.client.*; +import org.apache.qpid.client.transport.TransportConnection; +import org.apache.qpid.url.AMQBindingURL; +import org.apache.qpid.url.BindingURL; +import org.apache.qpid.exchange.ExchangeDefaults; +import org.apache.qpid.framing.FieldTable; + +import javax.jms.*; +import java.util.List; +import java.util.Collections; +import java.util.ArrayList; + +public class ReturnUnroutableMandatoryMessageTest extends TestCase implements ExceptionListener +{ + private static final Logger _logger = Logger.getLogger(ReturnUnroutableMandatoryMessageTest.class); + + private final List _bouncedMessageList = Collections.synchronizedList(new ArrayList()); + private static final String VIRTUALHOST = "test"; + private static final String BROKER = "vm://:1"; + + static + { + String workdir = System.getProperty("QPID_WORK"); + if (workdir == null || workdir.equals("")) + { + String tempdir = System.getProperty("java.io.tmpdir"); + System.out.println("QPID_WORK not set using tmp directory: " + tempdir); + System.setProperty("QPID_WORK", tempdir); + } +// DOMConfigurator.configure("../broker/etc/log4j.xml"); + } + + protected void setUp() throws Exception + { + super.setUp(); + TransportConnection.createVMBroker(1); + ApplicationRegistry.initialise(new NullApplicationRegistry(), 1); + } + + protected void tearDown() throws Exception + { + super.tearDown(); + TransportConnection.killAllVMBrokers(); + } + + /** + * Tests that mandatory message which are not routable are returned to the producer + * + * @throws Exception + */ + public void testReturnUnroutableMandatoryMessage_HEADERS() throws Exception + { + _bouncedMessageList.clear(); + Connection con = new AMQConnection(BROKER, "guest", "guest", "consumer1", VIRTUALHOST); + + + AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + AMQHeadersExchange queue = new AMQHeadersExchange(new AMQBindingURL(ExchangeDefaults.HEADERS_EXCHANGE_CLASS + "://" + ExchangeDefaults.HEADERS_EXCHANGE_NAME + "/test/queue1?" + BindingURL.OPTION_ROUTING_KEY + "='F0000=1'")); + FieldTable ft = new FieldTable(); + ft.setString("F1000", "1"); + MessageConsumer consumer = consumerSession.createConsumer(queue, AMQSession.DEFAULT_PREFETCH_LOW_MARK, AMQSession.DEFAULT_PREFETCH_HIGH_MARK, false, false, (String) null, ft); + + //force synch to ensure the consumer has resulted in a bound queue + //((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.HEADERS_EXCHANGE_NAME, ExchangeDefaults.HEADERS_EXCHANGE_CLASS); + // This is the default now + + Connection con2 = new AMQConnection(BROKER, "guest", "guest", "producer1", VIRTUALHOST); + + con2.setExceptionListener(this); + AMQSession producerSession = (AMQSession) con2.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + // Need to start the "producer" connection in order to receive bounced messages + _logger.info("Starting producer connection"); + con2.start(); + + + MessageProducer nonMandatoryProducer = producerSession.createProducer(queue, false, false); + MessageProducer mandatoryProducer = producerSession.createProducer(queue); + + // First test - should neither be bounced nor routed + _logger.info("Sending non-routable non-mandatory message"); + TextMessage msg1 = producerSession.createTextMessage("msg1"); + nonMandatoryProducer.send(msg1); + + // Second test - should be bounced + _logger.info("Sending non-routable mandatory message"); + TextMessage msg2 = producerSession.createTextMessage("msg2"); + mandatoryProducer.send(msg2); + + // Third test - should be routed + _logger.info("Sending routable message"); + TextMessage msg3 = producerSession.createTextMessage("msg3"); + msg3.setStringProperty("F1000", "1"); + mandatoryProducer.send(msg3); + + + _logger.info("Starting consumer connection"); + con.start(); + TextMessage tm = (TextMessage) consumer.receive(1000L); + + assertTrue("No message routed to receiver", tm != null); + assertTrue("Wrong message routed to receiver: " + tm.getText(), "msg3".equals(tm.getText())); + + try + { + Thread.sleep(1000L); + } + catch (InterruptedException e) + { + ; + } + + assertTrue("Wrong number of messages bounced (expect 1): " + _bouncedMessageList.size(), _bouncedMessageList.size() == 1); + Message m = _bouncedMessageList.get(0); + assertTrue("Wrong message bounced: " + m.toString(), m.toString().contains("msg2")); + + + con.close(); + con2.close(); + + + } + + public void testReturnUnroutableMandatoryMessage_QUEUE() throws Exception + { + _bouncedMessageList.clear(); + Connection con = new AMQConnection(BROKER, "guest", "guest", "consumer1", VIRTUALHOST); + + + AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + AMQQueue valid_queue = new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_CLASS, "testReturnUnroutableMandatoryMessage_QUEUE"); + AMQQueue invalid_queue = new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_CLASS, "testReturnUnroutableMandatoryMessage_QUEUE_INVALID"); + MessageConsumer consumer = consumerSession.createConsumer(valid_queue); + + //force synch to ensure the consumer has resulted in a bound queue + //((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.HEADERS_EXCHANGE_NAME, ExchangeDefaults.HEADERS_EXCHANGE_CLASS); + // This is the default now + + Connection con2 = new AMQConnection(BROKER, "guest", "guest", "producer1", VIRTUALHOST); + + con2.setExceptionListener(this); + AMQSession producerSession = (AMQSession) con2.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + // Need to start the "producer" connection in order to receive bounced messages + _logger.info("Starting producer connection"); + con2.start(); + + + MessageProducer nonMandatoryProducer = producerSession.createProducer(valid_queue, false, false); + MessageProducer mandatoryProducer = producerSession.createProducer(invalid_queue); + + // First test - should be routed + _logger.info("Sending non-mandatory message"); + TextMessage msg1 = producerSession.createTextMessage("msg1"); + nonMandatoryProducer.send(msg1); + + // Second test - should be bounced + _logger.info("Sending non-routable mandatory message"); + TextMessage msg2 = producerSession.createTextMessage("msg2"); + mandatoryProducer.send(msg2); + + + _logger.info("Starting consumer connection"); + con.start(); + TextMessage tm = (TextMessage) consumer.receive(1000L); + + assertTrue("No message routed to receiver", tm != null); + assertTrue("Wrong message routed to receiver: " + tm.getText(), "msg1".equals(tm.getText())); + + try + { + Thread.sleep(1000L); + } + catch (InterruptedException e) + { + ; + } + + assertTrue("Wrong number of messages bounced (expect 1): " + _bouncedMessageList.size(), _bouncedMessageList.size() == 1); + Message m = _bouncedMessageList.get(0); + assertTrue("Wrong message bounced: " + m.toString(), m.toString().contains("msg2")); + + + con.close(); + con2.close(); + } + + + public void testReturnUnroutableMandatoryMessage_TOPIC() throws Exception + { + _bouncedMessageList.clear(); + Connection con = new AMQConnection(BROKER, "guest", "guest", "consumer1", VIRTUALHOST); + + + AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + AMQTopic valid_topic = new AMQTopic(ExchangeDefaults.TOPIC_EXCHANGE_CLASS, "test.Return.Unroutable.Mandatory.Message.TOPIC"); + AMQTopic invalid_topic = new AMQTopic(ExchangeDefaults.TOPIC_EXCHANGE_CLASS, "test.Return.Unroutable.Mandatory.Message.TOPIC.invalid"); + MessageConsumer consumer = consumerSession.createConsumer(valid_topic); + + //force synch to ensure the consumer has resulted in a bound queue + //((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.HEADERS_EXCHANGE_NAME, ExchangeDefaults.HEADERS_EXCHANGE_CLASS); + // This is the default now + + Connection con2 = new AMQConnection(BROKER, "guest", "guest", "producer1", VIRTUALHOST); + + con2.setExceptionListener(this); + AMQSession producerSession = (AMQSession) con2.createSession(false, Session.CLIENT_ACKNOWLEDGE); + + // Need to start the "producer" connection in order to receive bounced messages + _logger.info("Starting producer connection"); + con2.start(); + + + MessageProducer nonMandatoryProducer = producerSession.createProducer(valid_topic, false, false); + MessageProducer mandatoryProducer = producerSession.createProducer(invalid_topic); + + // First test - should be routed + _logger.info("Sending non-mandatory message"); + TextMessage msg1 = producerSession.createTextMessage("msg1"); + nonMandatoryProducer.send(msg1); + + // Second test - should be bounced + _logger.info("Sending non-routable mandatory message"); + TextMessage msg2 = producerSession.createTextMessage("msg2"); + mandatoryProducer.send(msg2); + + + _logger.info("Starting consumer connection"); + con.start(); + TextMessage tm = (TextMessage) consumer.receive(1000L); + + assertTrue("No message routed to receiver", tm != null); + assertTrue("Wrong message routed to receiver: " + tm.getText(), "msg1".equals(tm.getText())); + + try + { + Thread.sleep(1000L); + } + catch (InterruptedException e) + { + ; + } + + assertEquals("Wrong number of messages bounced: ", 1, _bouncedMessageList.size()); + Message m = _bouncedMessageList.get(0); + assertTrue("Wrong message bounced: " + m.toString(), m.toString().contains("msg2")); + + + con.close(); + con2.close(); + } + + + public static junit.framework.Test suite() + { + return new junit.framework.TestSuite(ReturnUnroutableMandatoryMessageTest.class); + } + + public void onException(JMSException jmsException) + { + + Exception linkedException = null; + try + { + linkedException = jmsException.getLinkedException(); + } catch (Exception e) + { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } + if (linkedException instanceof AMQNoRouteException) + { + AMQNoRouteException noRoute = (AMQNoRouteException) linkedException; + Message bounced = (Message) noRoute.getUndeliveredMessage(); + _bouncedMessageList.add(bounced); + _logger.info("Caught expected NoRouteException"); + } + else + { + _logger.warn("Caught exception on producer: ", jmsException); + } + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/AMQPPublisher.java b/java/systests/src/main/java/org/apache/qpid/test/framework/AMQPPublisher.java index 706d99ffe2..13465741bd 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/AMQPPublisher.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/AMQPPublisher.java @@ -1,54 +1,54 @@ -/* - * - * 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.framework; - -import org.apache.qpid.junit.extensions.util.ParsedProperties; - -/** - * An AMQPPublisher represents the status of the publishing side of a test circuit that exposes AMQP specific features. - * Its provides additional assertions not available through the plain JMS {@link Publisher} interface. - * - *

- *
CRC Card
Responsibilities - *
Provide assertion that the publishers received a no consumers error code on every message. - *
Provide assertion that the publishers received a no route error code on every message. - *
- */ -public interface AMQPPublisher extends Publisher -{ - /** - * Provides an assertion that the publisher got a no consumers exception on every message. - * - * @param testProps The test configuration properties. - * - * @return An assertion that the publisher got a no consumers exception on every message. - */ - Assertion noConsumersAssertion(ParsedProperties testProps); - - /** - * Provides an assertion that the publisher got a no rout exception on every message. - * - * @param testProps The test configuration properties. - * - * @return An assertion that the publisher got a no rout exception on every message. - */ - Assertion noRouteAssertion(ParsedProperties testProps); -} +/* + * + * 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.framework; + +import org.apache.qpid.junit.extensions.util.ParsedProperties; + +/** + * An AMQPPublisher represents the status of the publishing side of a test circuit that exposes AMQP specific features. + * Its provides additional assertions not available through the plain JMS {@link Publisher} interface. + * + *

+ *
CRC Card
Responsibilities + *
Provide assertion that the publishers received a no consumers error code on every message. + *
Provide assertion that the publishers received a no route error code on every message. + *
+ */ +public interface AMQPPublisher extends Publisher +{ + /** + * Provides an assertion that the publisher got a no consumers exception on every message. + * + * @param testProps The test configuration properties. + * + * @return An assertion that the publisher got a no consumers exception on every message. + */ + Assertion noConsumersAssertion(ParsedProperties testProps); + + /** + * Provides an assertion that the publisher got a no rout exception on every message. + * + * @param testProps The test configuration properties. + * + * @return An assertion that the publisher got a no rout exception on every message. + */ + Assertion noRouteAssertion(ParsedProperties testProps); +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/BrokerLifecycleAware.java b/java/systests/src/main/java/org/apache/qpid/test/framework/BrokerLifecycleAware.java index e8b7da2537..41614f92fc 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/BrokerLifecycleAware.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/BrokerLifecycleAware.java @@ -1,70 +1,70 @@ -/* - * - * 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.framework; - -/** - * BrokerLifecycleAware is an awareness interface implemented by test cases that can run control the life-cycle of - * the brokers on which they run. Its purpose is to expose additional instrumentation of brokers during testing, that - * enables tests to use an automated failure mechanism to simulate broker failures, and to re-start failed brokers. - * - *

- *
CRC Card
Responsibilities Collaborations - *
Indicate whether or not a test case is using an in-vm broker. - *
Track which in-vm broker is currently in use. - *
Accept setting of a failure mechanism. {@link CauseFailure}. - *
- * - * @todo Need to think about how to present the brokers through this interface. Thinking numbering the available - * brokers from 1 will do. Then can kill 1 and assume failing onto 2. Restart 1 and kill 2 and fail back onto - * 1 again? - */ -public interface BrokerLifecycleAware -{ - public void setInVmBrokers(); - - /** - * Indicates whether or not a test case is using in-vm brokers. - * - * @return true if the test is using in-vm brokers, false otherwise. - */ - public boolean usingInVmBroker(); - - /** - * Sets the currently live in-vm broker. - * - * @param i The currently live in-vm broker. - */ - public void setLiveBroker(int i); - - /** - * Reports the currently live in-vm broker. - * - * @return The currently live in-vm broker. - */ - public int getLiveBroker(); - - /** - * Accepts a failure mechanism. - * - * @param failureMechanism The failure mechanism. - */ - public void setFailureMechanism(CauseFailure failureMechanism); -} +/* + * + * 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.framework; + +/** + * BrokerLifecycleAware is an awareness interface implemented by test cases that can run control the life-cycle of + * the brokers on which they run. Its purpose is to expose additional instrumentation of brokers during testing, that + * enables tests to use an automated failure mechanism to simulate broker failures, and to re-start failed brokers. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
Indicate whether or not a test case is using an in-vm broker. + *
Track which in-vm broker is currently in use. + *
Accept setting of a failure mechanism. {@link CauseFailure}. + *
+ * + * @todo Need to think about how to present the brokers through this interface. Thinking numbering the available + * brokers from 1 will do. Then can kill 1 and assume failing onto 2. Restart 1 and kill 2 and fail back onto + * 1 again? + */ +public interface BrokerLifecycleAware +{ + public void setInVmBrokers(); + + /** + * Indicates whether or not a test case is using in-vm brokers. + * + * @return true if the test is using in-vm brokers, false otherwise. + */ + public boolean usingInVmBroker(); + + /** + * Sets the currently live in-vm broker. + * + * @param i The currently live in-vm broker. + */ + public void setLiveBroker(int i); + + /** + * Reports the currently live in-vm broker. + * + * @return The currently live in-vm broker. + */ + public int getLiveBroker(); + + /** + * Accepts a failure mechanism. + * + * @param failureMechanism The failure mechanism. + */ + public void setFailureMechanism(CauseFailure failureMechanism); +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailure.java b/java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailure.java index 8a5a9560a0..9bdd5a72c5 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailure.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailure.java @@ -1,42 +1,42 @@ -/* - * - * 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.framework; - -/** - * CauseFailure provides a method to cause a failure in a messaging broker, usually used in conjunction with fail-over - * or other failure mode testing. In some cases failures may be automated, for example by shutting down an in-vm broker, - * or by sending a special control signal to a broker over a network connection. In other cases, it may be preferable - * to ask a user interactively to cause a failure scenario, in which case an implementation may display a prompt or - * dialog box asking for notification once the failure has been caused. The purpose of this interface is to abstract - * the exact cause and nature of a failure out of failure test cases. - * - *

- *
CRC Card
Responsibilities - *
Cause messaging broker failure. - *
- */ -public interface CauseFailure -{ - /** - * Causes the active message broker to fail. - */ - void causeFailure(); -} +/* + * + * 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.framework; + +/** + * CauseFailure provides a method to cause a failure in a messaging broker, usually used in conjunction with fail-over + * or other failure mode testing. In some cases failures may be automated, for example by shutting down an in-vm broker, + * or by sending a special control signal to a broker over a network connection. In other cases, it may be preferable + * to ask a user interactively to cause a failure scenario, in which case an implementation may display a prompt or + * dialog box asking for notification once the failure has been caused. The purpose of this interface is to abstract + * the exact cause and nature of a failure out of failure test cases. + * + *

+ *
CRC Card
Responsibilities + *
Cause messaging broker failure. + *
+ */ +public interface CauseFailure +{ + /** + * Causes the active message broker to fail. + */ + void causeFailure(); +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailureUserPrompt.java b/java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailureUserPrompt.java index 6b96ade674..889df4ad07 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailureUserPrompt.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/CauseFailureUserPrompt.java @@ -1,65 +1,65 @@ -/* - * - * 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.framework; - -import org.apache.qpid.test.framework.CauseFailure; - -import java.io.IOException; - -/** - * Causes a message broker failure by interactively prompting the user to cause it. - * - *

- *
CRC Card
Responsibilities Collaborations - *
Cause messaging broker failure. - *
- */ -public class CauseFailureUserPrompt implements CauseFailure -{ - /** - * Causes the active message broker to fail. - */ - public void causeFailure() - { - waitForUser("Cause a broker failure now, then press Return."); - } - - /** - * Outputs a prompt to the console and waits for the user to press return. - * - * @param prompt The prompt to display on the console. - */ - private void waitForUser(String prompt) - { - System.out.println(prompt); - - try - { - System.in.read(); - } - catch (IOException e) - { - // Ignored. - } - - System.out.println("Continuing."); - } -} +/* + * + * 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.framework; + +import org.apache.qpid.test.framework.CauseFailure; + +import java.io.IOException; + +/** + * Causes a message broker failure by interactively prompting the user to cause it. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
Cause messaging broker failure. + *
+ */ +public class CauseFailureUserPrompt implements CauseFailure +{ + /** + * Causes the active message broker to fail. + */ + public void causeFailure() + { + waitForUser("Cause a broker failure now, then press Return."); + } + + /** + * Outputs a prompt to the console and waits for the user to press return. + * + * @param prompt The prompt to display on the console. + */ + private void waitForUser(String prompt) + { + System.out.println(prompt); + + try + { + System.in.read(); + } + catch (IOException e) + { + // Ignored. + } + + System.out.println("Continuing."); + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkTestContext.java b/java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkTestContext.java index e7268db8eb..9a4668e86f 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkTestContext.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkTestContext.java @@ -1,48 +1,48 @@ -/* - * - * 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.framework; - -/** - * A FrameworkTestContext provides context information to test code about the current test case being run; its name, its - * parameters. - * - *

- *
CRC Card
Responsibilities Collaborations - *
Provide the name of the current test case. - *
Provide the test parameters. - *
- */ -public interface FrameworkTestContext -{ - /** - * Reports the current test case name. - * - * @return The current test case name. - */ - TestCaseVector getTestCaseVector(); - - /** - * Reports the current test case parameters. - * - * @return The current test case parameters. - */ - MessagingTestConfigProperties getTestParameters(); -} +/* + * + * 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.framework; + +/** + * A FrameworkTestContext provides context information to test code about the current test case being run; its name, its + * parameters. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
Provide the name of the current test case. + *
Provide the test parameters. + *
+ */ +public interface FrameworkTestContext +{ + /** + * Reports the current test case name. + * + * @return The current test case name. + */ + TestCaseVector getTestCaseVector(); + + /** + * Reports the current test case parameters. + * + * @return The current test case parameters. + */ + MessagingTestConfigProperties getTestParameters(); +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/LocalAMQPCircuitFactory.java b/java/systests/src/main/java/org/apache/qpid/test/framework/LocalAMQPCircuitFactory.java index d1fcad9cc0..7fbef06265 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/LocalAMQPCircuitFactory.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/LocalAMQPCircuitFactory.java @@ -1,168 +1,168 @@ -/* - * - * 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.framework; - -import org.apache.log4j.Logger; - -import org.apache.qpid.client.AMQSession; -import org.apache.qpid.test.framework.localcircuit.LocalAMQPPublisherImpl; -import org.apache.qpid.test.framework.localcircuit.LocalPublisherImpl; - -import org.apache.qpid.junit.extensions.util.ParsedProperties; - -import javax.jms.*; - -/** - * LocalAMQPCircuitFactory is a test sequencer that creates test circuits with publishing and receiving ends rooted - * on the same JVM, allowing AMQP/Qpid specific options to be applied to the circuit. - * - *

- *
CRC Card
Responsibilities Collaborations - *
Provide a standard test procedure over a test circuit. - *
Construct test circuits appropriate to a tests context. - *
Construct test circuits the support AMQP specific options. - *
- */ -public class LocalAMQPCircuitFactory extends LocalCircuitFactory -{ - /** Used for debugging. */ - private static final Logger log = Logger.getLogger(LocalAMQPCircuitFactory.class); - - /** - * Builds a circuit end suitable for the publishing side of a test circuit, from standard test parameters. - * - * @param connection The connection to build the circuit end on. - * @param testProps The test parameters to configure the circuit end construction. - * @param uniqueId A unique number to being numbering destinations from, to make this circuit unique. - * - * @return A circuit end suitable for the publishing side of a test circuit. - * - * @throws javax.jms.JMSException Any underlying JMSExceptions are allowed to fall through and fail the creation. - */ - public CircuitEndBase createPublisherCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId) - throws JMSException - { - log.debug( - "public CircuitEndBase createPublisherCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId = " - + uniqueId + "): called"); - - // Cast the test properties into a typed interface for convenience. - MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProps); - - Session session = connection.createSession(props.getPublisherTransacted(), props.getAckMode()); - - Destination destination = - props.getPubsub() ? session.createTopic(props.getSendDestinationNameRoot() + "_" + uniqueId) - : session.createQueue(props.getSendDestinationNameRoot() + "_" + uniqueId); - - MessageProducer producer = - props.getPublisherProducerBind() - ? ((props.getImmediate() | props.getMandatory()) - ? ((AMQSession) session).createProducer(destination, props.getMandatory(), props.getImmediate()) - : session.createProducer(destination)) : null; - - MessageConsumer consumer = - props.getPublisherConsumerBind() - ? session.createConsumer(session.createQueue(props.getReceiveDestinationNameRoot() + "_" + uniqueId)) : null; - - MessageMonitor messageMonitor = new MessageMonitor(); - - if (consumer != null) - { - consumer.setMessageListener(messageMonitor); - } - - ExceptionMonitor exceptionMonitor = new ExceptionMonitor(); - connection.setExceptionListener(exceptionMonitor); - - if (!props.getPublisherConsumerActive() && (consumer != null)) - { - consumer.close(); - } - - return new CircuitEndBase(producer, consumer, session, messageMonitor, exceptionMonitor); - } - - /** - * Builds a circuit end suitable for the receiving side of a test circuit, from standard test parameters. - * - * @param connection The connection to build the circuit end on. - * @param testProps The test parameters to configure the circuit end construction. - * @param uniqueId A unique number to being numbering destinations from, to make this circuit unique. - * - * @return A circuit end suitable for the receiving side of a test circuit. - * - * @throws JMSException Any underlying JMSExceptions are allowed to fall through and fail the creation. - */ - public CircuitEndBase createReceiverCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId) - throws JMSException - { - log.debug( - "public CircuitEndBase createReceiverCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId = " - + uniqueId + "): called"); - - // Cast the test properties into a typed interface for convenience. - MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProps); - - Session session = connection.createSession(props.getPublisherTransacted(), props.getAckMode()); - - MessageProducer producer = - props.getReceiverProducerBind() - ? session.createProducer(session.createQueue(props.getReceiveDestinationNameRoot() + "_" + uniqueId)) : null; - - Destination destination = - props.getPubsub() ? session.createTopic(props.getSendDestinationNameRoot() + "_" + uniqueId) - : session.createQueue(props.getSendDestinationNameRoot() + "_" + uniqueId); - - MessageConsumer consumer = - props.getReceiverConsumerBind() - ? ((props.getDurableSubscription() && props.getPubsub()) - ? session.createDurableSubscriber((Topic) destination, "testsub") : session.createConsumer(destination)) - : null; - - MessageMonitor messageMonitor = new MessageMonitor(); - - if (consumer != null) - { - consumer.setMessageListener(messageMonitor); - } - - if (!props.getReceiverConsumerActive() && (consumer != null)) - { - consumer.close(); - } - - return new CircuitEndBase(producer, consumer, session, messageMonitor, null); - } - - /** - * Creates a local {@link Publisher} from a {@link CircuitEnd}. The publisher implementation provides AMQP - * specific assertion methods, for testing beyond JMS. - * - * @param publisherEnd The publishing circuit end. - * - * @return A {@link Receiver}. - */ - protected LocalPublisherImpl createPublisherFromCircuitEnd(CircuitEndBase publisherEnd) - { - return new LocalAMQPPublisherImpl(publisherEnd); - } -} +/* + * + * 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.framework; + +import org.apache.log4j.Logger; + +import org.apache.qpid.client.AMQSession; +import org.apache.qpid.test.framework.localcircuit.LocalAMQPPublisherImpl; +import org.apache.qpid.test.framework.localcircuit.LocalPublisherImpl; + +import org.apache.qpid.junit.extensions.util.ParsedProperties; + +import javax.jms.*; + +/** + * LocalAMQPCircuitFactory is a test sequencer that creates test circuits with publishing and receiving ends rooted + * on the same JVM, allowing AMQP/Qpid specific options to be applied to the circuit. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
Provide a standard test procedure over a test circuit. + *
Construct test circuits appropriate to a tests context. + *
Construct test circuits the support AMQP specific options. + *
+ */ +public class LocalAMQPCircuitFactory extends LocalCircuitFactory +{ + /** Used for debugging. */ + private static final Logger log = Logger.getLogger(LocalAMQPCircuitFactory.class); + + /** + * Builds a circuit end suitable for the publishing side of a test circuit, from standard test parameters. + * + * @param connection The connection to build the circuit end on. + * @param testProps The test parameters to configure the circuit end construction. + * @param uniqueId A unique number to being numbering destinations from, to make this circuit unique. + * + * @return A circuit end suitable for the publishing side of a test circuit. + * + * @throws javax.jms.JMSException Any underlying JMSExceptions are allowed to fall through and fail the creation. + */ + public CircuitEndBase createPublisherCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId) + throws JMSException + { + log.debug( + "public CircuitEndBase createPublisherCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId = " + + uniqueId + "): called"); + + // Cast the test properties into a typed interface for convenience. + MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProps); + + Session session = connection.createSession(props.getPublisherTransacted(), props.getAckMode()); + + Destination destination = + props.getPubsub() ? session.createTopic(props.getSendDestinationNameRoot() + "_" + uniqueId) + : session.createQueue(props.getSendDestinationNameRoot() + "_" + uniqueId); + + MessageProducer producer = + props.getPublisherProducerBind() + ? ((props.getImmediate() | props.getMandatory()) + ? ((AMQSession) session).createProducer(destination, props.getMandatory(), props.getImmediate()) + : session.createProducer(destination)) : null; + + MessageConsumer consumer = + props.getPublisherConsumerBind() + ? session.createConsumer(session.createQueue(props.getReceiveDestinationNameRoot() + "_" + uniqueId)) : null; + + MessageMonitor messageMonitor = new MessageMonitor(); + + if (consumer != null) + { + consumer.setMessageListener(messageMonitor); + } + + ExceptionMonitor exceptionMonitor = new ExceptionMonitor(); + connection.setExceptionListener(exceptionMonitor); + + if (!props.getPublisherConsumerActive() && (consumer != null)) + { + consumer.close(); + } + + return new CircuitEndBase(producer, consumer, session, messageMonitor, exceptionMonitor); + } + + /** + * Builds a circuit end suitable for the receiving side of a test circuit, from standard test parameters. + * + * @param connection The connection to build the circuit end on. + * @param testProps The test parameters to configure the circuit end construction. + * @param uniqueId A unique number to being numbering destinations from, to make this circuit unique. + * + * @return A circuit end suitable for the receiving side of a test circuit. + * + * @throws JMSException Any underlying JMSExceptions are allowed to fall through and fail the creation. + */ + public CircuitEndBase createReceiverCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId) + throws JMSException + { + log.debug( + "public CircuitEndBase createReceiverCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId = " + + uniqueId + "): called"); + + // Cast the test properties into a typed interface for convenience. + MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProps); + + Session session = connection.createSession(props.getPublisherTransacted(), props.getAckMode()); + + MessageProducer producer = + props.getReceiverProducerBind() + ? session.createProducer(session.createQueue(props.getReceiveDestinationNameRoot() + "_" + uniqueId)) : null; + + Destination destination = + props.getPubsub() ? session.createTopic(props.getSendDestinationNameRoot() + "_" + uniqueId) + : session.createQueue(props.getSendDestinationNameRoot() + "_" + uniqueId); + + MessageConsumer consumer = + props.getReceiverConsumerBind() + ? ((props.getDurableSubscription() && props.getPubsub()) + ? session.createDurableSubscriber((Topic) destination, "testsub") : session.createConsumer(destination)) + : null; + + MessageMonitor messageMonitor = new MessageMonitor(); + + if (consumer != null) + { + consumer.setMessageListener(messageMonitor); + } + + if (!props.getReceiverConsumerActive() && (consumer != null)) + { + consumer.close(); + } + + return new CircuitEndBase(producer, consumer, session, messageMonitor, null); + } + + /** + * Creates a local {@link Publisher} from a {@link CircuitEnd}. The publisher implementation provides AMQP + * specific assertion methods, for testing beyond JMS. + * + * @param publisherEnd The publishing circuit end. + * + * @return A {@link Receiver}. + */ + protected LocalPublisherImpl createPublisherFromCircuitEnd(CircuitEndBase publisherEnd) + { + return new LocalAMQPPublisherImpl(publisherEnd); + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/LocalCircuitFactory.java b/java/systests/src/main/java/org/apache/qpid/test/framework/LocalCircuitFactory.java index 38a924a4ee..68aad6ee47 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/LocalCircuitFactory.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/LocalCircuitFactory.java @@ -1,316 +1,316 @@ -/* - * - * 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.framework; - -import org.apache.log4j.Logger; - -import org.apache.qpid.test.framework.localcircuit.LocalCircuitImpl; -import org.apache.qpid.test.framework.localcircuit.LocalPublisherImpl; -import org.apache.qpid.test.framework.localcircuit.LocalReceiverImpl; -import org.apache.qpid.test.framework.sequencers.CircuitFactory; -import org.apache.qpid.util.ConversationFactory; - -import org.apache.qpid.junit.extensions.util.ParsedProperties; - -import javax.jms.*; - -import java.util.List; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicLong; - -/** - * LocalCircuitFactory is a circuit factory that creates test circuits with publishing and receiving ends rooted - * on the same JVM. The ends of the circuit are presented as {@link Publisher} and {@link Receiver} interfaces, which - * in turn provide methods to apply assertions to the circuit. The creation of the circuit ends, and the presentation - * of the ends as publisher/receiver interfaces, are designed to be overriden, so that circuits and assertions that - * use messaging features not available in JMS can be written. This provides an extension point for writing tests - * against proprietary features of JMS implementations. - * - *

- *
CRC Card
Responsibilities Collaborations - *
Provide a standard test procedure over a test circuit. - *
Construct test circuits appropriate to a tests context. - *
- */ -public class LocalCircuitFactory implements CircuitFactory -{ - /** Used for debugging. */ - private static final Logger log = Logger.getLogger(LocalCircuitFactory.class); - - /** Used to create unique destination names for each test. */ - protected static AtomicLong uniqueDestsId = new AtomicLong(); - - /** - * Holds a test coordinating conversation with the test clients. This should consist of assigning the test roles, - * begining the test and gathering the test reports from the participants. - * - * @param testCircuit The test circuit. - * @param assertions The list of assertions to apply to the test circuit. - * @param testProperties The test case definition. - */ - public void sequenceTest(Circuit testCircuit, List assertions, Properties testProperties) - { - FrameworkBaseCase.assertNoFailures(testCircuit.test(1, assertions)); - } - - /** - * Creates a test circuit for the test, configered by the test parameters specified. - * - * @param testProperties The test parameters. - * - * @return A test circuit. - */ - public Circuit createCircuit(ParsedProperties testProperties) - { - Circuit result; - - // Cast the test properties into a typed interface for convenience. - MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProperties); - - // Create a standard publisher/receivers test client pair on a shared connection, individual sessions. - try - { - // Get a unique offset to append to destination names to make them unique to the connection. - long uniqueId = uniqueDestsId.incrementAndGet(); - - // Set up the connection. - Connection connection = TestUtils.createConnection(testProperties); - - // Add the connection exception listener to assert on exception conditions with. - // ExceptionMonitor exceptionMonitor = new ExceptionMonitor(); - // connection.setExceptionListener(exceptionMonitor); - - // Set up the publisher. - CircuitEndBase publisherEnd = createPublisherCircuitEnd(connection, props, uniqueId); - - // Set up the receiver. - CircuitEndBase receiverEnd = createReceiverCircuitEnd(connection, props, uniqueId); - - // Start listening for incoming messages. - connection.start(); - - // Package everything up. - LocalPublisherImpl publisher = createPublisherFromCircuitEnd(publisherEnd); - LocalReceiverImpl receiver = createReceiverFromCircuitEnd(receiverEnd); - - result = new LocalCircuitImpl(testProperties, publisher, receiver, connection, publisher.getExceptionMonitor()); - } - catch (JMSException e) - { - throw new RuntimeException("Could not create publisher/receivers pair due to a JMSException.", e); - } - - return result; - } - - /** - * Creates a local {@link Receiver} from a {@link CircuitEnd}. Sub-classes may override this to provide more - * specialized receivers if necessary. - * - * @param receiverEnd The receiving circuit end. - * - * @return A {@link Receiver}. - */ - protected LocalReceiverImpl createReceiverFromCircuitEnd(CircuitEndBase receiverEnd) - { - return new LocalReceiverImpl(receiverEnd); - } - - /** - * Creates a local {@link Publisher} from a {@link CircuitEnd}. Sub-classes may override this to provide more - * specialized receivers if necessary. - * - * @param publisherEnd The publishing circuit end. - * - * @return A {@link Receiver}. - */ - protected LocalPublisherImpl createPublisherFromCircuitEnd(CircuitEndBase publisherEnd) - { - return new LocalPublisherImpl(publisherEnd); - } - - /** - * Builds a circuit end suitable for the publishing side of a test circuit, from standard test parameters. - * - * @param connection The connection to build the circuit end on. - * @param testProps The test parameters to configure the circuit end construction. - * @param uniqueId A unique number to being numbering destinations from, to make this circuit unique. - * - * @return A circuit end suitable for the publishing side of a test circuit. - * - * @throws JMSException Any underlying JMSExceptions are allowed to fall through and fail the creation. - */ - public CircuitEndBase createPublisherCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId) - throws JMSException - { - log.debug( - "public CircuitEndBase createPublisherCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId = " - + uniqueId + "): called"); - - // Cast the test properties into a typed interface for convenience. - MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProps); - - // Check that the test properties do not contain AMQP/Qpid specific settings, and fail if they do. - if (props.getImmediate() || props.getMandatory()) - { - throw new RuntimeException( - "Cannot create a pure JMS circuit as the test properties require AMQP specific options."); - } - - Session session = connection.createSession(props.getPublisherTransacted(), props.getAckMode()); - - Destination destination = - props.getPubsub() ? session.createTopic(props.getSendDestinationNameRoot() + "_" + uniqueId) - : session.createQueue(props.getSendDestinationNameRoot() + "_" + uniqueId); - - MessageProducer producer = props.getPublisherProducerBind() ? session.createProducer(destination) : null; - - MessageConsumer consumer = - props.getPublisherConsumerBind() - ? session.createConsumer(session.createQueue(props.getReceiveDestinationNameRoot() + "_" + uniqueId)) : null; - - MessageMonitor messageMonitor = new MessageMonitor(); - - if (consumer != null) - { - consumer.setMessageListener(messageMonitor); - } - - ExceptionMonitor exceptionMonitor = new ExceptionMonitor(); - connection.setExceptionListener(exceptionMonitor); - - if (!props.getPublisherConsumerActive() && (consumer != null)) - { - consumer.close(); - } - - return new CircuitEndBase(producer, consumer, session, messageMonitor, exceptionMonitor); - } - - /** - * Builds a circuit end suitable for the receiving side of a test circuit, from standard test parameters. - * - * @param connection The connection to build the circuit end on. - * @param testProps The test parameters to configure the circuit end construction. - * @param uniqueId A unique number to being numbering destinations from, to make this circuit unique. - * - * @return A circuit end suitable for the receiving side of a test circuit. - * - * @throws JMSException Any underlying JMSExceptions are allowed to fall through and fail the creation. - */ - public CircuitEndBase createReceiverCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId) - throws JMSException - { - log.debug( - "public CircuitEndBase createReceiverCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId = " - + uniqueId + "): called"); - - // Cast the test properties into a typed interface for convenience. - MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProps); - - // Check that the test properties do not contain AMQP/Qpid specific settings, and fail if they do. - if (props.getImmediate() || props.getMandatory()) - { - throw new RuntimeException( - "Cannot create a pure JMS circuit as the test properties require AMQP specific options."); - } - - Session session = connection.createSession(props.getPublisherTransacted(), props.getAckMode()); - - MessageProducer producer = - props.getReceiverProducerBind() - ? session.createProducer(session.createQueue(props.getReceiveDestinationNameRoot() + "_" + uniqueId)) : null; - - Destination destination = - props.getPubsub() ? session.createTopic(props.getSendDestinationNameRoot() + "_" + uniqueId) - : session.createQueue(props.getSendDestinationNameRoot() + "_" + uniqueId); - - MessageConsumer consumer = - props.getReceiverConsumerBind() - ? ((props.getDurableSubscription() && props.getPubsub()) - ? session.createDurableSubscriber((Topic) destination, "testsub") : session.createConsumer(destination)) - : null; - - MessageMonitor messageMonitor = new MessageMonitor(); - - if (consumer != null) - { - consumer.setMessageListener(messageMonitor); - } - - if (!props.getReceiverConsumerActive() && (consumer != null)) - { - consumer.close(); - } - - return new CircuitEndBase(producer, consumer, session, messageMonitor, null); - } - - /** - * Sets the sender test client to coordinate the test with. - * - * @param sender The contact details of the sending client in the test. - */ - public void setSender(TestClientDetails sender) - { - throw new RuntimeException("Not implemented."); - } - - /** - * Sets the receiving test client to coordinate the test with. - * - * @param receiver The contact details of the sending client in the test. - */ - public void setReceiver(TestClientDetails receiver) - { - throw new RuntimeException("Not implemented."); - } - - /** - * Supplies the sending test client. - * - * @return The sending test client. - */ - public TestClientDetails getSender() - { - throw new RuntimeException("Not implemented."); - } - - /** - * Supplies the receiving test client. - * - * @return The receiving test client. - */ - public List getReceivers() - { - throw new RuntimeException("Not implemented."); - } - - /** - * Accepts the conversation factory over which to hold the test coordinating conversation. - * - * @param conversationFactory The conversation factory to coordinate the test over. - */ - public void setConversationFactory(ConversationFactory conversationFactory) - { - throw new RuntimeException("Not implemented."); - } -} +/* + * + * 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.framework; + +import org.apache.log4j.Logger; + +import org.apache.qpid.test.framework.localcircuit.LocalCircuitImpl; +import org.apache.qpid.test.framework.localcircuit.LocalPublisherImpl; +import org.apache.qpid.test.framework.localcircuit.LocalReceiverImpl; +import org.apache.qpid.test.framework.sequencers.CircuitFactory; +import org.apache.qpid.util.ConversationFactory; + +import org.apache.qpid.junit.extensions.util.ParsedProperties; + +import javax.jms.*; + +import java.util.List; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicLong; + +/** + * LocalCircuitFactory is a circuit factory that creates test circuits with publishing and receiving ends rooted + * on the same JVM. The ends of the circuit are presented as {@link Publisher} and {@link Receiver} interfaces, which + * in turn provide methods to apply assertions to the circuit. The creation of the circuit ends, and the presentation + * of the ends as publisher/receiver interfaces, are designed to be overriden, so that circuits and assertions that + * use messaging features not available in JMS can be written. This provides an extension point for writing tests + * against proprietary features of JMS implementations. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
Provide a standard test procedure over a test circuit. + *
Construct test circuits appropriate to a tests context. + *
+ */ +public class LocalCircuitFactory implements CircuitFactory +{ + /** Used for debugging. */ + private static final Logger log = Logger.getLogger(LocalCircuitFactory.class); + + /** Used to create unique destination names for each test. */ + protected static AtomicLong uniqueDestsId = new AtomicLong(); + + /** + * Holds a test coordinating conversation with the test clients. This should consist of assigning the test roles, + * begining the test and gathering the test reports from the participants. + * + * @param testCircuit The test circuit. + * @param assertions The list of assertions to apply to the test circuit. + * @param testProperties The test case definition. + */ + public void sequenceTest(Circuit testCircuit, List assertions, Properties testProperties) + { + FrameworkBaseCase.assertNoFailures(testCircuit.test(1, assertions)); + } + + /** + * Creates a test circuit for the test, configered by the test parameters specified. + * + * @param testProperties The test parameters. + * + * @return A test circuit. + */ + public Circuit createCircuit(ParsedProperties testProperties) + { + Circuit result; + + // Cast the test properties into a typed interface for convenience. + MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProperties); + + // Create a standard publisher/receivers test client pair on a shared connection, individual sessions. + try + { + // Get a unique offset to append to destination names to make them unique to the connection. + long uniqueId = uniqueDestsId.incrementAndGet(); + + // Set up the connection. + Connection connection = TestUtils.createConnection(testProperties); + + // Add the connection exception listener to assert on exception conditions with. + // ExceptionMonitor exceptionMonitor = new ExceptionMonitor(); + // connection.setExceptionListener(exceptionMonitor); + + // Set up the publisher. + CircuitEndBase publisherEnd = createPublisherCircuitEnd(connection, props, uniqueId); + + // Set up the receiver. + CircuitEndBase receiverEnd = createReceiverCircuitEnd(connection, props, uniqueId); + + // Start listening for incoming messages. + connection.start(); + + // Package everything up. + LocalPublisherImpl publisher = createPublisherFromCircuitEnd(publisherEnd); + LocalReceiverImpl receiver = createReceiverFromCircuitEnd(receiverEnd); + + result = new LocalCircuitImpl(testProperties, publisher, receiver, connection, publisher.getExceptionMonitor()); + } + catch (JMSException e) + { + throw new RuntimeException("Could not create publisher/receivers pair due to a JMSException.", e); + } + + return result; + } + + /** + * Creates a local {@link Receiver} from a {@link CircuitEnd}. Sub-classes may override this to provide more + * specialized receivers if necessary. + * + * @param receiverEnd The receiving circuit end. + * + * @return A {@link Receiver}. + */ + protected LocalReceiverImpl createReceiverFromCircuitEnd(CircuitEndBase receiverEnd) + { + return new LocalReceiverImpl(receiverEnd); + } + + /** + * Creates a local {@link Publisher} from a {@link CircuitEnd}. Sub-classes may override this to provide more + * specialized receivers if necessary. + * + * @param publisherEnd The publishing circuit end. + * + * @return A {@link Receiver}. + */ + protected LocalPublisherImpl createPublisherFromCircuitEnd(CircuitEndBase publisherEnd) + { + return new LocalPublisherImpl(publisherEnd); + } + + /** + * Builds a circuit end suitable for the publishing side of a test circuit, from standard test parameters. + * + * @param connection The connection to build the circuit end on. + * @param testProps The test parameters to configure the circuit end construction. + * @param uniqueId A unique number to being numbering destinations from, to make this circuit unique. + * + * @return A circuit end suitable for the publishing side of a test circuit. + * + * @throws JMSException Any underlying JMSExceptions are allowed to fall through and fail the creation. + */ + public CircuitEndBase createPublisherCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId) + throws JMSException + { + log.debug( + "public CircuitEndBase createPublisherCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId = " + + uniqueId + "): called"); + + // Cast the test properties into a typed interface for convenience. + MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProps); + + // Check that the test properties do not contain AMQP/Qpid specific settings, and fail if they do. + if (props.getImmediate() || props.getMandatory()) + { + throw new RuntimeException( + "Cannot create a pure JMS circuit as the test properties require AMQP specific options."); + } + + Session session = connection.createSession(props.getPublisherTransacted(), props.getAckMode()); + + Destination destination = + props.getPubsub() ? session.createTopic(props.getSendDestinationNameRoot() + "_" + uniqueId) + : session.createQueue(props.getSendDestinationNameRoot() + "_" + uniqueId); + + MessageProducer producer = props.getPublisherProducerBind() ? session.createProducer(destination) : null; + + MessageConsumer consumer = + props.getPublisherConsumerBind() + ? session.createConsumer(session.createQueue(props.getReceiveDestinationNameRoot() + "_" + uniqueId)) : null; + + MessageMonitor messageMonitor = new MessageMonitor(); + + if (consumer != null) + { + consumer.setMessageListener(messageMonitor); + } + + ExceptionMonitor exceptionMonitor = new ExceptionMonitor(); + connection.setExceptionListener(exceptionMonitor); + + if (!props.getPublisherConsumerActive() && (consumer != null)) + { + consumer.close(); + } + + return new CircuitEndBase(producer, consumer, session, messageMonitor, exceptionMonitor); + } + + /** + * Builds a circuit end suitable for the receiving side of a test circuit, from standard test parameters. + * + * @param connection The connection to build the circuit end on. + * @param testProps The test parameters to configure the circuit end construction. + * @param uniqueId A unique number to being numbering destinations from, to make this circuit unique. + * + * @return A circuit end suitable for the receiving side of a test circuit. + * + * @throws JMSException Any underlying JMSExceptions are allowed to fall through and fail the creation. + */ + public CircuitEndBase createReceiverCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId) + throws JMSException + { + log.debug( + "public CircuitEndBase createReceiverCircuitEnd(Connection connection, ParsedProperties testProps, long uniqueId = " + + uniqueId + "): called"); + + // Cast the test properties into a typed interface for convenience. + MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProps); + + // Check that the test properties do not contain AMQP/Qpid specific settings, and fail if they do. + if (props.getImmediate() || props.getMandatory()) + { + throw new RuntimeException( + "Cannot create a pure JMS circuit as the test properties require AMQP specific options."); + } + + Session session = connection.createSession(props.getPublisherTransacted(), props.getAckMode()); + + MessageProducer producer = + props.getReceiverProducerBind() + ? session.createProducer(session.createQueue(props.getReceiveDestinationNameRoot() + "_" + uniqueId)) : null; + + Destination destination = + props.getPubsub() ? session.createTopic(props.getSendDestinationNameRoot() + "_" + uniqueId) + : session.createQueue(props.getSendDestinationNameRoot() + "_" + uniqueId); + + MessageConsumer consumer = + props.getReceiverConsumerBind() + ? ((props.getDurableSubscription() && props.getPubsub()) + ? session.createDurableSubscriber((Topic) destination, "testsub") : session.createConsumer(destination)) + : null; + + MessageMonitor messageMonitor = new MessageMonitor(); + + if (consumer != null) + { + consumer.setMessageListener(messageMonitor); + } + + if (!props.getReceiverConsumerActive() && (consumer != null)) + { + consumer.close(); + } + + return new CircuitEndBase(producer, consumer, session, messageMonitor, null); + } + + /** + * Sets the sender test client to coordinate the test with. + * + * @param sender The contact details of the sending client in the test. + */ + public void setSender(TestClientDetails sender) + { + throw new RuntimeException("Not implemented."); + } + + /** + * Sets the receiving test client to coordinate the test with. + * + * @param receiver The contact details of the sending client in the test. + */ + public void setReceiver(TestClientDetails receiver) + { + throw new RuntimeException("Not implemented."); + } + + /** + * Supplies the sending test client. + * + * @return The sending test client. + */ + public TestClientDetails getSender() + { + throw new RuntimeException("Not implemented."); + } + + /** + * Supplies the receiving test client. + * + * @return The receiving test client. + */ + public List getReceivers() + { + throw new RuntimeException("Not implemented."); + } + + /** + * Accepts the conversation factory over which to hold the test coordinating conversation. + * + * @param conversationFactory The conversation factory to coordinate the test over. + */ + public void setConversationFactory(ConversationFactory conversationFactory) + { + throw new RuntimeException("Not implemented."); + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/MessageIdentityVector.java b/java/systests/src/main/java/org/apache/qpid/test/framework/MessageIdentityVector.java index b672b9c3ce..397c4e9fbd 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/MessageIdentityVector.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/MessageIdentityVector.java @@ -1,167 +1,167 @@ -/* - * - * 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.framework; - -/** - * MessageIdentityVector provides a message identification scheme, that matches individual messages with test cases. - * Test messages are being sent by a number of test clients, sending messages over a set of routes, and being received - * by another set of test clients. Each test is itself, being run within a test cycle, of which there could be many. It - * is the job of the test coordinator to request and receive reports from the available test clients, on what has been - * sent, what has been received, and what errors may have occurred, and to reconcile this information against the - * assertions being applied by the test case. In order to be able to figure out which messages belong to which test, - * there needs to be an identification scheme, that the coordinator can use to correlate messages in senders and - * receiver reports. Every message sent in a test can be associated with this information. - * - *

- *
CRC Card
Responsibilities Collaborations - *
Identify a test case, a handling client id, a circuit end within the client, and a test cycle number. - *
- */ -public class MessageIdentityVector -{ - /** Holds the test case vector component of the message identity vector. */ - private TestCaseVector testCaseVector; - - /** The unique client id. */ - private String clientId; - - /** The unique circuit end number within the client id. */ - private int circuitEndId; - - /** - * Creates a new identity vector for test messages. - * - * @param testCase The name of the test case generating the messages. - * @param clientId The unique id of the client implementing a circuit end that is handling the messages. - * @param circuitEndId The unique id number of the circuit end within the client. - * @param testCycleNumber The cycle iteration number of the test case. - */ - public MessageIdentityVector(String testCase, String clientId, int circuitEndId, int testCycleNumber) - { - this.testCaseVector = new TestCaseVector(testCase, testCycleNumber); - this.clientId = clientId; - this.circuitEndId = circuitEndId; - } - - /** - * Reports the test case vector component of the message identity vector. - * - * @return The test case vector component of the message identity vector. - */ - public TestCaseVector getTestCaseVector() - { - return testCaseVector; - } - - /** - * Reports the name of the test case. - * - * @return The name of the test case. - */ - public String getTestCase() - { - return testCaseVector.getTestCase(); - } - - /** - * Reports the test iteration cycle number within the test case. - * - * @return The test iteration cycle number within the test case. - */ - public int getTestCycleNumber() - { - return testCaseVector.getTestCycleNumber(); - } - - /** - * Resports the client id. - * - * @return The client id. - */ - public String getClientId() - { - return clientId; - } - - /** - * Reports the circuit end number within the test client. - * - * @return The circuit end number within the test client. - */ - public int getCircuitEndId() - { - return circuitEndId; - } - - /** - * Compares this identity vector with another for equality. All fields must match. - * - * @param o The identity vector to compare with. - * - * @return true if the identity vector is identical to this one by all fields, false otherwise. - */ - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - - if ((o == null) || (getClass() != o.getClass())) - { - return false; - } - - MessageIdentityVector that = (MessageIdentityVector) o; - - if (circuitEndId != that.circuitEndId) - { - return false; - } - - if ((clientId != null) ? (!clientId.equals(that.clientId)) : (that.clientId != null)) - { - return false; - } - - if ((testCaseVector != null) ? (!testCaseVector.equals(that.testCaseVector)) : (that.testCaseVector != null)) - { - return false; - } - - return true; - } - - /** - * Computes a hash code for this identity vector based on all fields. - * - * @return A hash code for this identity vector based on all fields. - */ - public int hashCode() - { - int result; - result = ((testCaseVector != null) ? testCaseVector.hashCode() : 0); - result = (31 * result) + ((clientId != null) ? clientId.hashCode() : 0); - result = (31 * result) + circuitEndId; - - return result; - } -} +/* + * + * 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.framework; + +/** + * MessageIdentityVector provides a message identification scheme, that matches individual messages with test cases. + * Test messages are being sent by a number of test clients, sending messages over a set of routes, and being received + * by another set of test clients. Each test is itself, being run within a test cycle, of which there could be many. It + * is the job of the test coordinator to request and receive reports from the available test clients, on what has been + * sent, what has been received, and what errors may have occurred, and to reconcile this information against the + * assertions being applied by the test case. In order to be able to figure out which messages belong to which test, + * there needs to be an identification scheme, that the coordinator can use to correlate messages in senders and + * receiver reports. Every message sent in a test can be associated with this information. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
Identify a test case, a handling client id, a circuit end within the client, and a test cycle number. + *
+ */ +public class MessageIdentityVector +{ + /** Holds the test case vector component of the message identity vector. */ + private TestCaseVector testCaseVector; + + /** The unique client id. */ + private String clientId; + + /** The unique circuit end number within the client id. */ + private int circuitEndId; + + /** + * Creates a new identity vector for test messages. + * + * @param testCase The name of the test case generating the messages. + * @param clientId The unique id of the client implementing a circuit end that is handling the messages. + * @param circuitEndId The unique id number of the circuit end within the client. + * @param testCycleNumber The cycle iteration number of the test case. + */ + public MessageIdentityVector(String testCase, String clientId, int circuitEndId, int testCycleNumber) + { + this.testCaseVector = new TestCaseVector(testCase, testCycleNumber); + this.clientId = clientId; + this.circuitEndId = circuitEndId; + } + + /** + * Reports the test case vector component of the message identity vector. + * + * @return The test case vector component of the message identity vector. + */ + public TestCaseVector getTestCaseVector() + { + return testCaseVector; + } + + /** + * Reports the name of the test case. + * + * @return The name of the test case. + */ + public String getTestCase() + { + return testCaseVector.getTestCase(); + } + + /** + * Reports the test iteration cycle number within the test case. + * + * @return The test iteration cycle number within the test case. + */ + public int getTestCycleNumber() + { + return testCaseVector.getTestCycleNumber(); + } + + /** + * Resports the client id. + * + * @return The client id. + */ + public String getClientId() + { + return clientId; + } + + /** + * Reports the circuit end number within the test client. + * + * @return The circuit end number within the test client. + */ + public int getCircuitEndId() + { + return circuitEndId; + } + + /** + * Compares this identity vector with another for equality. All fields must match. + * + * @param o The identity vector to compare with. + * + * @return true if the identity vector is identical to this one by all fields, false otherwise. + */ + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + + if ((o == null) || (getClass() != o.getClass())) + { + return false; + } + + MessageIdentityVector that = (MessageIdentityVector) o; + + if (circuitEndId != that.circuitEndId) + { + return false; + } + + if ((clientId != null) ? (!clientId.equals(that.clientId)) : (that.clientId != null)) + { + return false; + } + + if ((testCaseVector != null) ? (!testCaseVector.equals(that.testCaseVector)) : (that.testCaseVector != null)) + { + return false; + } + + return true; + } + + /** + * Computes a hash code for this identity vector based on all fields. + * + * @return A hash code for this identity vector based on all fields. + */ + public int hashCode() + { + int result; + result = ((testCaseVector != null) ? testCaseVector.hashCode() : 0); + result = (31 * result) + ((clientId != null) ? clientId.hashCode() : 0); + result = (31 * result) + circuitEndId; + + return result; + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/NotApplicableAssertion.java b/java/systests/src/main/java/org/apache/qpid/test/framework/NotApplicableAssertion.java index 63c7fd61c3..2a20be12d6 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/NotApplicableAssertion.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/NotApplicableAssertion.java @@ -1,112 +1,112 @@ -/* - * - * 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.framework; - -import org.apache.log4j.Logger; - -import org.apache.qpid.junit.extensions.util.ParsedProperties; - -/** - * NotApplicableAssertion is a messaging assertion that can be used when an assertion requested by a test-case is not - * applicable to the testing scenario. For example an assertion may relate to AMQP functionality, but a test case may be - * being run over a non-AMQP JMS implementation, in which case the request to create the assertion may return this - * instead of the proper assertion. The test framework is configurable to quietly drop these assertions, log them - * as warnings to the console, or raise them as test failures. - * - *

- *
CRC Card
Responsibilities Collaborations - *
Quitely pass. - *
Log a warning. - *
Raise a test failure. - *
- */ -public class NotApplicableAssertion implements Assertion -{ - /** Used for logging to the console. */ - private static final Logger console = Logger.getLogger("CONSOLE." + NotApplicableAssertion.class.getName()); - - /** The possible behavioural modes of this assertion. */ - private enum Mode - { - /** Quietly ignore the assertion by passing. */ - Quiet, - - /** Ignore the assertion by passing but log a warning about it. */ - Warn, - - /** Fail the assertion. */ - Fail; - } - - /** The behavioural mode of the assertion. */ - private Mode mode; - - /** - * Creates an assertion that is driven by the value of the 'notApplicableAssertion' property of the test - * configuration. Its value should match one of 'quiet', 'warn' or 'fail' and if it does not it is automatically - * read as 'fail'. - * - * @param testProperties The test configuration properties. - */ - public NotApplicableAssertion(ParsedProperties testProperties) - { - // Cast the test properties into a typed interface for convenience. - MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProperties); - - String modeName = props.getNotApplicableAssertionMode(); - - if ("quiet".equals(modeName)) - { - mode = Mode.Quiet; - } - else if ("warn".equals(modeName)) - { - mode = Mode.Warn; - } - else - { - mode = Mode.Fail; - } - } - - /** - * Applies the assertion. - * - * @return true if the assertion passes, false if it fails. - */ - public boolean apply() - { - switch (mode) - { - case Quiet: - return true; - - case Warn: - console.warn("Warning: Not applicable assertion being ignored."); - - return true; - - case Fail: - default: - return false; - } - } -} +/* + * + * 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.framework; + +import org.apache.log4j.Logger; + +import org.apache.qpid.junit.extensions.util.ParsedProperties; + +/** + * NotApplicableAssertion is a messaging assertion that can be used when an assertion requested by a test-case is not + * applicable to the testing scenario. For example an assertion may relate to AMQP functionality, but a test case may be + * being run over a non-AMQP JMS implementation, in which case the request to create the assertion may return this + * instead of the proper assertion. The test framework is configurable to quietly drop these assertions, log them + * as warnings to the console, or raise them as test failures. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
Quitely pass. + *
Log a warning. + *
Raise a test failure. + *
+ */ +public class NotApplicableAssertion implements Assertion +{ + /** Used for logging to the console. */ + private static final Logger console = Logger.getLogger("CONSOLE." + NotApplicableAssertion.class.getName()); + + /** The possible behavioural modes of this assertion. */ + private enum Mode + { + /** Quietly ignore the assertion by passing. */ + Quiet, + + /** Ignore the assertion by passing but log a warning about it. */ + Warn, + + /** Fail the assertion. */ + Fail; + } + + /** The behavioural mode of the assertion. */ + private Mode mode; + + /** + * Creates an assertion that is driven by the value of the 'notApplicableAssertion' property of the test + * configuration. Its value should match one of 'quiet', 'warn' or 'fail' and if it does not it is automatically + * read as 'fail'. + * + * @param testProperties The test configuration properties. + */ + public NotApplicableAssertion(ParsedProperties testProperties) + { + // Cast the test properties into a typed interface for convenience. + MessagingTestConfigProperties props = new MessagingTestConfigProperties(testProperties); + + String modeName = props.getNotApplicableAssertionMode(); + + if ("quiet".equals(modeName)) + { + mode = Mode.Quiet; + } + else if ("warn".equals(modeName)) + { + mode = Mode.Warn; + } + else + { + mode = Mode.Fail; + } + } + + /** + * Applies the assertion. + * + * @return true if the assertion passes, false if it fails. + */ + public boolean apply() + { + switch (mode) + { + case Quiet: + return true; + + case Warn: + console.warn("Warning: Not applicable assertion being ignored."); + + return true; + + case Fail: + default: + return false; + } + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/TestCaseVector.java b/java/systests/src/main/java/org/apache/qpid/test/framework/TestCaseVector.java index 0518a827ba..ad1e70f6f7 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/TestCaseVector.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/TestCaseVector.java @@ -1,88 +1,88 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.test.framework; - -/** - *

- *
CRC Card
Responsibilities Collaborations - *
- *
- */ -public class TestCaseVector -{ - /** The test case name. */ - private String testCase; - - /** The test cycle number within the test case. */ - private int testCycleNumber; - - public TestCaseVector(String testCase, int testCycleNumber) - { - this.testCase = testCase; - this.testCycleNumber = testCycleNumber; - } - - public String getTestCase() - { - return testCase; - } - - public int getTestCycleNumber() - { - return testCycleNumber; - } - - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - - if ((o == null) || (getClass() != o.getClass())) - { - return false; - } - - TestCaseVector that = (TestCaseVector) o; - - if (testCycleNumber != that.testCycleNumber) - { - return false; - } - - if ((testCase != null) ? (!testCase.equals(that.testCase)) : (that.testCase != null)) - { - return false; - } - - return true; - } - - public int hashCode() - { - int result; - result = ((testCase != null) ? testCase.hashCode() : 0); - result = (31 * result) + testCycleNumber; - - return result; - } -} +/* + * + * 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.framework; + +/** + *

+ *
CRC Card
Responsibilities Collaborations + *
+ *
+ */ +public class TestCaseVector +{ + /** The test case name. */ + private String testCase; + + /** The test cycle number within the test case. */ + private int testCycleNumber; + + public TestCaseVector(String testCase, int testCycleNumber) + { + this.testCase = testCase; + this.testCycleNumber = testCycleNumber; + } + + public String getTestCase() + { + return testCase; + } + + public int getTestCycleNumber() + { + return testCycleNumber; + } + + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + + if ((o == null) || (getClass() != o.getClass())) + { + return false; + } + + TestCaseVector that = (TestCaseVector) o; + + if (testCycleNumber != that.testCycleNumber) + { + return false; + } + + if ((testCase != null) ? (!testCase.equals(that.testCase)) : (that.testCase != null)) + { + return false; + } + + return true; + } + + public int hashCode() + { + int result; + result = ((testCase != null) ? testCase.hashCode() : 0); + result = (31 * result) + testCycleNumber; + + return result; + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/TestClient.java b/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/TestClient.java index 1c138fe575..9eba36e1e9 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/TestClient.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/distributedtesting/TestClient.java @@ -1,497 +1,497 @@ -/* - * - * 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.framework.distributedtesting; - -import org.apache.log4j.Logger; -import org.apache.log4j.NDC; - -import org.apache.qpid.test.framework.MessagingTestConfigProperties; -import org.apache.qpid.test.framework.TestUtils; -import org.apache.qpid.test.framework.clocksynch.ClockSynchThread; -import org.apache.qpid.test.framework.clocksynch.UDPClockSynchronizer; -import org.apache.qpid.util.ReflectionUtils; -import org.apache.qpid.util.ReflectionUtilsException; - -import org.apache.qpid.junit.extensions.SleepThrottle; -import org.apache.qpid.junit.extensions.util.ParsedProperties; -import org.apache.qpid.junit.extensions.util.TestContextProperties; - -import javax.jms.*; - -import java.util.*; - -/** - * Implements a test client as described in the interop testing spec - * (http://cwiki.apache.org/confluence/display/qpid/Interop+Testing+Specification). A test client is an agent that - * reacts to control message sequences send by the test {@link Coordinator}. - * - *

- *
Messages Handled by TestClient
Message Action - *
Invite(compulsory) Reply with Enlist. - *
Invite(test case) Reply with Enlist if test case available. - *
AssignRole(test case) Reply with Accept Role if matches an enlisted test. Keep test parameters. - *
Start Send test messages defined by test parameters. Send report on messages sent. - *
Status Request Send report on messages received. - *
Terminate Terminate the test client. - *
ClockSynch Synch clock against the supplied UDP address. - *
- * - *

- *
CRC Card
Responsibilities Collaborations - *
Handle all incoming control messages. {@link TestClientControlledTest} - *
Configure and look up test cases by name. {@link TestClientControlledTest} - *
- */ -public class TestClient implements MessageListener -{ - /** Used for debugging. */ - private static final Logger log = Logger.getLogger(TestClient.class); - - /** Used for reporting to the console. */ - private static final Logger console = Logger.getLogger("CONSOLE"); - - /** Holds the default identifying name of the test client. */ - public static final String CLIENT_NAME = "java"; - - /** Holds the URL of the broker to run the tests on. */ - public static String brokerUrl; - - /** Holds the virtual host to run the tests on. If null, then the default virtual host is used. */ - public static String virtualHost; - - /** - * Holds the test context properties that provides the default test parameters, plus command line overrides. - * This is initialized with the default test parameters, to which command line overrides may be applied. - */ - public static ParsedProperties testContextProperties = - TestContextProperties.getInstance(MessagingTestConfigProperties.defaults); - - /** Holds all the test cases loaded from the classpath. */ - Map testCases = new HashMap(); - - /** Holds the test case currently being run by this client. */ - protected TestClientControlledTest currentTestCase; - - /** Holds the connection to the broker that the test is being coordinated on. */ - protected Connection connection; - - /** Holds the message producer to hold the test coordination over. */ - protected MessageProducer producer; - - /** Holds the JMS controlSession for the test coordination. */ - protected Session session; - - /** Holds the name of this client, with a default value. */ - protected String clientName = CLIENT_NAME; - - /** This flag indicates that the test client should attempt to join the currently running test case on start up. */ - protected boolean join; - - /** Holds the clock synchronizer for the test node. */ - ClockSynchThread clockSynchThread; - - /** - * Creates a new interop test client, listenting to the specified broker and virtual host, with the specified client - * identifying name. - * - * @param pBrokerUrl The url of the broker to connect to. - * @param pVirtualHost The virtual host to conect to. - * @param clientName The client name to use. - * @param join Flag to indicate that this client should attempt to join running tests. - */ - public TestClient(String pBrokerUrl, String pVirtualHost, String clientName, boolean join) - { - log.debug("public TestClient(String pBrokerUrl = " + pBrokerUrl + ", String pVirtualHost = " + pVirtualHost - + ", String clientName = " + clientName + ", boolean join = " + join + "): called"); - - // Retain the connection parameters. - brokerUrl = pBrokerUrl; - virtualHost = pVirtualHost; - this.clientName = clientName; - this.join = join; - } - - /** - * The entry point for the interop test coordinator. This client accepts the following command line arguments: - * - *

- *
-b The broker URL. Optional. - *
-h The virtual host. Optional. - *
-n The test client name. Optional. - *
name=value Trailing argument define name/value pairs. Added to system properties. Optional. - *
- * - * @param args The command line arguments. - */ - public static void main(String[] args) - { - log.debug("public static void main(String[] args = " + Arrays.toString(args) + "): called"); - console.info("Qpid Distributed Test Client."); - - // Override the default broker url to be localhost:5672. - testContextProperties.setProperty(MessagingTestConfigProperties.BROKER_PROPNAME, "tcp://localhost:5672"); - - // Use the command line parser to evaluate the command line with standard handling behaviour (print errors - // and usage then exist if there are errors). - // Any options and trailing name=value pairs are also injected into the test context properties object, - // to override any defaults that may have been set up. - ParsedProperties options = - new ParsedProperties(org.apache.qpid.junit.extensions.util.CommandLineParser.processCommandLine(args, - new org.apache.qpid.junit.extensions.util.CommandLineParser( - new String[][] - { - { "b", "The broker URL.", "broker", "false" }, - { "h", "The virtual host to use.", "virtual host", "false" }, - { "o", "The name of the directory to output test timings to.", "dir", "false" }, - { "n", "The name of the test client.", "name", "false" }, - { "j", "Join this test client to running test.", "false" } - }), testContextProperties)); - - // Extract the command line options. - String brokerUrl = options.getProperty("b"); - String virtualHost = options.getProperty("h"); - String clientName = options.getProperty("n"); - clientName = (clientName == null) ? CLIENT_NAME : clientName; - boolean join = options.getPropertyAsBoolean("j"); - - // To distinguish logging output set up an NDC on the client name. - NDC.push(clientName); - - // Create a test client and start it running. - TestClient client = new TestClient(brokerUrl, virtualHost, clientName, join); - - // Use a class path scanner to find all the interop test case implementations. - // Hard code the test classes till the classpath scanner is fixed. - Collection> testCaseClasses = - new ArrayList>(); - // ClasspathScanner.getMatches(TestClientControlledTest.class, "^TestCase.*", true); - testCaseClasses.addAll(loadTestCases("org.apache.qpid.interop.clienttestcases.TestCase1DummyRun", - "org.apache.qpid.interop.clienttestcases.TestCase2BasicP2P", - "org.apache.qpid.interop.clienttestcases.TestCase3BasicPubSub", - "org.apache.qpid.interop.clienttestcases.TestCase4P2PMessageSize", - "org.apache.qpid.interop.clienttestcases.TestCase5PubSubMessageSize", - "org.apache.qpid.test.framework.distributedcircuit.TestClientCircuitEnd")); - - try - { - client.start(testCaseClasses); - } - catch (Exception e) - { - log.error("The test client was unable to start.", e); - console.info(e.getMessage()); - System.exit(1); - } - } - - /** - * Parses a list of class names, and loads them if they are available on the class path. - * - * @param classNames The names of the classes to load. - * - * @return A list of the loaded test case classes. - */ - public static List> loadTestCases(String... classNames) - { - List> testCases = - new LinkedList>(); - - for (String className : classNames) - { - try - { - Class cls = ReflectionUtils.forName(className); - testCases.add((Class) cls); - } - catch (ReflectionUtilsException e) - { - // Ignore, class could not be found, so test not available. - console.warn("Requested class " + className + " cannot be found, ignoring it."); - } - catch (ClassCastException e) - { - // Ignore, class was not of correct type to be a test case. - console.warn("Requested class " + className + " is not an instance of TestClientControlledTest."); - } - } - - return testCases; - } - - /** - * Starts the interop test client running. This causes it to start listening for incoming test invites. - * - * @param testCaseClasses The classes of the available test cases. The test case names from these are used to - * matchin incoming test invites against. - * - * @throws JMSException Any underlying JMSExceptions are allowed to fall through. - */ - protected void start(Collection> testCaseClasses) throws JMSException - { - log.debug("protected void start(Collection> testCaseClasses = " - + testCaseClasses + "): called"); - - // Create all the test case implementations and index them by the test names. - for (Class nextClass : testCaseClasses) - { - try - { - TestClientControlledTest testCase = nextClass.newInstance(); - testCases.put(testCase.getName(), testCase); - } - catch (InstantiationException e) - { - log.warn("Could not instantiate test case class: " + nextClass.getName(), e); - // Ignored. - } - catch (IllegalAccessException e) - { - log.warn("Could not instantiate test case class due to illegal access: " + nextClass.getName(), e); - // Ignored. - } - } - - // Open a connection to communicate with the coordinator on. - connection = TestUtils.createConnection(testContextProperties); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Set this up to listen for control messages. - Topic privateControlTopic = session.createTopic("iop.control." + clientName); - MessageConsumer consumer = session.createConsumer(privateControlTopic); - consumer.setMessageListener(this); - - Topic controlTopic = session.createTopic("iop.control"); - MessageConsumer consumer2 = session.createConsumer(controlTopic); - consumer2.setMessageListener(this); - - // Create a producer to send replies with. - producer = session.createProducer(null); - - // If the join flag was set, then broadcast a join message to notify the coordinator that a new test client - // is available to join the current test case, if it supports it. This message may be ignored, or it may result - // in this test client receiving a test invite. - if (join) - { - Message joinMessage = session.createMessage(); - - joinMessage.setStringProperty("CONTROL_TYPE", "JOIN"); - joinMessage.setStringProperty("CLIENT_NAME", clientName); - joinMessage.setStringProperty("CLIENT_PRIVATE_CONTROL_KEY", "iop.control." + clientName); - producer.send(controlTopic, joinMessage); - } - - // Start listening for incoming control messages. - connection.start(); - } - - /** - * Handles all incoming control messages. - * - * @param message The incoming message. - */ - public void onMessage(Message message) - { - NDC.push(clientName); - log.debug("public void onMessage(Message message = " + message + "): called"); - - try - { - String controlType = message.getStringProperty("CONTROL_TYPE"); - String testName = message.getStringProperty("TEST_NAME"); - - log.debug("Received control of type '" + controlType + "' for the test '" + testName + "'"); - - // Check if the message is a test invite. - if ("INVITE".equals(controlType)) - { - // Flag used to indicate that an enlist should be sent. Only enlist to compulsory invites or invites - // for which test cases exist. - boolean enlist = false; - - if (testName != null) - { - log.debug("Got an invite to test: " + testName); - - // Check if the requested test case is available. - TestClientControlledTest testCase = testCases.get(testName); - - if (testCase != null) - { - log.debug("Found implementing class for test '" + testName + "', enlisting for it."); - - // Check if the test case will accept the invitation. - enlist = testCase.acceptInvite(message); - - log.debug("The test case " - + (enlist ? " accepted the invite, enlisting for it." - : " did not accept the invite, not enlisting.")); - - // Make the requested test case the current test case. - currentTestCase = testCase; - } - else - { - log.debug("Received an invite to the test '" + testName + "' but this test is not known."); - } - } - else - { - log.debug("Got a compulsory invite, enlisting for it."); - - enlist = true; - } - - if (enlist) - { - // Reply with the client name in an Enlist message. - Message enlistMessage = session.createMessage(); - enlistMessage.setStringProperty("CONTROL_TYPE", "ENLIST"); - enlistMessage.setStringProperty("CLIENT_NAME", clientName); - enlistMessage.setStringProperty("CLIENT_PRIVATE_CONTROL_KEY", "iop.control." + clientName); - enlistMessage.setJMSCorrelationID(message.getJMSCorrelationID()); - - log.debug("Sending enlist message '" + enlistMessage + "' to " + message.getJMSReplyTo()); - - producer.send(message.getJMSReplyTo(), enlistMessage); - } - else - { - // Reply with the client name in an Decline message. - Message enlistMessage = session.createMessage(); - enlistMessage.setStringProperty("CONTROL_TYPE", "DECLINE"); - enlistMessage.setStringProperty("CLIENT_NAME", clientName); - enlistMessage.setStringProperty("CLIENT_PRIVATE_CONTROL_KEY", "iop.control." + clientName); - enlistMessage.setJMSCorrelationID(message.getJMSCorrelationID()); - - log.debug("Sending decline message '" + enlistMessage + "' to " + message.getJMSReplyTo()); - - producer.send(message.getJMSReplyTo(), enlistMessage); - } - } - else if ("ASSIGN_ROLE".equals(controlType)) - { - // Assign the role to the current test case. - String roleName = message.getStringProperty("ROLE"); - - log.debug("Got a role assignment to role: " + roleName); - - TestClientControlledTest.Roles role = Enum.valueOf(TestClientControlledTest.Roles.class, roleName); - - currentTestCase.assignRole(role, message); - - // Reply by accepting the role in an Accept Role message. - Message acceptRoleMessage = session.createMessage(); - acceptRoleMessage.setStringProperty("CLIENT_NAME", clientName); - acceptRoleMessage.setStringProperty("CONTROL_TYPE", "ACCEPT_ROLE"); - acceptRoleMessage.setJMSCorrelationID(message.getJMSCorrelationID()); - - log.debug("Sending accept role message '" + acceptRoleMessage + "' to " + message.getJMSReplyTo()); - - producer.send(message.getJMSReplyTo(), acceptRoleMessage); - } - else if ("START".equals(controlType) || "STATUS_REQUEST".equals(controlType)) - { - if ("START".equals(controlType)) - { - log.debug("Got a start notification."); - - // Extract the number of test messages to send from the start notification. - int numMessages; - - try - { - numMessages = message.getIntProperty("MESSAGE_COUNT"); - } - catch (NumberFormatException e) - { - // If the number of messages is not specified, use the default of one. - numMessages = 1; - } - - // Start the current test case. - currentTestCase.start(numMessages); - } - else - { - log.debug("Got a status request."); - } - - // Generate the report from the test case and reply with it as a Report message. - Message reportMessage = currentTestCase.getReport(session); - reportMessage.setStringProperty("CLIENT_NAME", clientName); - reportMessage.setStringProperty("CONTROL_TYPE", "REPORT"); - reportMessage.setJMSCorrelationID(message.getJMSCorrelationID()); - - log.debug("Sending report message '" + reportMessage + "' to " + message.getJMSReplyTo()); - - producer.send(message.getJMSReplyTo(), reportMessage); - } - else if ("TERMINATE".equals(controlType)) - { - console.info("Received termination instruction from coordinator."); - - // Is a cleaner shutdown needed? - connection.close(); - System.exit(0); - } - else if ("CLOCK_SYNCH".equals(controlType)) - { - log.debug("Received clock synch command."); - String address = message.getStringProperty("ADDRESS"); - - log.debug("address = " + address); - - // Re-create (if necessary) and start the clock synch thread to synch the clock every ten seconds. - if (clockSynchThread != null) - { - clockSynchThread.terminate(); - } - - SleepThrottle throttle = new SleepThrottle(); - throttle.setRate(0.1f); - - clockSynchThread = new ClockSynchThread(new UDPClockSynchronizer(address), throttle); - clockSynchThread.start(); - } - else - { - // Log a warning about this but otherwise ignore it. - log.warn("Got an unknown control message, controlType = " + controlType + ", message = " + message); - } - } - catch (JMSException e) - { - // Log a warning about this, but otherwise ignore it. - log.warn("Got JMSException whilst handling message: " + message, e); - } - // Log any runtimes that fall through this message handler. These are fatal errors for the test client. - catch (RuntimeException e) - { - log.error("The test client message handler got an unhandled exception: ", e); - console.info("The message handler got an unhandled exception, terminating the test client."); - System.exit(1); - } - finally - { - NDC.pop(); - } - } -} +/* + * + * 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.framework.distributedtesting; + +import org.apache.log4j.Logger; +import org.apache.log4j.NDC; + +import org.apache.qpid.test.framework.MessagingTestConfigProperties; +import org.apache.qpid.test.framework.TestUtils; +import org.apache.qpid.test.framework.clocksynch.ClockSynchThread; +import org.apache.qpid.test.framework.clocksynch.UDPClockSynchronizer; +import org.apache.qpid.util.ReflectionUtils; +import org.apache.qpid.util.ReflectionUtilsException; + +import org.apache.qpid.junit.extensions.SleepThrottle; +import org.apache.qpid.junit.extensions.util.ParsedProperties; +import org.apache.qpid.junit.extensions.util.TestContextProperties; + +import javax.jms.*; + +import java.util.*; + +/** + * Implements a test client as described in the interop testing spec + * (http://cwiki.apache.org/confluence/display/qpid/Interop+Testing+Specification). A test client is an agent that + * reacts to control message sequences send by the test {@link Coordinator}. + * + *

+ *
Messages Handled by TestClient
Message Action + *
Invite(compulsory) Reply with Enlist. + *
Invite(test case) Reply with Enlist if test case available. + *
AssignRole(test case) Reply with Accept Role if matches an enlisted test. Keep test parameters. + *
Start Send test messages defined by test parameters. Send report on messages sent. + *
Status Request Send report on messages received. + *
Terminate Terminate the test client. + *
ClockSynch Synch clock against the supplied UDP address. + *
+ * + *

+ *
CRC Card
Responsibilities Collaborations + *
Handle all incoming control messages. {@link TestClientControlledTest} + *
Configure and look up test cases by name. {@link TestClientControlledTest} + *
+ */ +public class TestClient implements MessageListener +{ + /** Used for debugging. */ + private static final Logger log = Logger.getLogger(TestClient.class); + + /** Used for reporting to the console. */ + private static final Logger console = Logger.getLogger("CONSOLE"); + + /** Holds the default identifying name of the test client. */ + public static final String CLIENT_NAME = "java"; + + /** Holds the URL of the broker to run the tests on. */ + public static String brokerUrl; + + /** Holds the virtual host to run the tests on. If null, then the default virtual host is used. */ + public static String virtualHost; + + /** + * Holds the test context properties that provides the default test parameters, plus command line overrides. + * This is initialized with the default test parameters, to which command line overrides may be applied. + */ + public static ParsedProperties testContextProperties = + TestContextProperties.getInstance(MessagingTestConfigProperties.defaults); + + /** Holds all the test cases loaded from the classpath. */ + Map testCases = new HashMap(); + + /** Holds the test case currently being run by this client. */ + protected TestClientControlledTest currentTestCase; + + /** Holds the connection to the broker that the test is being coordinated on. */ + protected Connection connection; + + /** Holds the message producer to hold the test coordination over. */ + protected MessageProducer producer; + + /** Holds the JMS controlSession for the test coordination. */ + protected Session session; + + /** Holds the name of this client, with a default value. */ + protected String clientName = CLIENT_NAME; + + /** This flag indicates that the test client should attempt to join the currently running test case on start up. */ + protected boolean join; + + /** Holds the clock synchronizer for the test node. */ + ClockSynchThread clockSynchThread; + + /** + * Creates a new interop test client, listenting to the specified broker and virtual host, with the specified client + * identifying name. + * + * @param pBrokerUrl The url of the broker to connect to. + * @param pVirtualHost The virtual host to conect to. + * @param clientName The client name to use. + * @param join Flag to indicate that this client should attempt to join running tests. + */ + public TestClient(String pBrokerUrl, String pVirtualHost, String clientName, boolean join) + { + log.debug("public TestClient(String pBrokerUrl = " + pBrokerUrl + ", String pVirtualHost = " + pVirtualHost + + ", String clientName = " + clientName + ", boolean join = " + join + "): called"); + + // Retain the connection parameters. + brokerUrl = pBrokerUrl; + virtualHost = pVirtualHost; + this.clientName = clientName; + this.join = join; + } + + /** + * The entry point for the interop test coordinator. This client accepts the following command line arguments: + * + *

+ *
-b The broker URL. Optional. + *
-h The virtual host. Optional. + *
-n The test client name. Optional. + *
name=value Trailing argument define name/value pairs. Added to system properties. Optional. + *
+ * + * @param args The command line arguments. + */ + public static void main(String[] args) + { + log.debug("public static void main(String[] args = " + Arrays.toString(args) + "): called"); + console.info("Qpid Distributed Test Client."); + + // Override the default broker url to be localhost:5672. + testContextProperties.setProperty(MessagingTestConfigProperties.BROKER_PROPNAME, "tcp://localhost:5672"); + + // Use the command line parser to evaluate the command line with standard handling behaviour (print errors + // and usage then exist if there are errors). + // Any options and trailing name=value pairs are also injected into the test context properties object, + // to override any defaults that may have been set up. + ParsedProperties options = + new ParsedProperties(org.apache.qpid.junit.extensions.util.CommandLineParser.processCommandLine(args, + new org.apache.qpid.junit.extensions.util.CommandLineParser( + new String[][] + { + { "b", "The broker URL.", "broker", "false" }, + { "h", "The virtual host to use.", "virtual host", "false" }, + { "o", "The name of the directory to output test timings to.", "dir", "false" }, + { "n", "The name of the test client.", "name", "false" }, + { "j", "Join this test client to running test.", "false" } + }), testContextProperties)); + + // Extract the command line options. + String brokerUrl = options.getProperty("b"); + String virtualHost = options.getProperty("h"); + String clientName = options.getProperty("n"); + clientName = (clientName == null) ? CLIENT_NAME : clientName; + boolean join = options.getPropertyAsBoolean("j"); + + // To distinguish logging output set up an NDC on the client name. + NDC.push(clientName); + + // Create a test client and start it running. + TestClient client = new TestClient(brokerUrl, virtualHost, clientName, join); + + // Use a class path scanner to find all the interop test case implementations. + // Hard code the test classes till the classpath scanner is fixed. + Collection> testCaseClasses = + new ArrayList>(); + // ClasspathScanner.getMatches(TestClientControlledTest.class, "^TestCase.*", true); + testCaseClasses.addAll(loadTestCases("org.apache.qpid.interop.clienttestcases.TestCase1DummyRun", + "org.apache.qpid.interop.clienttestcases.TestCase2BasicP2P", + "org.apache.qpid.interop.clienttestcases.TestCase3BasicPubSub", + "org.apache.qpid.interop.clienttestcases.TestCase4P2PMessageSize", + "org.apache.qpid.interop.clienttestcases.TestCase5PubSubMessageSize", + "org.apache.qpid.test.framework.distributedcircuit.TestClientCircuitEnd")); + + try + { + client.start(testCaseClasses); + } + catch (Exception e) + { + log.error("The test client was unable to start.", e); + console.info(e.getMessage()); + System.exit(1); + } + } + + /** + * Parses a list of class names, and loads them if they are available on the class path. + * + * @param classNames The names of the classes to load. + * + * @return A list of the loaded test case classes. + */ + public static List> loadTestCases(String... classNames) + { + List> testCases = + new LinkedList>(); + + for (String className : classNames) + { + try + { + Class cls = ReflectionUtils.forName(className); + testCases.add((Class) cls); + } + catch (ReflectionUtilsException e) + { + // Ignore, class could not be found, so test not available. + console.warn("Requested class " + className + " cannot be found, ignoring it."); + } + catch (ClassCastException e) + { + // Ignore, class was not of correct type to be a test case. + console.warn("Requested class " + className + " is not an instance of TestClientControlledTest."); + } + } + + return testCases; + } + + /** + * Starts the interop test client running. This causes it to start listening for incoming test invites. + * + * @param testCaseClasses The classes of the available test cases. The test case names from these are used to + * matchin incoming test invites against. + * + * @throws JMSException Any underlying JMSExceptions are allowed to fall through. + */ + protected void start(Collection> testCaseClasses) throws JMSException + { + log.debug("protected void start(Collection> testCaseClasses = " + + testCaseClasses + "): called"); + + // Create all the test case implementations and index them by the test names. + for (Class nextClass : testCaseClasses) + { + try + { + TestClientControlledTest testCase = nextClass.newInstance(); + testCases.put(testCase.getName(), testCase); + } + catch (InstantiationException e) + { + log.warn("Could not instantiate test case class: " + nextClass.getName(), e); + // Ignored. + } + catch (IllegalAccessException e) + { + log.warn("Could not instantiate test case class due to illegal access: " + nextClass.getName(), e); + // Ignored. + } + } + + // Open a connection to communicate with the coordinator on. + connection = TestUtils.createConnection(testContextProperties); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + // Set this up to listen for control messages. + Topic privateControlTopic = session.createTopic("iop.control." + clientName); + MessageConsumer consumer = session.createConsumer(privateControlTopic); + consumer.setMessageListener(this); + + Topic controlTopic = session.createTopic("iop.control"); + MessageConsumer consumer2 = session.createConsumer(controlTopic); + consumer2.setMessageListener(this); + + // Create a producer to send replies with. + producer = session.createProducer(null); + + // If the join flag was set, then broadcast a join message to notify the coordinator that a new test client + // is available to join the current test case, if it supports it. This message may be ignored, or it may result + // in this test client receiving a test invite. + if (join) + { + Message joinMessage = session.createMessage(); + + joinMessage.setStringProperty("CONTROL_TYPE", "JOIN"); + joinMessage.setStringProperty("CLIENT_NAME", clientName); + joinMessage.setStringProperty("CLIENT_PRIVATE_CONTROL_KEY", "iop.control." + clientName); + producer.send(controlTopic, joinMessage); + } + + // Start listening for incoming control messages. + connection.start(); + } + + /** + * Handles all incoming control messages. + * + * @param message The incoming message. + */ + public void onMessage(Message message) + { + NDC.push(clientName); + log.debug("public void onMessage(Message message = " + message + "): called"); + + try + { + String controlType = message.getStringProperty("CONTROL_TYPE"); + String testName = message.getStringProperty("TEST_NAME"); + + log.debug("Received control of type '" + controlType + "' for the test '" + testName + "'"); + + // Check if the message is a test invite. + if ("INVITE".equals(controlType)) + { + // Flag used to indicate that an enlist should be sent. Only enlist to compulsory invites or invites + // for which test cases exist. + boolean enlist = false; + + if (testName != null) + { + log.debug("Got an invite to test: " + testName); + + // Check if the requested test case is available. + TestClientControlledTest testCase = testCases.get(testName); + + if (testCase != null) + { + log.debug("Found implementing class for test '" + testName + "', enlisting for it."); + + // Check if the test case will accept the invitation. + enlist = testCase.acceptInvite(message); + + log.debug("The test case " + + (enlist ? " accepted the invite, enlisting for it." + : " did not accept the invite, not enlisting.")); + + // Make the requested test case the current test case. + currentTestCase = testCase; + } + else + { + log.debug("Received an invite to the test '" + testName + "' but this test is not known."); + } + } + else + { + log.debug("Got a compulsory invite, enlisting for it."); + + enlist = true; + } + + if (enlist) + { + // Reply with the client name in an Enlist message. + Message enlistMessage = session.createMessage(); + enlistMessage.setStringProperty("CONTROL_TYPE", "ENLIST"); + enlistMessage.setStringProperty("CLIENT_NAME", clientName); + enlistMessage.setStringProperty("CLIENT_PRIVATE_CONTROL_KEY", "iop.control." + clientName); + enlistMessage.setJMSCorrelationID(message.getJMSCorrelationID()); + + log.debug("Sending enlist message '" + enlistMessage + "' to " + message.getJMSReplyTo()); + + producer.send(message.getJMSReplyTo(), enlistMessage); + } + else + { + // Reply with the client name in an Decline message. + Message enlistMessage = session.createMessage(); + enlistMessage.setStringProperty("CONTROL_TYPE", "DECLINE"); + enlistMessage.setStringProperty("CLIENT_NAME", clientName); + enlistMessage.setStringProperty("CLIENT_PRIVATE_CONTROL_KEY", "iop.control." + clientName); + enlistMessage.setJMSCorrelationID(message.getJMSCorrelationID()); + + log.debug("Sending decline message '" + enlistMessage + "' to " + message.getJMSReplyTo()); + + producer.send(message.getJMSReplyTo(), enlistMessage); + } + } + else if ("ASSIGN_ROLE".equals(controlType)) + { + // Assign the role to the current test case. + String roleName = message.getStringProperty("ROLE"); + + log.debug("Got a role assignment to role: " + roleName); + + TestClientControlledTest.Roles role = Enum.valueOf(TestClientControlledTest.Roles.class, roleName); + + currentTestCase.assignRole(role, message); + + // Reply by accepting the role in an Accept Role message. + Message acceptRoleMessage = session.createMessage(); + acceptRoleMessage.setStringProperty("CLIENT_NAME", clientName); + acceptRoleMessage.setStringProperty("CONTROL_TYPE", "ACCEPT_ROLE"); + acceptRoleMessage.setJMSCorrelationID(message.getJMSCorrelationID()); + + log.debug("Sending accept role message '" + acceptRoleMessage + "' to " + message.getJMSReplyTo()); + + producer.send(message.getJMSReplyTo(), acceptRoleMessage); + } + else if ("START".equals(controlType) || "STATUS_REQUEST".equals(controlType)) + { + if ("START".equals(controlType)) + { + log.debug("Got a start notification."); + + // Extract the number of test messages to send from the start notification. + int numMessages; + + try + { + numMessages = message.getIntProperty("MESSAGE_COUNT"); + } + catch (NumberFormatException e) + { + // If the number of messages is not specified, use the default of one. + numMessages = 1; + } + + // Start the current test case. + currentTestCase.start(numMessages); + } + else + { + log.debug("Got a status request."); + } + + // Generate the report from the test case and reply with it as a Report message. + Message reportMessage = currentTestCase.getReport(session); + reportMessage.setStringProperty("CLIENT_NAME", clientName); + reportMessage.setStringProperty("CONTROL_TYPE", "REPORT"); + reportMessage.setJMSCorrelationID(message.getJMSCorrelationID()); + + log.debug("Sending report message '" + reportMessage + "' to " + message.getJMSReplyTo()); + + producer.send(message.getJMSReplyTo(), reportMessage); + } + else if ("TERMINATE".equals(controlType)) + { + console.info("Received termination instruction from coordinator."); + + // Is a cleaner shutdown needed? + connection.close(); + System.exit(0); + } + else if ("CLOCK_SYNCH".equals(controlType)) + { + log.debug("Received clock synch command."); + String address = message.getStringProperty("ADDRESS"); + + log.debug("address = " + address); + + // Re-create (if necessary) and start the clock synch thread to synch the clock every ten seconds. + if (clockSynchThread != null) + { + clockSynchThread.terminate(); + } + + SleepThrottle throttle = new SleepThrottle(); + throttle.setRate(0.1f); + + clockSynchThread = new ClockSynchThread(new UDPClockSynchronizer(address), throttle); + clockSynchThread.start(); + } + else + { + // Log a warning about this but otherwise ignore it. + log.warn("Got an unknown control message, controlType = " + controlType + ", message = " + message); + } + } + catch (JMSException e) + { + // Log a warning about this, but otherwise ignore it. + log.warn("Got JMSException whilst handling message: " + message, e); + } + // Log any runtimes that fall through this message handler. These are fatal errors for the test client. + catch (RuntimeException e) + { + log.error("The test client message handler got an unhandled exception: ", e); + console.info("The message handler got an unhandled exception, terminating the test client."); + System.exit(1); + } + finally + { + NDC.pop(); + } + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalAMQPPublisherImpl.java b/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalAMQPPublisherImpl.java index 14ae108da8..4388c7fbd8 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalAMQPPublisherImpl.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/localcircuit/LocalAMQPPublisherImpl.java @@ -1,133 +1,133 @@ -/* - * - * 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.framework.localcircuit; - -import org.apache.qpid.client.AMQNoConsumersException; -import org.apache.qpid.client.AMQNoRouteException; -import org.apache.qpid.test.framework.*; - -import org.apache.qpid.junit.extensions.util.ParsedProperties; - -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; - -/** - * LocalAMQPPublisherImpl is an extension of {@link LocalPublisherImpl} that adds AMQP specific features. Specifically - * extra assertions for AMQP features not available through generic JMS. - * - *

- *
CRC Card
Responsibilities Collaborations - *
- *
- */ -public class LocalAMQPPublisherImpl extends LocalPublisherImpl implements AMQPPublisher -{ - /** - * Creates a circuit end point on the specified producer, consumer and controlSession. Monitors are also configured - * for messages and exceptions received by the circuit end. - * - * @param producer The message producer for the circuit end point. - * @param consumer The message consumer for the circuit end point. - * @param session The controlSession for the circuit end point. - * @param messageMonitor The monitor to notify of all messages received by the circuit end. - * @param exceptionMonitor The monitor to notify of all exceptions received by the circuit end. - */ - public LocalAMQPPublisherImpl(MessageProducer producer, MessageConsumer consumer, Session session, - MessageMonitor messageMonitor, ExceptionMonitor exceptionMonitor) - { - super(producer, consumer, session, messageMonitor, exceptionMonitor); - } - - /** - * Creates a circuit end point from the producer, consumer and controlSession in a circuit end base implementation. - * - * @param end The circuit end base implementation to take producers and consumers from. - */ - public LocalAMQPPublisherImpl(CircuitEndBase end) - { - super(end); - } - - /** - * Provides an assertion that the publisher got a no consumers exception on every message. - * - * @param testProps The test configuration properties. - * - * @return An assertion that the publisher got a no consumers exception on every message. - */ - public Assertion noConsumersAssertion(ParsedProperties testProps) - { - return new AssertionBase() - { - public boolean apply() - { - boolean passed = true; - ExceptionMonitor connectionExceptionMonitor = circuit.getConnectionExceptionMonitor(); - - if (!connectionExceptionMonitor.assertOneJMSExceptionWithLinkedCause(AMQNoConsumersException.class)) - { - passed = false; - - addError("Was expecting linked exception type " + AMQNoConsumersException.class.getName() - + " on the connection.\n"); - addError((connectionExceptionMonitor.size() > 0) - ? ("Actually got the following exceptions on the connection, " + connectionExceptionMonitor) - : "Got no exceptions on the connection."); - } - - return passed; - } - }; - } - - /** - * Provides an assertion that the publisher got a no rout exception on every message. - * - * @param testProps The test configuration properties. - * - * @return An assertion that the publisher got a no rout exception on every message. - */ - public Assertion noRouteAssertion(ParsedProperties testProps) - { - return new AssertionBase() - { - public boolean apply() - { - boolean passed = true; - ExceptionMonitor connectionExceptionMonitor = circuit.getConnectionExceptionMonitor(); - - if (!connectionExceptionMonitor.assertOneJMSExceptionWithLinkedCause(AMQNoRouteException.class)) - { - passed = false; - - addError("Was expecting linked exception type " + AMQNoRouteException.class.getName() - + " on the connection.\n"); - addError((connectionExceptionMonitor.size() > 0) - ? ("Actually got the following exceptions on the connection, " + connectionExceptionMonitor) - : "Got no exceptions on the connection."); - } - - return passed; - } - }; - } -} +/* + * + * 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.framework.localcircuit; + +import org.apache.qpid.client.AMQNoConsumersException; +import org.apache.qpid.client.AMQNoRouteException; +import org.apache.qpid.test.framework.*; + +import org.apache.qpid.junit.extensions.util.ParsedProperties; + +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Session; + +/** + * LocalAMQPPublisherImpl is an extension of {@link LocalPublisherImpl} that adds AMQP specific features. Specifically + * extra assertions for AMQP features not available through generic JMS. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
+ *
+ */ +public class LocalAMQPPublisherImpl extends LocalPublisherImpl implements AMQPPublisher +{ + /** + * Creates a circuit end point on the specified producer, consumer and controlSession. Monitors are also configured + * for messages and exceptions received by the circuit end. + * + * @param producer The message producer for the circuit end point. + * @param consumer The message consumer for the circuit end point. + * @param session The controlSession for the circuit end point. + * @param messageMonitor The monitor to notify of all messages received by the circuit end. + * @param exceptionMonitor The monitor to notify of all exceptions received by the circuit end. + */ + public LocalAMQPPublisherImpl(MessageProducer producer, MessageConsumer consumer, Session session, + MessageMonitor messageMonitor, ExceptionMonitor exceptionMonitor) + { + super(producer, consumer, session, messageMonitor, exceptionMonitor); + } + + /** + * Creates a circuit end point from the producer, consumer and controlSession in a circuit end base implementation. + * + * @param end The circuit end base implementation to take producers and consumers from. + */ + public LocalAMQPPublisherImpl(CircuitEndBase end) + { + super(end); + } + + /** + * Provides an assertion that the publisher got a no consumers exception on every message. + * + * @param testProps The test configuration properties. + * + * @return An assertion that the publisher got a no consumers exception on every message. + */ + public Assertion noConsumersAssertion(ParsedProperties testProps) + { + return new AssertionBase() + { + public boolean apply() + { + boolean passed = true; + ExceptionMonitor connectionExceptionMonitor = circuit.getConnectionExceptionMonitor(); + + if (!connectionExceptionMonitor.assertOneJMSExceptionWithLinkedCause(AMQNoConsumersException.class)) + { + passed = false; + + addError("Was expecting linked exception type " + AMQNoConsumersException.class.getName() + + " on the connection.\n"); + addError((connectionExceptionMonitor.size() > 0) + ? ("Actually got the following exceptions on the connection, " + connectionExceptionMonitor) + : "Got no exceptions on the connection."); + } + + return passed; + } + }; + } + + /** + * Provides an assertion that the publisher got a no rout exception on every message. + * + * @param testProps The test configuration properties. + * + * @return An assertion that the publisher got a no rout exception on every message. + */ + public Assertion noRouteAssertion(ParsedProperties testProps) + { + return new AssertionBase() + { + public boolean apply() + { + boolean passed = true; + ExceptionMonitor connectionExceptionMonitor = circuit.getConnectionExceptionMonitor(); + + if (!connectionExceptionMonitor.assertOneJMSExceptionWithLinkedCause(AMQNoRouteException.class)) + { + passed = false; + + addError("Was expecting linked exception type " + AMQNoRouteException.class.getName() + + " on the connection.\n"); + addError((connectionExceptionMonitor.size() > 0) + ? ("Actually got the following exceptions on the connection, " + connectionExceptionMonitor) + : "Got no exceptions on the connection."); + } + + return passed; + } + }; + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/AMQPFeatureDecorator.java b/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/AMQPFeatureDecorator.java index 4545e3c164..c11f75e742 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/AMQPFeatureDecorator.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/AMQPFeatureDecorator.java @@ -1,96 +1,96 @@ -/* - * - * 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.framework.qpid; - -import junit.framework.Test; -import junit.framework.TestResult; - -import org.apache.qpid.test.framework.FrameworkBaseCase; -import org.apache.qpid.test.framework.LocalAMQPCircuitFactory; - -import org.apache.qpid.junit.extensions.WrappedSuiteTestDecorator; - -/** - * AMQPFeatureDecorator applies decorations to {@link FrameworkBaseCase} tests, so that they may use Qpid/AMQP specific - * features, not available through JMS. For example, the immediate and mandatory flags. This decorator replaces the - * standard test circuit factory on the base class with one that allows these features to be used. - * - *

- *
CRC Card
Responsibilities Collaborations - *
Substitute the circuit factory with an AMQP/Qpid specific one. - *
- * - * @todo This wrapper substitutes in a LocalAMQPCircuitFactory, which is fine for local tests. For distributed tests - * the Fanout or Interop factories are substituted in by their decorators instead. These actually use - * distributed circuit static create methods to build the circuits, which should actually be changed to a factory, - * so that static methods do not need to be used. The distributed circuit creater delegates the circuit - * construction to remote test nodes. This decorator should not be used with distributed tests, or should be made - * aware of them, in which case it might ensure that an AMQP feature (implied already by other properties) flag - * is passed out to the remote test nodes, and provide a mechansim for them to decorate their circuit creation - * with AMQP features too. Add factory substituion/decoration mechansim for test clients, here or in a seperate - * class. - */ -public class AMQPFeatureDecorator extends WrappedSuiteTestDecorator -{ - /** The test suite to run. */ - private Test test; - - /** - * Creates a wrapped test test decorator from another one. - * - * @param test The test test. - */ - public AMQPFeatureDecorator(WrappedSuiteTestDecorator test) - { - super(test); - this.test = test; - } - - /** - * Runs the tests with a LocalAMQPCircuitFactory. Only tests that extend FrameworkBaseCase are decorated. - * - * @param testResult The the results object to monitor the test results with. - */ - public void run(TestResult testResult) - { - for (Test test : getAllUnderlyingTests()) - { - if (test instanceof FrameworkBaseCase) - { - FrameworkBaseCase frameworkTest = (FrameworkBaseCase) test; - frameworkTest.setCircuitFactory(new LocalAMQPCircuitFactory()); - } - } - - // Run the test. - test.run(testResult); - } - - /** - * Prints the name of the test for debugging purposes. - * - * @return The name of the test. - */ - public String toString() - { - return "AMQPFeatureDecorator: [test = \"" + test + "\"]"; - } -} +/* + * + * 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.framework.qpid; + +import junit.framework.Test; +import junit.framework.TestResult; + +import org.apache.qpid.test.framework.FrameworkBaseCase; +import org.apache.qpid.test.framework.LocalAMQPCircuitFactory; + +import org.apache.qpid.junit.extensions.WrappedSuiteTestDecorator; + +/** + * AMQPFeatureDecorator applies decorations to {@link FrameworkBaseCase} tests, so that they may use Qpid/AMQP specific + * features, not available through JMS. For example, the immediate and mandatory flags. This decorator replaces the + * standard test circuit factory on the base class with one that allows these features to be used. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
Substitute the circuit factory with an AMQP/Qpid specific one. + *
+ * + * @todo This wrapper substitutes in a LocalAMQPCircuitFactory, which is fine for local tests. For distributed tests + * the Fanout or Interop factories are substituted in by their decorators instead. These actually use + * distributed circuit static create methods to build the circuits, which should actually be changed to a factory, + * so that static methods do not need to be used. The distributed circuit creater delegates the circuit + * construction to remote test nodes. This decorator should not be used with distributed tests, or should be made + * aware of them, in which case it might ensure that an AMQP feature (implied already by other properties) flag + * is passed out to the remote test nodes, and provide a mechansim for them to decorate their circuit creation + * with AMQP features too. Add factory substituion/decoration mechansim for test clients, here or in a seperate + * class. + */ +public class AMQPFeatureDecorator extends WrappedSuiteTestDecorator +{ + /** The test suite to run. */ + private Test test; + + /** + * Creates a wrapped test test decorator from another one. + * + * @param test The test test. + */ + public AMQPFeatureDecorator(WrappedSuiteTestDecorator test) + { + super(test); + this.test = test; + } + + /** + * Runs the tests with a LocalAMQPCircuitFactory. Only tests that extend FrameworkBaseCase are decorated. + * + * @param testResult The the results object to monitor the test results with. + */ + public void run(TestResult testResult) + { + for (Test test : getAllUnderlyingTests()) + { + if (test instanceof FrameworkBaseCase) + { + FrameworkBaseCase frameworkTest = (FrameworkBaseCase) test; + frameworkTest.setCircuitFactory(new LocalAMQPCircuitFactory()); + } + } + + // Run the test. + test.run(testResult); + } + + /** + * Prints the name of the test for debugging purposes. + * + * @return The name of the test. + */ + public String toString() + { + return "AMQPFeatureDecorator: [test = \"" + test + "\"]"; + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureDecorator.java b/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureDecorator.java index 3a048ac042..2708253d86 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureDecorator.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureDecorator.java @@ -1,95 +1,95 @@ -/* - * - * 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.framework.qpid; - -import junit.framework.Test; -import junit.framework.TestResult; - -import org.apache.qpid.test.framework.BrokerLifecycleAware; -import org.apache.qpid.test.framework.CauseFailureUserPrompt; - -import org.apache.qpid.junit.extensions.WrappedSuiteTestDecorator; - -/** - * CauseFailureDecorator applies decorations to {@link BrokerLifecycleAware} tests, so that they may use different failure - * mechanisms. It is capable of detecting when a test case uses in-vm brokers, and setting up an automatic failure - * for those tests, so that the current live broker can be shut-down by test cases. For external brokers, automatic - * failure could be implemented, for example by having a kill script. At the moment this sets up the failure to prompt - * a user interactively to cause a failure, using {@link CauseFailureUserPrompt}. - * - *

- *
CRC Card
Responsibilities Collaborations - *
Setup automatic failures for in-vm brokers. {@link CauseFailureInVM} - *
Setup user generated failures for external brokers. {@link CauseFailureUserPrompt}. - *
- *
- * - * @todo Slight problem in that CauseFailureInVM is Qpid specific, whereas CauseFailureUserPrompt is not. Would like the - * failure decorator to be non-qpid specific so that it can test failure of any JMS implementation too. Either pass - * in class name of failure mechanism, set it up in the in-vm decorator instead of here but with prompt user as the - * default for when the in-vm decorator is not used? - */ -public class CauseFailureDecorator extends WrappedSuiteTestDecorator -{ - /** The test suite to run. */ - private Test test; - - /** - * Creates a wrapped test test decorator from another one. - * - * @param test The test test. - */ - public CauseFailureDecorator(WrappedSuiteTestDecorator test) - { - super(test); - this.test = test; - } - - /** - * Runs the tests with a LocalAMQPCircuitFactory. Only tests that extend FrameworkBaseCase are decorated. - * - * @param testResult The the results object to monitor the test results with. - */ - public void run(TestResult testResult) - { - for (Test test : getAllUnderlyingTests()) - { - if (test instanceof BrokerLifecycleAware) - { - BrokerLifecycleAware failureTest = (BrokerLifecycleAware) test; - failureTest.setFailureMechanism(new CauseFailureUserPrompt()); - } - } - - // Run the test. - test.run(testResult); - } - - /** - * Prints the name of the test for debugging purposes. - * - * @return The name of the test. - */ - public String toString() - { - return "CauseFailureDecorator: [test = \"" + test + "\"]"; - } -} +/* + * + * 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.framework.qpid; + +import junit.framework.Test; +import junit.framework.TestResult; + +import org.apache.qpid.test.framework.BrokerLifecycleAware; +import org.apache.qpid.test.framework.CauseFailureUserPrompt; + +import org.apache.qpid.junit.extensions.WrappedSuiteTestDecorator; + +/** + * CauseFailureDecorator applies decorations to {@link BrokerLifecycleAware} tests, so that they may use different failure + * mechanisms. It is capable of detecting when a test case uses in-vm brokers, and setting up an automatic failure + * for those tests, so that the current live broker can be shut-down by test cases. For external brokers, automatic + * failure could be implemented, for example by having a kill script. At the moment this sets up the failure to prompt + * a user interactively to cause a failure, using {@link CauseFailureUserPrompt}. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
Setup automatic failures for in-vm brokers. {@link CauseFailureInVM} + *
Setup user generated failures for external brokers. {@link CauseFailureUserPrompt}. + *
+ *
+ * + * @todo Slight problem in that CauseFailureInVM is Qpid specific, whereas CauseFailureUserPrompt is not. Would like the + * failure decorator to be non-qpid specific so that it can test failure of any JMS implementation too. Either pass + * in class name of failure mechanism, set it up in the in-vm decorator instead of here but with prompt user as the + * default for when the in-vm decorator is not used? + */ +public class CauseFailureDecorator extends WrappedSuiteTestDecorator +{ + /** The test suite to run. */ + private Test test; + + /** + * Creates a wrapped test test decorator from another one. + * + * @param test The test test. + */ + public CauseFailureDecorator(WrappedSuiteTestDecorator test) + { + super(test); + this.test = test; + } + + /** + * Runs the tests with a LocalAMQPCircuitFactory. Only tests that extend FrameworkBaseCase are decorated. + * + * @param testResult The the results object to monitor the test results with. + */ + public void run(TestResult testResult) + { + for (Test test : getAllUnderlyingTests()) + { + if (test instanceof BrokerLifecycleAware) + { + BrokerLifecycleAware failureTest = (BrokerLifecycleAware) test; + failureTest.setFailureMechanism(new CauseFailureUserPrompt()); + } + } + + // Run the test. + test.run(testResult); + } + + /** + * Prints the name of the test for debugging purposes. + * + * @return The name of the test. + */ + public String toString() + { + return "CauseFailureDecorator: [test = \"" + test + "\"]"; + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureInVM.java b/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureInVM.java index b63ac43601..3e03ad0872 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureInVM.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/CauseFailureInVM.java @@ -1,70 +1,70 @@ -/* - * - * 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.framework.qpid; - -import org.apache.qpid.client.transport.TransportConnection; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.test.framework.CauseFailure; -import org.apache.qpid.test.framework.BrokerLifecycleAware; - -/** - *

- *
CRC Card
Responsibilities Collaborations - *
Cause messaging broker failure on the active in-vm broker. - * {@link TransportConnection}, {@link ApplicationRegistry} - *
- */ -public class CauseFailureInVM implements CauseFailure -{ - /** Holds the in-vm broker instrumented test case to create failures for. */ - private BrokerLifecycleAware inVMTest; - - /** - * Creates an automated failure mechanism for testing against in-vm brokers. The test to create the mechanism - * for is specified, and as this failure is for in-vm brokers, the test must be {@link org.apache.qpid.test.framework.BrokerLifecycleAware}. The test - * must also report that it is currently being run against an in-vm broker, and it is a runtime error if it is not, - * as the creator of this failure mechanism should already have checked that it is. - * - * @param inVMTest The test case to create an automated failure mechanism for. - */ - public CauseFailureInVM(BrokerLifecycleAware inVMTest) - { - // Check that the test is really using in-vm brokers. - if (!inVMTest.usingInVmBroker()) - { - throw new RuntimeException( - "Cannot create in-vm broker failure mechanism for a test that is not using in-vm brokers."); - } - - this.inVMTest = inVMTest; - } - - /** - * Causes the active message broker to fail. - */ - public void causeFailure() - { - int liveBroker = inVMTest.getLiveBroker(); - - TransportConnection.killVMBroker(liveBroker); - ApplicationRegistry.remove(liveBroker); - } -} +/* + * + * 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.framework.qpid; + +import org.apache.qpid.client.transport.TransportConnection; +import org.apache.qpid.server.registry.ApplicationRegistry; +import org.apache.qpid.test.framework.CauseFailure; +import org.apache.qpid.test.framework.BrokerLifecycleAware; + +/** + *

+ *
CRC Card
Responsibilities Collaborations + *
Cause messaging broker failure on the active in-vm broker. + * {@link TransportConnection}, {@link ApplicationRegistry} + *
+ */ +public class CauseFailureInVM implements CauseFailure +{ + /** Holds the in-vm broker instrumented test case to create failures for. */ + private BrokerLifecycleAware inVMTest; + + /** + * Creates an automated failure mechanism for testing against in-vm brokers. The test to create the mechanism + * for is specified, and as this failure is for in-vm brokers, the test must be {@link org.apache.qpid.test.framework.BrokerLifecycleAware}. The test + * must also report that it is currently being run against an in-vm broker, and it is a runtime error if it is not, + * as the creator of this failure mechanism should already have checked that it is. + * + * @param inVMTest The test case to create an automated failure mechanism for. + */ + public CauseFailureInVM(BrokerLifecycleAware inVMTest) + { + // Check that the test is really using in-vm brokers. + if (!inVMTest.usingInVmBroker()) + { + throw new RuntimeException( + "Cannot create in-vm broker failure mechanism for a test that is not using in-vm brokers."); + } + + this.inVMTest = inVMTest; + } + + /** + * Causes the active message broker to fail. + */ + public void causeFailure() + { + int liveBroker = inVMTest.getLiveBroker(); + + TransportConnection.killVMBroker(liveBroker); + ApplicationRegistry.remove(liveBroker); + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/InVMBrokerDecorator.java b/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/InVMBrokerDecorator.java index bcf052ea06..e0fddb10b7 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/InVMBrokerDecorator.java +++ b/java/systests/src/main/java/org/apache/qpid/test/framework/qpid/InVMBrokerDecorator.java @@ -1,135 +1,135 @@ -/* - * - * 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.framework.qpid; - -import junit.framework.Test; -import junit.framework.TestResult; - -import org.apache.qpid.client.transport.TransportConnection; -import org.apache.qpid.client.vmbroker.AMQVMBrokerCreationException; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.test.framework.BrokerLifecycleAware; -import org.apache.qpid.test.framework.FrameworkBaseCase; - -import org.apache.qpid.junit.extensions.SetupTaskAware; -import org.apache.qpid.junit.extensions.WrappedSuiteTestDecorator; - -/** - * InVMBrokerDecorator is a test decorator, that is activated when running tests against an in-vm broker only. Its - * purpose is to automatically create, and close and delete an in-vm broker, during the set-up and tear-down of - * each test case. This decorator may only be used in conjunction with tests that extend {@link FrameworkBaseCase}. - * - *

- *
CRC Card
Responsibilities Collaborations - *
Create/Destroy an in-vm broker on every test run. - *
- * - * @todo May need to add a more fine grained injection point for the in-vm broker management, as this acts at the - * suite level, rather than the individual test level. - * - * @todo Management of in-vm brokers for failure testing. Failure test setups may need to set their connection url to - * use multiple broker (vm://:1;vm://:2), with fail-over between them. There is round-robin fail-over, but also - * retry? A test case using an in-vm broker needs to record which one it is using, so that it can be - * killed/restarted. - */ -public class InVMBrokerDecorator extends WrappedSuiteTestDecorator -{ - /** The test suite to run. */ - private Test test; - - /** - * Creates a wrapped test suite decorator from another one. - * - * @param test The test suite. - */ - public InVMBrokerDecorator(WrappedSuiteTestDecorator test) - { - super(test); - this.test = test; - } - - /** - * Runs the tests with in-vm broker creation and clean-up added to the tests task stack. - * - * @param testResult The the results object to monitor the test results with. - */ - public void run(TestResult testResult) - { - for (Test test : getAllUnderlyingTests()) - { - // Check that the test to have an in-vm broker setup/teardown task added to it, is actually a framework - // test that can handle setup tasks. - if ((test instanceof SetupTaskAware)) - { - SetupTaskAware frameworkTest = (SetupTaskAware) test; - - frameworkTest.chainSetupTask(new Runnable() - { - public void run() - { - // Ensure that the in-vm broker is created. - try - { - TransportConnection.createVMBroker(1); - } - catch (AMQVMBrokerCreationException e) - { - throw new RuntimeException("In-VM broker creation failed: " + e.getMessage(), e); - } - } - }); - - frameworkTest.chainTearDownTask(new Runnable() - { - public void run() - { - // Ensure that the in-vm broker is cleaned up so that the next test starts afresh. - TransportConnection.killVMBroker(1); - ApplicationRegistry.remove(1); - } - }); - - // Check if the test is aware whether or not it can control the broker life cycle, and if so provide - // additional instrumentation for it to control the in-vm broker through. - if (test instanceof BrokerLifecycleAware) - { - BrokerLifecycleAware inVMTest = (BrokerLifecycleAware) test; - inVMTest.setInVmBrokers(); - inVMTest.setLiveBroker(1); - inVMTest.setFailureMechanism(new CauseFailureInVM(inVMTest)); - } - } - } - - // Run the test. - test.run(testResult); - } - - /** - * Prints the name of the test for debugging purposes. - * - * @return The name of the test. - */ - public String toString() - { - return "InVMBrokerDecorator: [test = " + test + "]"; - } -} +/* + * + * 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.framework.qpid; + +import junit.framework.Test; +import junit.framework.TestResult; + +import org.apache.qpid.client.transport.TransportConnection; +import org.apache.qpid.client.vmbroker.AMQVMBrokerCreationException; +import org.apache.qpid.server.registry.ApplicationRegistry; +import org.apache.qpid.test.framework.BrokerLifecycleAware; +import org.apache.qpid.test.framework.FrameworkBaseCase; + +import org.apache.qpid.junit.extensions.SetupTaskAware; +import org.apache.qpid.junit.extensions.WrappedSuiteTestDecorator; + +/** + * InVMBrokerDecorator is a test decorator, that is activated when running tests against an in-vm broker only. Its + * purpose is to automatically create, and close and delete an in-vm broker, during the set-up and tear-down of + * each test case. This decorator may only be used in conjunction with tests that extend {@link FrameworkBaseCase}. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
Create/Destroy an in-vm broker on every test run. + *
+ * + * @todo May need to add a more fine grained injection point for the in-vm broker management, as this acts at the + * suite level, rather than the individual test level. + * + * @todo Management of in-vm brokers for failure testing. Failure test setups may need to set their connection url to + * use multiple broker (vm://:1;vm://:2), with fail-over between them. There is round-robin fail-over, but also + * retry? A test case using an in-vm broker needs to record which one it is using, so that it can be + * killed/restarted. + */ +public class InVMBrokerDecorator extends WrappedSuiteTestDecorator +{ + /** The test suite to run. */ + private Test test; + + /** + * Creates a wrapped test suite decorator from another one. + * + * @param test The test suite. + */ + public InVMBrokerDecorator(WrappedSuiteTestDecorator test) + { + super(test); + this.test = test; + } + + /** + * Runs the tests with in-vm broker creation and clean-up added to the tests task stack. + * + * @param testResult The the results object to monitor the test results with. + */ + public void run(TestResult testResult) + { + for (Test test : getAllUnderlyingTests()) + { + // Check that the test to have an in-vm broker setup/teardown task added to it, is actually a framework + // test that can handle setup tasks. + if ((test instanceof SetupTaskAware)) + { + SetupTaskAware frameworkTest = (SetupTaskAware) test; + + frameworkTest.chainSetupTask(new Runnable() + { + public void run() + { + // Ensure that the in-vm broker is created. + try + { + TransportConnection.createVMBroker(1); + } + catch (AMQVMBrokerCreationException e) + { + throw new RuntimeException("In-VM broker creation failed: " + e.getMessage(), e); + } + } + }); + + frameworkTest.chainTearDownTask(new Runnable() + { + public void run() + { + // Ensure that the in-vm broker is cleaned up so that the next test starts afresh. + TransportConnection.killVMBroker(1); + ApplicationRegistry.remove(1); + } + }); + + // Check if the test is aware whether or not it can control the broker life cycle, and if so provide + // additional instrumentation for it to control the in-vm broker through. + if (test instanceof BrokerLifecycleAware) + { + BrokerLifecycleAware inVMTest = (BrokerLifecycleAware) test; + inVMTest.setInVmBrokers(); + inVMTest.setLiveBroker(1); + inVMTest.setFailureMechanism(new CauseFailureInVM(inVMTest)); + } + } + } + + // Run the test. + test.run(testResult); + } + + /** + * Prints the name of the test for debugging purposes. + * + * @return The name of the test. + */ + public String toString() + { + return "InVMBrokerDecorator: [test = " + test + "]"; + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/testcases/FailoverTest.java b/java/systests/src/main/java/org/apache/qpid/test/testcases/FailoverTest.java index e7d874ffa9..5f41a07949 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/testcases/FailoverTest.java +++ b/java/systests/src/main/java/org/apache/qpid/test/testcases/FailoverTest.java @@ -1,119 +1,119 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.test.testcases; - -import org.apache.qpid.test.framework.*; -import static org.apache.qpid.test.framework.MessagingTestConfigProperties.*; -import org.apache.qpid.test.framework.localcircuit.LocalCircuitImpl; -import org.apache.qpid.test.framework.sequencers.CircuitFactory; - -import javax.jms.JMSException; -import javax.jms.MessageProducer; -import javax.jms.Session; - -/** - * FailoverTest provides testing of fail-over over a local-circuit implementation. The circuit being tested may be - * against an in-vm broker or against an external broker, with the failure mechanism abstracted out of the test case. - * Automatic failures can be simulated against an in-vm broker. Currently the test must interact with the user to - * simulate failures on an external broker. - * - * Things to test: - * In tx, failure duing tx causes tx to error on subsequent sends/receives or commits/rollbacks. - * Outside of tx, reconnection allows msg flow to continue but there may be loss. - * - *

- *
CRC Card
Responsibilities Collaborations - *
- *
- * - * @todo This test is designed to be run over a local circuit only. For in-vm using automatic failures, for external - * brokers by prompting the user (or maybe using a script). Enforce the local-circuit only nature of the tests as - * well as thinking about how other local-circuit tests might be implemented. For example, could add a method - * to the framework base case for local only tests to call, that allows them access to the local-circuit - * implementation and so on. - * - * @todo More. Need to really expand the set of fail-over tests. - */ -public class FailoverTest extends FrameworkBaseCase -{ - /* Used for debugging purposes. */ - // private static final Logger log = Logger.getLogger(FailoverTest.class); - - /** - * Creates a new test case with the specified name. - * - * @param name The test case name. - */ - public FailoverTest(String name) - { - super(name); - } - - /** - * Checks that all messages sent within a transaction are receieved despite a fail-over occuring outside of - * the transaction. - * - * @throws JMSException Allowed to fall through and fail test. - */ - public void testTxP2PFailover() throws JMSException - { - // Set up the test properties to match the test cases requirements. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); - testProps.setProperty(ACK_MODE_PROPNAME, Session.AUTO_ACKNOWLEDGE); - testProps.setProperty(PUBSUB_PROPNAME, false); - - // MessagingTestConfigProperties props = this.getTestParameters(); - - // Create the test circuit from the test configuration parameters. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - // Create an assertion that all messages are received. - Assertion allMessagesReceived = testCircuit.getReceiver().allMessagesReceivedAssertion(testProps); - - // This test case assumes it is using a local circuit. - LocalCircuitImpl localCircuit = (LocalCircuitImpl) testCircuit; - - Session producerSession = localCircuit.getLocalPublisherCircuitEnd().getSession(); - MessageProducer producer = localCircuit.getLocalPublisherCircuitEnd().getProducer(); - // MessageConsumer consumer = localCircuit.getLocalReceiverCircuitEnd().getConsumer(); - - // Send some test messages. - for (int i = 0; i < 100; i++) - { - producer.send(TestUtils.createTestMessageOfSize(producerSession, 10)); - producerSession.commit(); - - // Cause a failover. - if (i == 50) - { - failureMechanism.causeFailure(); - } - - // Wait for the reconnection to complete. - } - - // Check that trying to send within the original transaction fails. - - // Check that all messages sent were received. - assertTrue("All messages sent were not received back again.", allMessagesReceived.apply()); - } -} +/* + * + * 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.testcases; + +import org.apache.qpid.test.framework.*; +import static org.apache.qpid.test.framework.MessagingTestConfigProperties.*; +import org.apache.qpid.test.framework.localcircuit.LocalCircuitImpl; +import org.apache.qpid.test.framework.sequencers.CircuitFactory; + +import javax.jms.JMSException; +import javax.jms.MessageProducer; +import javax.jms.Session; + +/** + * FailoverTest provides testing of fail-over over a local-circuit implementation. The circuit being tested may be + * against an in-vm broker or against an external broker, with the failure mechanism abstracted out of the test case. + * Automatic failures can be simulated against an in-vm broker. Currently the test must interact with the user to + * simulate failures on an external broker. + * + * Things to test: + * In tx, failure duing tx causes tx to error on subsequent sends/receives or commits/rollbacks. + * Outside of tx, reconnection allows msg flow to continue but there may be loss. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
+ *
+ * + * @todo This test is designed to be run over a local circuit only. For in-vm using automatic failures, for external + * brokers by prompting the user (or maybe using a script). Enforce the local-circuit only nature of the tests as + * well as thinking about how other local-circuit tests might be implemented. For example, could add a method + * to the framework base case for local only tests to call, that allows them access to the local-circuit + * implementation and so on. + * + * @todo More. Need to really expand the set of fail-over tests. + */ +public class FailoverTest extends FrameworkBaseCase +{ + /* Used for debugging purposes. */ + // private static final Logger log = Logger.getLogger(FailoverTest.class); + + /** + * Creates a new test case with the specified name. + * + * @param name The test case name. + */ + public FailoverTest(String name) + { + super(name); + } + + /** + * Checks that all messages sent within a transaction are receieved despite a fail-over occuring outside of + * the transaction. + * + * @throws JMSException Allowed to fall through and fail test. + */ + public void testTxP2PFailover() throws JMSException + { + // Set up the test properties to match the test cases requirements. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); + testProps.setProperty(ACK_MODE_PROPNAME, Session.AUTO_ACKNOWLEDGE); + testProps.setProperty(PUBSUB_PROPNAME, false); + + // MessagingTestConfigProperties props = this.getTestParameters(); + + // Create the test circuit from the test configuration parameters. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + // Create an assertion that all messages are received. + Assertion allMessagesReceived = testCircuit.getReceiver().allMessagesReceivedAssertion(testProps); + + // This test case assumes it is using a local circuit. + LocalCircuitImpl localCircuit = (LocalCircuitImpl) testCircuit; + + Session producerSession = localCircuit.getLocalPublisherCircuitEnd().getSession(); + MessageProducer producer = localCircuit.getLocalPublisherCircuitEnd().getProducer(); + // MessageConsumer consumer = localCircuit.getLocalReceiverCircuitEnd().getConsumer(); + + // Send some test messages. + for (int i = 0; i < 100; i++) + { + producer.send(TestUtils.createTestMessageOfSize(producerSession, 10)); + producerSession.commit(); + + // Cause a failover. + if (i == 50) + { + failureMechanism.causeFailure(); + } + + // Wait for the reconnection to complete. + } + + // Check that trying to send within the original transaction fails. + + // Check that all messages sent were received. + assertTrue("All messages sent were not received back again.", allMessagesReceived.apply()); + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/testcases/ImmediateMessageTest.java b/java/systests/src/main/java/org/apache/qpid/test/testcases/ImmediateMessageTest.java index 845c3ed9c8..767871e25a 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/testcases/ImmediateMessageTest.java +++ b/java/systests/src/main/java/org/apache/qpid/test/testcases/ImmediateMessageTest.java @@ -1,303 +1,303 @@ -/* - * - * 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.testcases; - -import org.apache.qpid.test.framework.AMQPPublisher; -import org.apache.qpid.test.framework.Circuit; -import org.apache.qpid.test.framework.FrameworkBaseCase; -import org.apache.qpid.test.framework.MessagingTestConfigProperties; -import static org.apache.qpid.test.framework.MessagingTestConfigProperties.*; -import org.apache.qpid.test.framework.sequencers.CircuitFactory; - -import org.apache.qpid.junit.extensions.util.TestContextProperties; - -/** - * ImmediateMessageTest tests for the desired behaviour of immediate messages. Immediate messages are a non-JMS - * feature. A message may be marked with an immediate delivery flag, which means that a consumer must be connected - * to receive the message, through a valid route, when it is sent, or when its transaction is committed in the case - * of transactional messaging. If this is not the case, the broker should return the message with a NO_CONSUMERS code. - * - *

- *
CRC Card
Responsibilities Collaborations - *
Check that an immediate message is sent succesfully not using transactions when a consumer is connected. - *
Check that an immediate message is committed succesfully in a transaction when a consumer is connected. - *
Check that an immediate message results in no consumers code, not using transactions, when a consumer is - * disconnected. - *
Check that an immediate message results in no consumers code, in a transaction, when a consumer is - * disconnected. - *
Check that an immediate message results in no route code, not using transactions, when no outgoing route is - * connected. - *
Check that an immediate message results in no route code, upon transaction commit, when no outgoing route is - * connected. - *
Check that an immediate message is sent succesfully not using transactions when a consumer is connected. - *
Check that an immediate message is committed succesfully in a transaction when a consumer is connected. - *
Check that an immediate message results in no consumers code, not using transactions, when a consumer is - * disconnected. - *
Check that an immediate message results in no consumers code, in a transaction, when a consumer is - * disconnected. - *
Check that an immediate message results in no route code, not using transactions, when no outgoing route is - * connected. - *
Check that an immediate message results in no route code, upon transaction commit, when no outgoing route is - * connected. - *
- * - * @todo All of these test cases will be generated by a test generator that thoroughly tests all combinations of test - * circuits. - */ -public class ImmediateMessageTest extends FrameworkBaseCase -{ - /** - * Creates a new test case with the specified name. - * - * @param name The test case name. - */ - public ImmediateMessageTest(String name) - { - super(name); - } - - /** Check that an immediate message is sent succesfully not using transactions when a consumer is connected. */ - public void test_QPID_517_ImmediateOkNoTxP2P() - { - // Ensure transactional sessions are off. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); - testProps.setProperty(PUBSUB_PROPNAME, false); - - // Run the default test sequence over the test circuit checking for no errors. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, assertionList(testCircuit.getPublisher().noExceptionsAssertion(testProps)))); - } - - /** Check that an immediate message is committed succesfully in a transaction when a consumer is connected. */ - public void test_QPID_517_ImmediateOkTxP2P() - { - // Ensure transactional sessions are off. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); - testProps.setProperty(PUBSUB_PROPNAME, false); - - // Send one message with no errors. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, assertionList(testCircuit.getPublisher().noExceptionsAssertion(testProps)))); - } - - /** Check that an immediate message results in no consumers code, not using transactions, when a consumer is disconnected. */ - public void test_QPID_517_ImmediateFailsConsumerDisconnectedNoTxP2P() - { - // Ensure transactional sessions are off. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); - testProps.setProperty(PUBSUB_PROPNAME, false); - - // Disconnect the consumer. - testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); - - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - // Send one message and get a linked no consumers exception. - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noConsumersAssertion(testProps)))); - } - - /** Check that an immediate message results in no consumers code, in a transaction, when a consumer is disconnected. */ - public void test_QPID_517_ImmediateFailsConsumerDisconnectedTxP2P() - { - // Ensure transactional sessions are on. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); - testProps.setProperty(PUBSUB_PROPNAME, false); - - // Disconnect the consumer. - testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); - - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - // Send one message and get a linked no consumers exception. - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noConsumersAssertion(testProps)))); - } - - /** Check that an immediate message results in no route code, not using transactions, when no outgoing route is connected. */ - public void test_QPID_517_ImmediateFailsNoRouteNoTxP2P() - { - // Ensure transactional sessions are off. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); - testProps.setProperty(PUBSUB_PROPNAME, false); - - // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to - // collect its messages). - testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); - - // Send one message and get a linked no route exception. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); - } - - /** Check that an immediate message results in no route code, upon transaction commit, when no outgoing route is connected. */ - public void test_QPID_517_ImmediateFailsNoRouteTxP2P() - { - // Ensure transactional sessions are on. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); - testProps.setProperty(PUBSUB_PROPNAME, false); - - // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to - // collect its messages). - testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); - - // Send one message and get a linked no route exception. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); - } - - /** Check that an immediate message is sent succesfully not using transactions when a consumer is connected. */ - public void test_QPID_517_ImmediateOkNoTxPubSub() - { - // Ensure transactional sessions are off. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); - testProps.setProperty(PUBSUB_PROPNAME, true); - - // Send one message with no errors. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); - } - - /** Check that an immediate message is committed succesfully in a transaction when a consumer is connected. */ - public void test_QPID_517_ImmediateOkTxPubSub() - { - // Ensure transactional sessions are off. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); - testProps.setProperty(PUBSUB_PROPNAME, true); - - // Send one message with no errors. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); - } - - /** Check that an immediate message results in no consumers code, not using transactions, when a consumer is disconnected. */ - public void test_QPID_517_ImmediateFailsConsumerDisconnectedNoTxPubSub() - { - // Ensure transactional sessions are off. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); - testProps.setProperty(PUBSUB_PROPNAME, true); - - // Use durable subscriptions, so that the route remains open with no subscribers. - testProps.setProperty(DURABLE_SUBSCRIPTION_PROPNAME, true); - - // Disconnect the consumer. - testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); - - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - // Send one message and get a linked no consumers exception. - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noConsumersAssertion(testProps)))); - } - - /** Check that an immediate message results in no consumers code, in a transaction, when a consumer is disconnected. */ - public void test_QPID_517_ImmediateFailsConsumerDisconnectedTxPubSub() - { - // Ensure transactional sessions are on. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); - testProps.setProperty(PUBSUB_PROPNAME, true); - - // Use durable subscriptions, so that the route remains open with no subscribers. - testProps.setProperty(DURABLE_SUBSCRIPTION_PROPNAME, true); - - // Disconnect the consumer. - testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); - - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - // Send one message and get a linked no consumers exception. - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noConsumersAssertion(testProps)))); - } - - /** Check that an immediate message results in no route code, not using transactions, when no outgoing route is connected. */ - public void test_QPID_517_ImmediateFailsNoRouteNoTxPubSub() - { - // Ensure transactional sessions are off. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); - testProps.setProperty(PUBSUB_PROPNAME, true); - - // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to - // collect its messages). - testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); - - // Send one message and get a linked no route exception. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); - } - - /** Check that an immediate message results in no route code, upon transaction commit, when no outgoing route is connected. */ - public void test_QPID_517_ImmediateFailsNoRouteTxPubSub() - { - // Ensure transactional sessions are on. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); - testProps.setProperty(PUBSUB_PROPNAME, true); - - // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to - // collect its messages). - testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); - - // Send one message and get a linked no route exception. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); - } - - protected void setUp() throws Exception - { - super.setUp(); - - testProps = TestContextProperties.getInstance(MessagingTestConfigProperties.defaults); - - /** All these tests should have the immediate flag on. */ - testProps.setProperty(IMMEDIATE_PROPNAME, true); - testProps.setProperty(MANDATORY_PROPNAME, false); - - /** Bind the receivers consumer by default. */ - testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, true); - testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, true); - } -} +/* + * + * 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.testcases; + +import org.apache.qpid.test.framework.AMQPPublisher; +import org.apache.qpid.test.framework.Circuit; +import org.apache.qpid.test.framework.FrameworkBaseCase; +import org.apache.qpid.test.framework.MessagingTestConfigProperties; +import static org.apache.qpid.test.framework.MessagingTestConfigProperties.*; +import org.apache.qpid.test.framework.sequencers.CircuitFactory; + +import org.apache.qpid.junit.extensions.util.TestContextProperties; + +/** + * ImmediateMessageTest tests for the desired behaviour of immediate messages. Immediate messages are a non-JMS + * feature. A message may be marked with an immediate delivery flag, which means that a consumer must be connected + * to receive the message, through a valid route, when it is sent, or when its transaction is committed in the case + * of transactional messaging. If this is not the case, the broker should return the message with a NO_CONSUMERS code. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
Check that an immediate message is sent succesfully not using transactions when a consumer is connected. + *
Check that an immediate message is committed succesfully in a transaction when a consumer is connected. + *
Check that an immediate message results in no consumers code, not using transactions, when a consumer is + * disconnected. + *
Check that an immediate message results in no consumers code, in a transaction, when a consumer is + * disconnected. + *
Check that an immediate message results in no route code, not using transactions, when no outgoing route is + * connected. + *
Check that an immediate message results in no route code, upon transaction commit, when no outgoing route is + * connected. + *
Check that an immediate message is sent succesfully not using transactions when a consumer is connected. + *
Check that an immediate message is committed succesfully in a transaction when a consumer is connected. + *
Check that an immediate message results in no consumers code, not using transactions, when a consumer is + * disconnected. + *
Check that an immediate message results in no consumers code, in a transaction, when a consumer is + * disconnected. + *
Check that an immediate message results in no route code, not using transactions, when no outgoing route is + * connected. + *
Check that an immediate message results in no route code, upon transaction commit, when no outgoing route is + * connected. + *
+ * + * @todo All of these test cases will be generated by a test generator that thoroughly tests all combinations of test + * circuits. + */ +public class ImmediateMessageTest extends FrameworkBaseCase +{ + /** + * Creates a new test case with the specified name. + * + * @param name The test case name. + */ + public ImmediateMessageTest(String name) + { + super(name); + } + + /** Check that an immediate message is sent succesfully not using transactions when a consumer is connected. */ + public void test_QPID_517_ImmediateOkNoTxP2P() + { + // Ensure transactional sessions are off. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); + testProps.setProperty(PUBSUB_PROPNAME, false); + + // Run the default test sequence over the test circuit checking for no errors. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, assertionList(testCircuit.getPublisher().noExceptionsAssertion(testProps)))); + } + + /** Check that an immediate message is committed succesfully in a transaction when a consumer is connected. */ + public void test_QPID_517_ImmediateOkTxP2P() + { + // Ensure transactional sessions are off. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); + testProps.setProperty(PUBSUB_PROPNAME, false); + + // Send one message with no errors. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, assertionList(testCircuit.getPublisher().noExceptionsAssertion(testProps)))); + } + + /** Check that an immediate message results in no consumers code, not using transactions, when a consumer is disconnected. */ + public void test_QPID_517_ImmediateFailsConsumerDisconnectedNoTxP2P() + { + // Ensure transactional sessions are off. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); + testProps.setProperty(PUBSUB_PROPNAME, false); + + // Disconnect the consumer. + testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); + + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + // Send one message and get a linked no consumers exception. + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noConsumersAssertion(testProps)))); + } + + /** Check that an immediate message results in no consumers code, in a transaction, when a consumer is disconnected. */ + public void test_QPID_517_ImmediateFailsConsumerDisconnectedTxP2P() + { + // Ensure transactional sessions are on. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); + testProps.setProperty(PUBSUB_PROPNAME, false); + + // Disconnect the consumer. + testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); + + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + // Send one message and get a linked no consumers exception. + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noConsumersAssertion(testProps)))); + } + + /** Check that an immediate message results in no route code, not using transactions, when no outgoing route is connected. */ + public void test_QPID_517_ImmediateFailsNoRouteNoTxP2P() + { + // Ensure transactional sessions are off. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); + testProps.setProperty(PUBSUB_PROPNAME, false); + + // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to + // collect its messages). + testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); + + // Send one message and get a linked no route exception. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); + } + + /** Check that an immediate message results in no route code, upon transaction commit, when no outgoing route is connected. */ + public void test_QPID_517_ImmediateFailsNoRouteTxP2P() + { + // Ensure transactional sessions are on. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); + testProps.setProperty(PUBSUB_PROPNAME, false); + + // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to + // collect its messages). + testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); + + // Send one message and get a linked no route exception. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); + } + + /** Check that an immediate message is sent succesfully not using transactions when a consumer is connected. */ + public void test_QPID_517_ImmediateOkNoTxPubSub() + { + // Ensure transactional sessions are off. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); + testProps.setProperty(PUBSUB_PROPNAME, true); + + // Send one message with no errors. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); + } + + /** Check that an immediate message is committed succesfully in a transaction when a consumer is connected. */ + public void test_QPID_517_ImmediateOkTxPubSub() + { + // Ensure transactional sessions are off. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); + testProps.setProperty(PUBSUB_PROPNAME, true); + + // Send one message with no errors. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); + } + + /** Check that an immediate message results in no consumers code, not using transactions, when a consumer is disconnected. */ + public void test_QPID_517_ImmediateFailsConsumerDisconnectedNoTxPubSub() + { + // Ensure transactional sessions are off. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); + testProps.setProperty(PUBSUB_PROPNAME, true); + + // Use durable subscriptions, so that the route remains open with no subscribers. + testProps.setProperty(DURABLE_SUBSCRIPTION_PROPNAME, true); + + // Disconnect the consumer. + testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); + + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + // Send one message and get a linked no consumers exception. + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noConsumersAssertion(testProps)))); + } + + /** Check that an immediate message results in no consumers code, in a transaction, when a consumer is disconnected. */ + public void test_QPID_517_ImmediateFailsConsumerDisconnectedTxPubSub() + { + // Ensure transactional sessions are on. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); + testProps.setProperty(PUBSUB_PROPNAME, true); + + // Use durable subscriptions, so that the route remains open with no subscribers. + testProps.setProperty(DURABLE_SUBSCRIPTION_PROPNAME, true); + + // Disconnect the consumer. + testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); + + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + // Send one message and get a linked no consumers exception. + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noConsumersAssertion(testProps)))); + } + + /** Check that an immediate message results in no route code, not using transactions, when no outgoing route is connected. */ + public void test_QPID_517_ImmediateFailsNoRouteNoTxPubSub() + { + // Ensure transactional sessions are off. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); + testProps.setProperty(PUBSUB_PROPNAME, true); + + // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to + // collect its messages). + testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); + + // Send one message and get a linked no route exception. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); + } + + /** Check that an immediate message results in no route code, upon transaction commit, when no outgoing route is connected. */ + public void test_QPID_517_ImmediateFailsNoRouteTxPubSub() + { + // Ensure transactional sessions are on. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); + testProps.setProperty(PUBSUB_PROPNAME, true); + + // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to + // collect its messages). + testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); + + // Send one message and get a linked no route exception. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); + } + + protected void setUp() throws Exception + { + super.setUp(); + + testProps = TestContextProperties.getInstance(MessagingTestConfigProperties.defaults); + + /** All these tests should have the immediate flag on. */ + testProps.setProperty(IMMEDIATE_PROPNAME, true); + testProps.setProperty(MANDATORY_PROPNAME, false); + + /** Bind the receivers consumer by default. */ + testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, true); + testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, true); + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/testcases/MandatoryMessageTest.java b/java/systests/src/main/java/org/apache/qpid/test/testcases/MandatoryMessageTest.java index 066b4e24ba..d46a866b93 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/testcases/MandatoryMessageTest.java +++ b/java/systests/src/main/java/org/apache/qpid/test/testcases/MandatoryMessageTest.java @@ -1,321 +1,321 @@ -/* - * - * 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.testcases; - -import org.apache.qpid.test.framework.AMQPPublisher; -import org.apache.qpid.test.framework.Circuit; -import org.apache.qpid.test.framework.FrameworkBaseCase; -import org.apache.qpid.test.framework.MessagingTestConfigProperties; -import static org.apache.qpid.test.framework.MessagingTestConfigProperties.*; -import org.apache.qpid.test.framework.sequencers.CircuitFactory; - -import org.apache.qpid.junit.extensions.util.ParsedProperties; -import org.apache.qpid.junit.extensions.util.TestContextProperties; - -/** - * MandatoryMessageTest tests for the desired behaviour of mandatory messages. Mandatory messages are a non-JMS - * feature. A message may be marked with a mandatory delivery flag, which means that a valid route for the message - * must exist, when it is sent, or when its transaction is committed in the case of transactional messaging. If this - * is not the case, the broker should return the message with a NO_CONSUMERS code. - * - *

- *
CRC Card
Responsibilities Collaborations - *
Check that an mandatory message is sent succesfully not using transactions when a consumer is connected. - *
Check that an mandatory message is committed succesfully in a transaction when a consumer is connected. - *
Check that a mandatory message is sent succesfully, not using transactions, when a consumer is disconnected - * but the route exists. - *
Check that a mandatory message is sent succesfully, in a transaction, when a consumer is disconnected but - * the route exists. - *
Check that an mandatory message results in no route code, not using transactions, when no consumer is - * connected. - *
Check that an mandatory message results in no route code, upon transaction commit, when a consumer is - * connected. - *
Check that an mandatory message is sent succesfully not using transactions when a consumer is connected. - *
Check that an mandatory message is committed succesfully in a transaction when a consumer is connected. - *
Check that a mandatory message is sent succesfully, not using transactions, when a consumer is disconnected - * but the route exists. - *
Check that a mandatory message is sent succesfully, in a transaction, when a consumer is disconnected but - * the route exists. - *
Check that an mandatory message results in no route code, not using transactions, when no consumer is - * connected. - *
Check that an mandatory message results in no route code, upon transaction commit, when a consumer is - * connected. - *
- * - * @todo All of these test cases will be generated by a test generator that thoroughly tests all combinations of test - * circuits. - */ -public class MandatoryMessageTest extends FrameworkBaseCase -{ - /** Used to read the tests configurable properties through. */ - ParsedProperties testProps; - - /** - * Creates a new test case with the specified name. - * - * @param name The test case name. - */ - public MandatoryMessageTest(String name) - { - super(name); - } - - /** Check that an mandatory message is sent succesfully not using transactions when a consumer is connected. */ - public void test_QPID_508_MandatoryOkNoTxP2P() - { - // Ensure transactional sessions are off. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); - testProps.setProperty(PUBSUB_PROPNAME, false); - - // Run the default test sequence over the test circuit checking for no errors. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); - } - - /** Check that an mandatory message is committed succesfully in a transaction when a consumer is connected. */ - public void test_QPID_508_MandatoryOkTxP2P() - { - // Ensure transactional sessions are off. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); - testProps.setProperty(PUBSUB_PROPNAME, false); - - // Run the default test sequence over the test circuit checking for no errors. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); - } - - /** - * Check that a mandatory message is sent succesfully, not using transactions, when a consumer is disconnected but - * the route exists. - */ - public void test_QPID_517_MandatoryOkConsumerDisconnectedNoTxP2P() - { - // Ensure transactional sessions are off. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); - testProps.setProperty(PUBSUB_PROPNAME, false); - - // Disconnect the consumer. - testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); - - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - // Send one message with no errors. - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); - } - - /** - * Check that a mandatory message is sent succesfully, in a transaction, when a consumer is disconnected but - * the route exists. - */ - public void test_QPID_517_MandatoryOkConsumerDisconnectedTxP2P() - { - // Ensure transactional sessions are on. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); - testProps.setProperty(PUBSUB_PROPNAME, false); - - // Disconnect the consumer. - testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); - - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - // Send one message with no errors. - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); - } - - /** Check that an mandatory message results in no route code, not using transactions, when no consumer is connected. */ - public void test_QPID_508_MandatoryFailsNoRouteNoTxP2P() - { - // Ensure transactional sessions are off. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); - testProps.setProperty(PUBSUB_PROPNAME, false); - - // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to - // collect its messages). - testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); - - // Send one message and get a linked no route exception. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); - } - - /** Check that an mandatory message results in no route code, upon transaction commit, when a consumer is connected. */ - public void test_QPID_508_MandatoryFailsNoRouteTxP2P() - { - // Ensure transactional sessions are on. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); - testProps.setProperty(PUBSUB_PROPNAME, false); - - // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to - // collect its messages). - testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); - - // Send one message and get a linked no route exception. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); - } - - /** Check that an mandatory message is sent succesfully not using transactions when a consumer is connected. */ - public void test_QPID_508_MandatoryOkNoTxPubSub() - { - // Ensure transactional sessions are off. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); - testProps.setProperty(PUBSUB_PROPNAME, true); - - // Run the default test sequence over the test circuit checking for no errors. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); - } - - /** Check that an mandatory message is committed succesfully in a transaction when a consumer is connected. */ - public void test_QPID_508_MandatoryOkTxPubSub() - { - // Ensure transactional sessions are on. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); - testProps.setProperty(PUBSUB_PROPNAME, true); - - // Run the default test sequence over the test circuit checking for no errors. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); - } - - /** - * Check that a mandatory message is sent succesfully, not using transactions, when a consumer is disconnected but - * the route exists. - */ - public void test_QPID_517_MandatoryOkConsumerDisconnectedNoTxPubSub() - { - // Ensure transactional sessions are off. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); - testProps.setProperty(PUBSUB_PROPNAME, true); - - // Use durable subscriptions, so that the route remains open with no subscribers. - testProps.setProperty(DURABLE_SUBSCRIPTION_PROPNAME, true); - - // Disconnect the consumer. - testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); - - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - // Send one message with no errors. - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); - } - - /** - * Check that a mandatory message is sent succesfully, in a transaction, when a consumer is disconnected but - * the route exists. - */ - public void test_QPID_517_MandatoryOkConsumerDisconnectedTxPubSub() - { - // Ensure transactional sessions are on. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); - testProps.setProperty(PUBSUB_PROPNAME, true); - - // Use durable subscriptions, so that the route remains open with no subscribers. - testProps.setProperty(DURABLE_SUBSCRIPTION_PROPNAME, true); - - // Disconnect the consumer. - testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); - - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - // Send one message with no errors. - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); - } - - /** Check that an mandatory message results in no route code, not using transactions, when no consumer is connected. */ - public void test_QPID_508_MandatoryFailsNoRouteNoTxPubSub() - { - // Ensure transactional sessions are off. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); - testProps.setProperty(PUBSUB_PROPNAME, true); - - // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to - // collect its messages). - testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); - - // Send one message and get a linked no route exception. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); - } - - /** Check that an mandatory message results in no route code, upon transaction commit, when a consumer is connected. */ - public void test_QPID_508_MandatoryFailsNoRouteTxPubSub() - { - // Ensure transactional sessions are on. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); - testProps.setProperty(PUBSUB_PROPNAME, true); - - // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to - // collect its messages). - testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); - - // Send one message and get a linked no route exception. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); - } - - protected void setUp() throws Exception - { - super.setUp(); - - testProps = TestContextProperties.getInstance(MessagingTestConfigProperties.defaults); - - /** All these tests should have the mandatory flag on. */ - testProps.setProperty(IMMEDIATE_PROPNAME, false); - testProps.setProperty(MANDATORY_PROPNAME, true); - - /** Bind the receivers consumer by default. */ - testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, true); - testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, true); - } -} +/* + * + * 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.testcases; + +import org.apache.qpid.test.framework.AMQPPublisher; +import org.apache.qpid.test.framework.Circuit; +import org.apache.qpid.test.framework.FrameworkBaseCase; +import org.apache.qpid.test.framework.MessagingTestConfigProperties; +import static org.apache.qpid.test.framework.MessagingTestConfigProperties.*; +import org.apache.qpid.test.framework.sequencers.CircuitFactory; + +import org.apache.qpid.junit.extensions.util.ParsedProperties; +import org.apache.qpid.junit.extensions.util.TestContextProperties; + +/** + * MandatoryMessageTest tests for the desired behaviour of mandatory messages. Mandatory messages are a non-JMS + * feature. A message may be marked with a mandatory delivery flag, which means that a valid route for the message + * must exist, when it is sent, or when its transaction is committed in the case of transactional messaging. If this + * is not the case, the broker should return the message with a NO_CONSUMERS code. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
Check that an mandatory message is sent succesfully not using transactions when a consumer is connected. + *
Check that an mandatory message is committed succesfully in a transaction when a consumer is connected. + *
Check that a mandatory message is sent succesfully, not using transactions, when a consumer is disconnected + * but the route exists. + *
Check that a mandatory message is sent succesfully, in a transaction, when a consumer is disconnected but + * the route exists. + *
Check that an mandatory message results in no route code, not using transactions, when no consumer is + * connected. + *
Check that an mandatory message results in no route code, upon transaction commit, when a consumer is + * connected. + *
Check that an mandatory message is sent succesfully not using transactions when a consumer is connected. + *
Check that an mandatory message is committed succesfully in a transaction when a consumer is connected. + *
Check that a mandatory message is sent succesfully, not using transactions, when a consumer is disconnected + * but the route exists. + *
Check that a mandatory message is sent succesfully, in a transaction, when a consumer is disconnected but + * the route exists. + *
Check that an mandatory message results in no route code, not using transactions, when no consumer is + * connected. + *
Check that an mandatory message results in no route code, upon transaction commit, when a consumer is + * connected. + *
+ * + * @todo All of these test cases will be generated by a test generator that thoroughly tests all combinations of test + * circuits. + */ +public class MandatoryMessageTest extends FrameworkBaseCase +{ + /** Used to read the tests configurable properties through. */ + ParsedProperties testProps; + + /** + * Creates a new test case with the specified name. + * + * @param name The test case name. + */ + public MandatoryMessageTest(String name) + { + super(name); + } + + /** Check that an mandatory message is sent succesfully not using transactions when a consumer is connected. */ + public void test_QPID_508_MandatoryOkNoTxP2P() + { + // Ensure transactional sessions are off. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); + testProps.setProperty(PUBSUB_PROPNAME, false); + + // Run the default test sequence over the test circuit checking for no errors. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); + } + + /** Check that an mandatory message is committed succesfully in a transaction when a consumer is connected. */ + public void test_QPID_508_MandatoryOkTxP2P() + { + // Ensure transactional sessions are off. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); + testProps.setProperty(PUBSUB_PROPNAME, false); + + // Run the default test sequence over the test circuit checking for no errors. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); + } + + /** + * Check that a mandatory message is sent succesfully, not using transactions, when a consumer is disconnected but + * the route exists. + */ + public void test_QPID_517_MandatoryOkConsumerDisconnectedNoTxP2P() + { + // Ensure transactional sessions are off. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); + testProps.setProperty(PUBSUB_PROPNAME, false); + + // Disconnect the consumer. + testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); + + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + // Send one message with no errors. + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); + } + + /** + * Check that a mandatory message is sent succesfully, in a transaction, when a consumer is disconnected but + * the route exists. + */ + public void test_QPID_517_MandatoryOkConsumerDisconnectedTxP2P() + { + // Ensure transactional sessions are on. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); + testProps.setProperty(PUBSUB_PROPNAME, false); + + // Disconnect the consumer. + testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); + + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + // Send one message with no errors. + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); + } + + /** Check that an mandatory message results in no route code, not using transactions, when no consumer is connected. */ + public void test_QPID_508_MandatoryFailsNoRouteNoTxP2P() + { + // Ensure transactional sessions are off. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); + testProps.setProperty(PUBSUB_PROPNAME, false); + + // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to + // collect its messages). + testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); + + // Send one message and get a linked no route exception. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); + } + + /** Check that an mandatory message results in no route code, upon transaction commit, when a consumer is connected. */ + public void test_QPID_508_MandatoryFailsNoRouteTxP2P() + { + // Ensure transactional sessions are on. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); + testProps.setProperty(PUBSUB_PROPNAME, false); + + // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to + // collect its messages). + testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); + + // Send one message and get a linked no route exception. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); + } + + /** Check that an mandatory message is sent succesfully not using transactions when a consumer is connected. */ + public void test_QPID_508_MandatoryOkNoTxPubSub() + { + // Ensure transactional sessions are off. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); + testProps.setProperty(PUBSUB_PROPNAME, true); + + // Run the default test sequence over the test circuit checking for no errors. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); + } + + /** Check that an mandatory message is committed succesfully in a transaction when a consumer is connected. */ + public void test_QPID_508_MandatoryOkTxPubSub() + { + // Ensure transactional sessions are on. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); + testProps.setProperty(PUBSUB_PROPNAME, true); + + // Run the default test sequence over the test circuit checking for no errors. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); + } + + /** + * Check that a mandatory message is sent succesfully, not using transactions, when a consumer is disconnected but + * the route exists. + */ + public void test_QPID_517_MandatoryOkConsumerDisconnectedNoTxPubSub() + { + // Ensure transactional sessions are off. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); + testProps.setProperty(PUBSUB_PROPNAME, true); + + // Use durable subscriptions, so that the route remains open with no subscribers. + testProps.setProperty(DURABLE_SUBSCRIPTION_PROPNAME, true); + + // Disconnect the consumer. + testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); + + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + // Send one message with no errors. + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); + } + + /** + * Check that a mandatory message is sent succesfully, in a transaction, when a consumer is disconnected but + * the route exists. + */ + public void test_QPID_517_MandatoryOkConsumerDisconnectedTxPubSub() + { + // Ensure transactional sessions are on. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); + testProps.setProperty(PUBSUB_PROPNAME, true); + + // Use durable subscriptions, so that the route remains open with no subscribers. + testProps.setProperty(DURABLE_SUBSCRIPTION_PROPNAME, true); + + // Disconnect the consumer. + testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, false); + + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + // Send one message with no errors. + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noExceptionsAssertion(testProps)))); + } + + /** Check that an mandatory message results in no route code, not using transactions, when no consumer is connected. */ + public void test_QPID_508_MandatoryFailsNoRouteNoTxPubSub() + { + // Ensure transactional sessions are off. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); + testProps.setProperty(PUBSUB_PROPNAME, true); + + // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to + // collect its messages). + testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); + + // Send one message and get a linked no route exception. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); + } + + /** Check that an mandatory message results in no route code, upon transaction commit, when a consumer is connected. */ + public void test_QPID_508_MandatoryFailsNoRouteTxPubSub() + { + // Ensure transactional sessions are on. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); + testProps.setProperty(PUBSUB_PROPNAME, true); + + // Set up the messaging topology so that only the publishers producer is bound (do not set up the receivers to + // collect its messages). + testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, false); + + // Send one message and get a linked no route exception. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(((AMQPPublisher) testCircuit.getPublisher()).noRouteAssertion(testProps)))); + } + + protected void setUp() throws Exception + { + super.setUp(); + + testProps = TestContextProperties.getInstance(MessagingTestConfigProperties.defaults); + + /** All these tests should have the mandatory flag on. */ + testProps.setProperty(IMMEDIATE_PROPNAME, false); + testProps.setProperty(MANDATORY_PROPNAME, true); + + /** Bind the receivers consumer by default. */ + testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, true); + testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, true); + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/testcases/RollbackTest.java b/java/systests/src/main/java/org/apache/qpid/test/testcases/RollbackTest.java index f39d22bc67..c1a484b2aa 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/testcases/RollbackTest.java +++ b/java/systests/src/main/java/org/apache/qpid/test/testcases/RollbackTest.java @@ -1,132 +1,132 @@ -/* - * - * 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.testcases; - -import org.apache.qpid.test.framework.Circuit; -import org.apache.qpid.test.framework.FrameworkBaseCase; -import org.apache.qpid.test.framework.MessagingTestConfigProperties; -import static org.apache.qpid.test.framework.MessagingTestConfigProperties.*; -import org.apache.qpid.test.framework.sequencers.CircuitFactory; - -import org.apache.qpid.junit.extensions.util.ParsedProperties; -import org.apache.qpid.junit.extensions.util.TestContextProperties; - -/** - * RollbackTest tests the rollback ability of transactional messaging. - * - *

- *
CRC Card
Responsibilities Collaborations - *
Check messages sent but rolled back are never received. - *
Check messages received but rolled back are redelivered on subsequent receives. - *
Attempting to rollback outside of a transaction results in an IllegalStateException. - *
- */ -public class RollbackTest extends FrameworkBaseCase -{ - /** Used to read the tests configurable properties through. */ - ParsedProperties testProps; - - /** - * Creates a new test case with the specified name. - * - * @param name The test case name. - */ - public RollbackTest(String name) - { - super(name); - } - - /** Check messages sent but rolled back are never received. */ - public void testRolledbackMessageNotDelivered() - { - // Ensure transactional sessions are on. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); - testProps.setProperty(ROLLBACK_PUBLISHER_PROPNAME, true); - - // Run the default test sequence over the test circuit checking for no errors. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(testCircuit.getPublisher().noExceptionsAssertion(testProps), - testCircuit.getReceiver().noMessagesReceivedAssertion(testProps)))); - } - - /** Check messages received but rolled back are redelivered on subsequent receives. */ - public void testRolledbackMessagesSubsequentlyReceived() - { - // Ensure transactional sessions are on. - testProps.setProperty(TRANSACTED_RECEIVER_PROPNAME, true); - testProps.setProperty(ROLLBACK_RECEIVER_PROPNAME, true); - - // Run the default test sequence over the test circuit checking for no errors. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, - assertionList(testCircuit.getPublisher().noExceptionsAssertion(testProps), - testCircuit.getReceiver().allMessagesReceivedAssertion(testProps)))); - } - - /** Attempting to rollback outside of a transaction results in an IllegalStateException. */ - public void testRollbackUnavailableOutsideTransactionPublisher() - { - // Ensure transactional sessions are on. - testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); - testProps.setProperty(ROLLBACK_PUBLISHER_PROPNAME, true); - - // Run the default test sequence over the test circuit checking for no errors. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, assertionList(testCircuit.getPublisher().channelClosedAssertion(testProps)))); - } - - /** Attempting to rollback outside of a transaction results in an IllegalStateException. */ - public void testRollbackUnavailableOutsideTransactionReceiver() - { - // Ensure transactional sessions are on. - testProps.setProperty(TRANSACTED_RECEIVER_PROPNAME, false); - testProps.setProperty(ROLLBACK_RECEIVER_PROPNAME, true); - - // Run the default test sequence over the test circuit checking for no errors. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - assertNoFailures(testCircuit.test(1, assertionList(testCircuit.getReceiver().channelClosedAssertion(testProps)))); - } - - /** - * Sets up all tests to have an active outward route and consumer by default. - * - * @throws Exception Any exceptions are allowed to fall through and fail the test. - */ - protected void setUp() throws Exception - { - super.setUp(); - - testProps = TestContextProperties.getInstance(MessagingTestConfigProperties.defaults); - - /** Bind the receivers consumer by default. */ - testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, true); - testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, true); - } -} +/* + * + * 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.testcases; + +import org.apache.qpid.test.framework.Circuit; +import org.apache.qpid.test.framework.FrameworkBaseCase; +import org.apache.qpid.test.framework.MessagingTestConfigProperties; +import static org.apache.qpid.test.framework.MessagingTestConfigProperties.*; +import org.apache.qpid.test.framework.sequencers.CircuitFactory; + +import org.apache.qpid.junit.extensions.util.ParsedProperties; +import org.apache.qpid.junit.extensions.util.TestContextProperties; + +/** + * RollbackTest tests the rollback ability of transactional messaging. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
Check messages sent but rolled back are never received. + *
Check messages received but rolled back are redelivered on subsequent receives. + *
Attempting to rollback outside of a transaction results in an IllegalStateException. + *
+ */ +public class RollbackTest extends FrameworkBaseCase +{ + /** Used to read the tests configurable properties through. */ + ParsedProperties testProps; + + /** + * Creates a new test case with the specified name. + * + * @param name The test case name. + */ + public RollbackTest(String name) + { + super(name); + } + + /** Check messages sent but rolled back are never received. */ + public void testRolledbackMessageNotDelivered() + { + // Ensure transactional sessions are on. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, true); + testProps.setProperty(ROLLBACK_PUBLISHER_PROPNAME, true); + + // Run the default test sequence over the test circuit checking for no errors. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(testCircuit.getPublisher().noExceptionsAssertion(testProps), + testCircuit.getReceiver().noMessagesReceivedAssertion(testProps)))); + } + + /** Check messages received but rolled back are redelivered on subsequent receives. */ + public void testRolledbackMessagesSubsequentlyReceived() + { + // Ensure transactional sessions are on. + testProps.setProperty(TRANSACTED_RECEIVER_PROPNAME, true); + testProps.setProperty(ROLLBACK_RECEIVER_PROPNAME, true); + + // Run the default test sequence over the test circuit checking for no errors. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, + assertionList(testCircuit.getPublisher().noExceptionsAssertion(testProps), + testCircuit.getReceiver().allMessagesReceivedAssertion(testProps)))); + } + + /** Attempting to rollback outside of a transaction results in an IllegalStateException. */ + public void testRollbackUnavailableOutsideTransactionPublisher() + { + // Ensure transactional sessions are on. + testProps.setProperty(TRANSACTED_PUBLISHER_PROPNAME, false); + testProps.setProperty(ROLLBACK_PUBLISHER_PROPNAME, true); + + // Run the default test sequence over the test circuit checking for no errors. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, assertionList(testCircuit.getPublisher().channelClosedAssertion(testProps)))); + } + + /** Attempting to rollback outside of a transaction results in an IllegalStateException. */ + public void testRollbackUnavailableOutsideTransactionReceiver() + { + // Ensure transactional sessions are on. + testProps.setProperty(TRANSACTED_RECEIVER_PROPNAME, false); + testProps.setProperty(ROLLBACK_RECEIVER_PROPNAME, true); + + // Run the default test sequence over the test circuit checking for no errors. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + assertNoFailures(testCircuit.test(1, assertionList(testCircuit.getReceiver().channelClosedAssertion(testProps)))); + } + + /** + * Sets up all tests to have an active outward route and consumer by default. + * + * @throws Exception Any exceptions are allowed to fall through and fail the test. + */ + protected void setUp() throws Exception + { + super.setUp(); + + testProps = TestContextProperties.getInstance(MessagingTestConfigProperties.defaults); + + /** Bind the receivers consumer by default. */ + testProps.setProperty(RECEIVER_CONSUMER_BIND_PROPNAME, true); + testProps.setProperty(RECEIVER_CONSUMER_ACTIVE_PROPNAME, true); + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/test/testcases/TTLTest.java b/java/systests/src/main/java/org/apache/qpid/test/testcases/TTLTest.java index f752ccba00..9004cb72df 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/testcases/TTLTest.java +++ b/java/systests/src/main/java/org/apache/qpid/test/testcases/TTLTest.java @@ -1,151 +1,151 @@ -/* - * - * 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.testcases; - -import org.apache.qpid.test.framework.Circuit; -import org.apache.qpid.test.framework.FrameworkBaseCase; -import static org.apache.qpid.test.framework.MessagingTestConfigProperties.ACK_MODE_PROPNAME; -import static org.apache.qpid.test.framework.MessagingTestConfigProperties.PUBSUB_PROPNAME; -import org.apache.qpid.test.framework.TestUtils; -import org.apache.qpid.test.framework.localcircuit.LocalCircuitImpl; -import org.apache.qpid.test.framework.sequencers.CircuitFactory; - -import javax.jms.*; - -import java.util.LinkedList; -import java.util.List; -import java.util.Random; - -/** - * TTLTest checks that time-to-live is applied to messages. The test sends messages with a variety of TTL stamps on them - * then after a pause attempts to receive those messages. Only messages with a large enough TTL to have survived the pause - * should be receiveable. This test case also applies an additional assertion against the broker, that the message store - * is empty at the end of the test. - * - *

This test is designed to run over local circuits only, as it must control a timed pause between sending and receiving - * messages to that TTL can be applied to purge some of the messages. - * - *

- *
CRC Card
Responsibilities Collaborations - *
- *
- * - * @todo Use an interface or other method to mark this test as local only. - * - * @todo Implement the message store assertion for in-vm broker. Could also be done for external broker, for example - * by using diagnostic exchange. - * - * @todo Implement and add a queue depth assertion too. This might already be in another test to copy from. - * - * @todo Create variations on test theme, for different ack mode and tx and message sizes etc. - * - * @todo Add an allowable margin of error to the test, as ttl may not be precise. - */ -public class TTLTest extends FrameworkBaseCase -{ - /** - * Creates a new test case with the specified name. - * - * @param name The test case name. - */ - public TTLTest(String name) - { - super(name); - } - - /** - * Checks that all messages sent with a TTL shorter than a pause between sending them and attempting to receive them - * will fail to arrive. Once all messages have been purged by TTL or received, check that they no longer exist on - * the broker. - * - * @throws javax.jms.JMSException Allowed to fall through and fail test. - */ - public void testTTLP2P() throws JMSException - { - String errorMessages = ""; - Random r = new Random(); - - // Used to accumulate correctly received messages in. - List receivedMessages = new LinkedList(); - - // Set up the test properties to match the test case requirements. - testProps.setProperty(ACK_MODE_PROPNAME, Session.AUTO_ACKNOWLEDGE); - testProps.setProperty(PUBSUB_PROPNAME, false); - - // Create the test circuit from the test configuration parameters. - CircuitFactory circuitFactory = getCircuitFactory(); - Circuit testCircuit = circuitFactory.createCircuit(testProps); - - // This test case assumes it is using a local circuit. - LocalCircuitImpl localCircuit = (LocalCircuitImpl) testCircuit; - - Session producerSession = localCircuit.getLocalPublisherCircuitEnd().getSession(); - MessageProducer producer = localCircuit.getLocalPublisherCircuitEnd().getProducer(); - MessageConsumer consumer = localCircuit.getLocalReceiverCircuitEnd().getConsumer(); - - // Send some tests messages, with random TTLs, some shorter and some longer than the pause time. - for (int i = 0; i < 100; i++) - { - Message testMessage = TestUtils.createTestMessageOfSize(producerSession, 10); - - // Set the TTL on the message and record its value in the message headers. - long ttl = 500 + r.nextInt(1500); - producer.setTimeToLive(ttl); - testMessage.setLongProperty("testTTL", ttl); - - producer.send(testMessage); - // producerSession.commit(); - } - - // Inject a pause to allow some messages to be purged by TTL. - TestUtils.pause(1000); - - // Attempt to receive back all of the messages, confirming by the message time stamps and TTLs that only - // those received should have avoided being purged by the TTL. - boolean timedOut = false; - - while (!timedOut) - { - Message testMessage = consumer.receive(1000); - - long ttl = testMessage.getLongProperty("testTTL"); - long timeStamp = testMessage.getJMSTimestamp(); - long now = System.currentTimeMillis(); - - if ((timeStamp + ttl) < now) - { - errorMessages += - "Received message [sent: " + timeStamp + ", ttl: " + ttl + ", received: " + now - + "] which should have been purged by its TTL.\n"; - } - /*else - { - receivedMessages.add(testMessage); - }*/ - } - - // Check that the queue and message store on the broker are empty. - // assertTrue("Message store is not empty.", messageStoreEmpty.apply()); - // assertTrue("Queue is not empty.", queueEmpty.apply()); - - assertTrue(errorMessages, "".equals(errorMessages)); - } -} +/* + * + * 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.testcases; + +import org.apache.qpid.test.framework.Circuit; +import org.apache.qpid.test.framework.FrameworkBaseCase; +import static org.apache.qpid.test.framework.MessagingTestConfigProperties.ACK_MODE_PROPNAME; +import static org.apache.qpid.test.framework.MessagingTestConfigProperties.PUBSUB_PROPNAME; +import org.apache.qpid.test.framework.TestUtils; +import org.apache.qpid.test.framework.localcircuit.LocalCircuitImpl; +import org.apache.qpid.test.framework.sequencers.CircuitFactory; + +import javax.jms.*; + +import java.util.LinkedList; +import java.util.List; +import java.util.Random; + +/** + * TTLTest checks that time-to-live is applied to messages. The test sends messages with a variety of TTL stamps on them + * then after a pause attempts to receive those messages. Only messages with a large enough TTL to have survived the pause + * should be receiveable. This test case also applies an additional assertion against the broker, that the message store + * is empty at the end of the test. + * + *

This test is designed to run over local circuits only, as it must control a timed pause between sending and receiving + * messages to that TTL can be applied to purge some of the messages. + * + *

+ *
CRC Card
Responsibilities Collaborations + *
+ *
+ * + * @todo Use an interface or other method to mark this test as local only. + * + * @todo Implement the message store assertion for in-vm broker. Could also be done for external broker, for example + * by using diagnostic exchange. + * + * @todo Implement and add a queue depth assertion too. This might already be in another test to copy from. + * + * @todo Create variations on test theme, for different ack mode and tx and message sizes etc. + * + * @todo Add an allowable margin of error to the test, as ttl may not be precise. + */ +public class TTLTest extends FrameworkBaseCase +{ + /** + * Creates a new test case with the specified name. + * + * @param name The test case name. + */ + public TTLTest(String name) + { + super(name); + } + + /** + * Checks that all messages sent with a TTL shorter than a pause between sending them and attempting to receive them + * will fail to arrive. Once all messages have been purged by TTL or received, check that they no longer exist on + * the broker. + * + * @throws javax.jms.JMSException Allowed to fall through and fail test. + */ + public void testTTLP2P() throws JMSException + { + String errorMessages = ""; + Random r = new Random(); + + // Used to accumulate correctly received messages in. + List receivedMessages = new LinkedList(); + + // Set up the test properties to match the test case requirements. + testProps.setProperty(ACK_MODE_PROPNAME, Session.AUTO_ACKNOWLEDGE); + testProps.setProperty(PUBSUB_PROPNAME, false); + + // Create the test circuit from the test configuration parameters. + CircuitFactory circuitFactory = getCircuitFactory(); + Circuit testCircuit = circuitFactory.createCircuit(testProps); + + // This test case assumes it is using a local circuit. + LocalCircuitImpl localCircuit = (LocalCircuitImpl) testCircuit; + + Session producerSession = localCircuit.getLocalPublisherCircuitEnd().getSession(); + MessageProducer producer = localCircuit.getLocalPublisherCircuitEnd().getProducer(); + MessageConsumer consumer = localCircuit.getLocalReceiverCircuitEnd().getConsumer(); + + // Send some tests messages, with random TTLs, some shorter and some longer than the pause time. + for (int i = 0; i < 100; i++) + { + Message testMessage = TestUtils.createTestMessageOfSize(producerSession, 10); + + // Set the TTL on the message and record its value in the message headers. + long ttl = 500 + r.nextInt(1500); + producer.setTimeToLive(ttl); + testMessage.setLongProperty("testTTL", ttl); + + producer.send(testMessage); + // producerSession.commit(); + } + + // Inject a pause to allow some messages to be purged by TTL. + TestUtils.pause(1000); + + // Attempt to receive back all of the messages, confirming by the message time stamps and TTLs that only + // those received should have avoided being purged by the TTL. + boolean timedOut = false; + + while (!timedOut) + { + Message testMessage = consumer.receive(1000); + + long ttl = testMessage.getLongProperty("testTTL"); + long timeStamp = testMessage.getJMSTimestamp(); + long now = System.currentTimeMillis(); + + if ((timeStamp + ttl) < now) + { + errorMessages += + "Received message [sent: " + timeStamp + ", ttl: " + ttl + ", received: " + now + + "] which should have been purged by its TTL.\n"; + } + /*else + { + receivedMessages.add(testMessage); + }*/ + } + + // Check that the queue and message store on the broker are empty. + // assertTrue("Message store is not empty.", messageStoreEmpty.apply()); + // assertTrue("Queue is not empty.", queueEmpty.apply()); + + assertTrue(errorMessages, "".equals(errorMessages)); + } +} diff --git a/java/systests/src/main/java/org/apache/qpid/testutil/QpidClientConnectionHelper.java b/java/systests/src/main/java/org/apache/qpid/testutil/QpidClientConnectionHelper.java index 398e3e7800..c43b65a805 100644 --- a/java/systests/src/main/java/org/apache/qpid/testutil/QpidClientConnectionHelper.java +++ b/java/systests/src/main/java/org/apache/qpid/testutil/QpidClientConnectionHelper.java @@ -1,296 +1,296 @@ -/* - * - * 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.testutil; - -import org.apache.log4j.Logger; - -import org.apache.qpid.client.AMQConnection; -import org.apache.qpid.client.AMQConnectionFactory; -import org.apache.qpid.client.AMQConnectionURL; -import org.apache.qpid.client.JMSAMQException; -import org.apache.qpid.url.URLSyntaxException; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.ExceptionListener; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TextMessage; - -/** - * @todo This was originally cut and paste from the client module leading to a duplicate class, then altered very - * slightly. To avoid the duplicate class the name was altered slightly to have 'Helper' on the end in order - * to distinguish it from the original. Delete this class and use the original instead, just upgrade it to - * provide the new features needed. - */ -public class QpidClientConnectionHelper implements ExceptionListener -{ - - private static final Logger _logger = Logger.getLogger(QpidClientConnectionHelper.class); - - private boolean transacted = true; - private int ackMode = Session.CLIENT_ACKNOWLEDGE; - private Connection connection; - - private String virtualHost; - private String brokerlist; - private int prefetch; - protected Session session; - protected boolean connected; - - public QpidClientConnectionHelper(String broker) - { - super(); - setVirtualHost("/test"); - setBrokerList(broker); - setPrefetch(5000); - } - - public void connect() throws JMSException - { - if (!connected) - { - /* - * amqp://[user:pass@][clientid]/virtualhost? - * brokerlist='[transport://]host[:port][?option='value'[&option='value']];' - * [&failover='method[?option='value'[&option='value']]'] - * [&option='value']" - */ - String brokerUrl = "amqp://guest:guest@" + virtualHost + "?brokerlist='" + brokerlist + "'"; - try - { - AMQConnectionFactory factory = new AMQConnectionFactory(new AMQConnectionURL(brokerUrl)); - _logger.info("connecting to Qpid :" + brokerUrl); - connection = factory.createConnection(); - - // register exception listener - connection.setExceptionListener(this); - - session = ((AMQConnection) connection).createSession(transacted, ackMode, prefetch); - - _logger.info("starting connection"); - connection.start(); - - connected = true; - } - catch (URLSyntaxException e) - { - throw new JMSAMQException("URL syntax error in [" + brokerUrl + "]: " + e.getMessage(), e); - } - } - } - - public void disconnect() throws JMSException - { - if (connected) - { - session.commit(); - session.close(); - connection.close(); - connected = false; - _logger.info("disconnected"); - } - } - - public void disconnectWithoutCommit() throws JMSException - { - if (connected) - { - session.close(); - connection.close(); - connected = false; - _logger.info("disconnected without commit"); - } - } - - public String getBrokerList() - { - return brokerlist; - } - - public void setBrokerList(String brokerlist) - { - this.brokerlist = brokerlist; - } - - public String getVirtualHost() - { - return virtualHost; - } - - public void setVirtualHost(String virtualHost) - { - this.virtualHost = virtualHost; - } - - public void setPrefetch(int prefetch) - { - this.prefetch = prefetch; - } - - /** override as necessary */ - public void onException(JMSException exception) - { - _logger.info("ExceptionListener event: error " + exception.getErrorCode() + ", message: " + exception.getMessage()); - } - - public boolean isConnected() - { - return connected; - } - - public Session getSession() - { - return session; - } - - /** - * Put a String as a text messages, repeat n times. A null payload will result in a null message. - * - * @param queueName The queue name to put to - * @param payload the content of the payload - * @param copies the number of messages to put - * - * @throws javax.jms.JMSException any exception that occurs - */ - public void put(String queueName, String payload, int copies, int deliveryMode) throws JMSException - { - if (!connected) - { - connect(); - } - - _logger.info("putting to queue " + queueName); - Queue queue = session.createQueue(queueName); - - final MessageProducer sender = session.createProducer(queue); - - sender.setDeliveryMode(deliveryMode); - - for (int i = 0; i < copies; i++) - { - Message m = session.createTextMessage(payload + i); - m.setIntProperty("index", i + 1); - sender.send(m); - } - - session.commit(); - sender.close(); - _logger.info("put " + copies + " copies"); - } - - /** - * GET the top message on a queue. Consumes the message. Accepts timeout value. - * - * @param queueName The quename to get from - * @param readTimeout The timeout to use - * - * @return the content of the text message if any - * - * @throws javax.jms.JMSException any exception that occured - */ - public Message getNextMessage(String queueName, long readTimeout) throws JMSException - { - if (!connected) - { - connect(); - } - - Queue queue = session.createQueue(queueName); - - final MessageConsumer consumer = session.createConsumer(queue); - - Message message = consumer.receive(readTimeout); - session.commit(); - consumer.close(); - - Message result; - - // all messages we consume should be TextMessages - if (message instanceof TextMessage) - { - result = ((TextMessage) message); - } - else if (null == message) - { - result = null; - } - else - { - _logger.info("warning: received non-text message"); - result = message; - } - - return result; - } - - /** - * GET the top message on a queue. Consumes the message. - * - * @param queueName The Queuename to get from - * - * @return The string content of the text message, if any received - * - * @throws javax.jms.JMSException any exception that occurs - */ - public Message getNextMessage(String queueName) throws JMSException - { - return getNextMessage(queueName, 0); - } - - /** - * Completely clears a queue. For readTimeout behaviour see Javadocs for javax.jms.MessageConsumer. - * - * @param queueName The Queue name to consume from - * @param readTimeout The timeout for each consume - * - * @throws javax.jms.JMSException Any exception that occurs during the consume - * @throws InterruptedException If the consume thread was interrupted during a consume. - */ - public void consume(String queueName, int readTimeout) throws JMSException, InterruptedException - { - if (!connected) - { - connect(); - } - - _logger.info("consuming queue " + queueName); - Queue queue = session.createQueue(queueName); - - final MessageConsumer consumer = session.createConsumer(queue); - int messagesReceived = 0; - - _logger.info("consuming..."); - while ((consumer.receive(readTimeout)) != null) - { - messagesReceived++; - } - - session.commit(); - consumer.close(); - _logger.info("consumed: " + messagesReceived); - } -} +/* + * + * 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.testutil; + +import org.apache.log4j.Logger; + +import org.apache.qpid.client.AMQConnection; +import org.apache.qpid.client.AMQConnectionFactory; +import org.apache.qpid.client.AMQConnectionURL; +import org.apache.qpid.client.JMSAMQException; +import org.apache.qpid.url.URLSyntaxException; + +import javax.jms.Connection; +import javax.jms.DeliveryMode; +import javax.jms.ExceptionListener; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Queue; +import javax.jms.Session; +import javax.jms.TextMessage; + +/** + * @todo This was originally cut and paste from the client module leading to a duplicate class, then altered very + * slightly. To avoid the duplicate class the name was altered slightly to have 'Helper' on the end in order + * to distinguish it from the original. Delete this class and use the original instead, just upgrade it to + * provide the new features needed. + */ +public class QpidClientConnectionHelper implements ExceptionListener +{ + + private static final Logger _logger = Logger.getLogger(QpidClientConnectionHelper.class); + + private boolean transacted = true; + private int ackMode = Session.CLIENT_ACKNOWLEDGE; + private Connection connection; + + private String virtualHost; + private String brokerlist; + private int prefetch; + protected Session session; + protected boolean connected; + + public QpidClientConnectionHelper(String broker) + { + super(); + setVirtualHost("/test"); + setBrokerList(broker); + setPrefetch(5000); + } + + public void connect() throws JMSException + { + if (!connected) + { + /* + * amqp://[user:pass@][clientid]/virtualhost? + * brokerlist='[transport://]host[:port][?option='value'[&option='value']];' + * [&failover='method[?option='value'[&option='value']]'] + * [&option='value']" + */ + String brokerUrl = "amqp://guest:guest@" + virtualHost + "?brokerlist='" + brokerlist + "'"; + try + { + AMQConnectionFactory factory = new AMQConnectionFactory(new AMQConnectionURL(brokerUrl)); + _logger.info("connecting to Qpid :" + brokerUrl); + connection = factory.createConnection(); + + // register exception listener + connection.setExceptionListener(this); + + session = ((AMQConnection) connection).createSession(transacted, ackMode, prefetch); + + _logger.info("starting connection"); + connection.start(); + + connected = true; + } + catch (URLSyntaxException e) + { + throw new JMSAMQException("URL syntax error in [" + brokerUrl + "]: " + e.getMessage(), e); + } + } + } + + public void disconnect() throws JMSException + { + if (connected) + { + session.commit(); + session.close(); + connection.close(); + connected = false; + _logger.info("disconnected"); + } + } + + public void disconnectWithoutCommit() throws JMSException + { + if (connected) + { + session.close(); + connection.close(); + connected = false; + _logger.info("disconnected without commit"); + } + } + + public String getBrokerList() + { + return brokerlist; + } + + public void setBrokerList(String brokerlist) + { + this.brokerlist = brokerlist; + } + + public String getVirtualHost() + { + return virtualHost; + } + + public void setVirtualHost(String virtualHost) + { + this.virtualHost = virtualHost; + } + + public void setPrefetch(int prefetch) + { + this.prefetch = prefetch; + } + + /** override as necessary */ + public void onException(JMSException exception) + { + _logger.info("ExceptionListener event: error " + exception.getErrorCode() + ", message: " + exception.getMessage()); + } + + public boolean isConnected() + { + return connected; + } + + public Session getSession() + { + return session; + } + + /** + * Put a String as a text messages, repeat n times. A null payload will result in a null message. + * + * @param queueName The queue name to put to + * @param payload the content of the payload + * @param copies the number of messages to put + * + * @throws javax.jms.JMSException any exception that occurs + */ + public void put(String queueName, String payload, int copies, int deliveryMode) throws JMSException + { + if (!connected) + { + connect(); + } + + _logger.info("putting to queue " + queueName); + Queue queue = session.createQueue(queueName); + + final MessageProducer sender = session.createProducer(queue); + + sender.setDeliveryMode(deliveryMode); + + for (int i = 0; i < copies; i++) + { + Message m = session.createTextMessage(payload + i); + m.setIntProperty("index", i + 1); + sender.send(m); + } + + session.commit(); + sender.close(); + _logger.info("put " + copies + " copies"); + } + + /** + * GET the top message on a queue. Consumes the message. Accepts timeout value. + * + * @param queueName The quename to get from + * @param readTimeout The timeout to use + * + * @return the content of the text message if any + * + * @throws javax.jms.JMSException any exception that occured + */ + public Message getNextMessage(String queueName, long readTimeout) throws JMSException + { + if (!connected) + { + connect(); + } + + Queue queue = session.createQueue(queueName); + + final MessageConsumer consumer = session.createConsumer(queue); + + Message message = consumer.receive(readTimeout); + session.commit(); + consumer.close(); + + Message result; + + // all messages we consume should be TextMessages + if (message instanceof TextMessage) + { + result = ((TextMessage) message); + } + else if (null == message) + { + result = null; + } + else + { + _logger.info("warning: received non-text message"); + result = message; + } + + return result; + } + + /** + * GET the top message on a queue. Consumes the message. + * + * @param queueName The Queuename to get from + * + * @return The string content of the text message, if any received + * + * @throws javax.jms.JMSException any exception that occurs + */ + public Message getNextMessage(String queueName) throws JMSException + { + return getNextMessage(queueName, 0); + } + + /** + * Completely clears a queue. For readTimeout behaviour see Javadocs for javax.jms.MessageConsumer. + * + * @param queueName The Queue name to consume from + * @param readTimeout The timeout for each consume + * + * @throws javax.jms.JMSException Any exception that occurs during the consume + * @throws InterruptedException If the consume thread was interrupted during a consume. + */ + public void consume(String queueName, int readTimeout) throws JMSException, InterruptedException + { + if (!connected) + { + connect(); + } + + _logger.info("consuming queue " + queueName); + Queue queue = session.createQueue(queueName); + + final MessageConsumer consumer = session.createConsumer(queue); + int messagesReceived = 0; + + _logger.info("consuming..."); + while ((consumer.receive(readTimeout)) != null) + { + messagesReceived++; + } + + session.commit(); + consumer.close(); + _logger.info("consumed: " + messagesReceived); + } +} -- cgit v1.2.1